Global Live Video Streaming Platform

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a consumer live-video platform where creators broadcast real-time video and audio to global audiences while viewers watch and chat together. A single creator produces one live feed that may be watched simultaneously by anywhere from a handful of fans to millions of concurrent viewers during flagship events.

Design for the following product capabilities, operating targets, and boundaries:

  • Core product features: Real-time broadcast ingestion; adaptive multi-bitrate video playback (1080p down to 360p) so constrained networks degrade gracefully; live channel chat; browsing and searching active broadcasts; and automatic recording into on-demand video (VOD) retained for 30 days after a broadcast concludes.
  • Traffic & latency targets: Support 50M daily users, 100,000 simultaneous active broadcasts (averaging 2 hours each), and 10M concurrent viewers at peak—including single viral channels exceeding 1M–2M simultaneous viewers. Keep end-to-end video lag below 10 seconds and chat message delivery under 1 second.
  • Reliability & scope boundaries: Scale horizontally across every tier and keep active broadcasts resilient against transient network blips or single-server crashes. Treat subscription billing, ML moderation classifiers, mobile client UI, and login/authentication internals as out of scope.

Scope & Expectations

  • Capacity & bandwidth estimation: Quantify ingest vs. egress video throughput, real-time encoding compute, petabyte-scale VOD storage, and peak chat fan-out rates.
  • Media pipeline & CDN delivery: Detail broadcast ingestion, keyframe-aligned multi-rendition transcoding, segment packaging, and tiered CDN caching that stays within the 10-second latency budget.
  • Real-time chat & discovery: Show how WebSocket chat scales from small rooms to million-viewer broadcasts without overwhelming servers or human readers, alongside live stream discovery.
  • VOD recording & fault tolerance: Explain how live media becomes playable VOD cost-effectively and how the platform recovers cleanly from uplink, encoder, origin, or CDN failures.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Live streaming looks like one product on screen, but under the hood it combines two opposite distributed systems:

    1. Live video (write-once, read-millions): one broadcaster uploads a single video feed, and millions of viewers download it within a strict 10-second latency budget. Video is huge in bytes, so bandwidth and video encoding dominate the architecture and the cloud bill.
    2. Live chat (write-thousands, read-millions): tiny text messages (~100 bytes each) arrive from thousands of viewers at once and must appear on millions of screens in under 1 second. Bytes are tiny, so connection count and message fan-out (copying one incoming message to every viewer) dominate.

    Functional requirements

    • Broadcast: broadcasters start a live stream and push video and audio in real time.
    • Adaptive playback: viewers watch with a few seconds of delay across multiple renditions (copies of the same stream at different resolutions and bitrates, such as 1080p, 720p, 480p, and 360p) so slow connections step down in quality instead of freezing.
    • Live chat: viewers send and read real-time chat messages alongside each stream.
    • Discovery: viewers browse top live streams by category and search active channels.
    • VOD (Video on Demand): live streams are recorded so viewers can replay them after the broadcast ends.

    Non-functional requirements

    • Massive single-stream concurrency: up to 2 million concurrent viewers on a single viral stream, and 10 million concurrent viewers platform-wide at peak.
    • Glass-to-glass video delay below 10 seconds (from the broadcaster's camera lens to the viewer's screen).
    • High availability: brief network hiccups or single-server crashes must not drop an active broadcast, and every layer scales horizontally.
    • Real-time chat: sub-second delivery for active chat rooms.

    Clarifying assumptions to state out loud

    • Ingest format: broadcasters push up to 1080p at 60 fps (6 Mbps) using RTMP (Real-Time Messaging Protocol, the standard TCP streaming protocol supported by tools like OBS) or SRT (Secure Reliable Transport, a UDP protocol that recovers lost packets cleanly on shaky mobile uplinks), configured with a keyframe every 2 seconds.
    • Latency tiers: < 10 s standard latency for all streams over ordinary CDNs (Content Delivery Networks — globally distributed caches close to users), plus an optional ~3–4 s low-latency mode for interactive streams. Sub-second video-call latency is out of scope (covered in follow-ups).
    • Chat delivery: best-effort display in massive rooms (dropping non-moderator messages above human reading speed is expected), while storing every accepted message durably for moderation and VOD chat replay.
    • VOD retention: 30 days by default unless the broadcaster marks a video as a permanent highlight.
    • Out of scope: payments/subscriptions, ML content moderation models, mobile UI specifics, and login/auth internals.
  2. Back-of-the-envelope numbers

    Starting from our operating targets (50M daily users, 100,000 simultaneous active broadcasts, and 10M concurrent viewers at peak), derive the throughput, compute, and storage figures that govern each subsystem:

    1. Video bandwidth
       Bitrate ladder per stream   1080p (6.0) + 720p (3.0) + 480p (1.5) + 360p (0.8) = 11.3 Mbps (~1.88x source)
       Ingest (broadcasters -> us) 100,000 streams x 6 Mbps            = 600 Gbps
       Egress (edges -> viewers)   10,000,000 viewers x 3 Mbps average = 30 Tbps
       Single 2M-viewer stream     2,000,000 viewers x 3 Mbps          = 6 Tbps leaving CDN edges
    
    2. How CDN caching collapses origin bandwidth (for that 2M-viewer stream)
       Origin -> 10 regional shields (all 4 renditions): 10 x 11.3 Mbps = 113 Mbps leaving our origin
       Bandwidth reduction ratio:                        6 Tbps / 113 Mbps ~ 53,000x!
    
    3. Video segments and HTTP request rate (using 2-second segments)
       2 s segment file size       6 Mbps x 2 s = 12 Mb = 1.5 MB (1080p); 3 Mbps x 2 s = 0.75 MB (720p)
       Segments created at peak    100,000 streams x 4 renditions / 2 s = 200,000 segments/s
       Viewer HTTP requests        10M viewers x (1 segment + 1 playlist refresh) / 2 s = 10M req/s at CDN edges
    
    4. Transcoding compute (converting 1080p into 720p + 480p + 360p in real time)
       1 GPU encode server         ~20 live streams in real time
       Full ladder for all 100k    100,000 / 20 = 5,000 GPU servers (our biggest compute bill)
    
    5. VOD storage (6 Mbps = 0.75 MB/s = 2.7 GB/hour raw; full ladder = ~5.1 GB/hour)
       Baseline volume (100k broadcasts/day x 2 h = 200k broadcast-hours/day):
         540 TB/day raw -> ~1.0 PB/day with all renditions -> ~30 PB for 30 days
       Continuous-concurrency check (if 100k is peak and daily avg is 40k concurrent x 24 h = 960k stream-hours/day):
         ~2.6 PB/day raw -> ~4.9 PB/day with ladder -> ~147 PB for 30 days!
    
    6. Live chat (assuming 10% of viewers send 1 message/minute)
       Open connections            10M WebSockets / 50,000 per gateway = 200 gateways (~260 with AZ headroom)
       Platform inbound chat       1M active chatters / 60 s = ~16,700 msg/s
       Average room (100 viewers)  10 chatters -> 0.17 msg/s x 100 viewers = ~17 deliveries/s (easy)
       Viral room (2M viewers)     200,000 chatters -> 3,333 msg/s in;
                                   naive full fan-out = 3,333 x 2,000,000 = 6.7 BILLION deliveries/s (impossible!)
    
    7. Discovery & viewer telemetry
       Browse queries              50M DAU x 10 views/day -> ~5,800 req/s avg (~17,000 req/s peak, CDN-cacheable)
       Player heartbeat beacons    10M viewers / 30 s interval = ~333,000 beacons/s
    

    Four architectural rules jump straight out of this math:

    • No origin data center can push 30 Tbps: video delivery must be pure HTTP files cached across multiple commercial CDNs, with our origin serving only a handful of regional cache shields.
    • Transcoding 100,000 streams blindly wastes thousands of GPUs: most streams have fewer than 5 viewers, so encoding policies should adapt to audience size.
    • VOD storage is 30–150 PB/month: how we write segments to object storage and how aggressively we age out unwatched recordings directly determine storage cost.
    • Chat must change strategy by room size: broadcasting 3,333 messages/s to 2M people is neither human-readable nor network-feasible, so massive rooms need bounded sampling.
  3. API and playback protocol

    Video bytes never pass through JSON API servers: broadcasters push media to dedicated ingest servers, and viewers pull HLS (HTTP Live Streaming, Apple's universal streaming standard where video is sliced into tiny .m4s segment files listed in a text .m3u8 playlist) directly from CDN edges.

    Broadcaster control & media push
      POST  /v1/channels/{channel_id}/stream-key:rotate  -> {"stream_key": "live_8a1f..."}
      RTMP  rtmp://ingest.example.com/live/{stream_key}  (or SRT; stream_key authenticates the push)
      PATCH /v1/streams/{stream_id}                      {"title": "Grandmaster Blitz Finals", "category_id": 512}
      POST  /v1/streams/{stream_id}/end                  (or stop pushing; auto-ends after 90 s grace window)
    
    Viewer discovery, playback & telemetry
      GET   /v1/streams?category=512&cursor=...&limit=30 -> top live streams by viewer count (CDN-cached 10 s)
      GET   /v1/streams/{stream_id}
        200 {"status": "LIVE", "title": "...", "viewers": 18234, "latency_mode": "standard",
             "playback": {
               "master": "https://cdn-a.example.com/live/{stream_id}/master.m3u8?token=...",
               "alternates": ["https://cdn-b.example.com/live/{stream_id}/master.m3u8?token=..."]
             },
             "chat": {"url": "wss://chat.example.com/v1/rooms/{stream_id}", "token": "..."}}
    
      GET   {cdn}/live/{stream_id}/master.m3u8            lists available renditions (bandwidth + resolution)
      GET   {cdn}/live/{stream_id}/{rendition}/index.m3u8 sliding window of the latest ~6 segments
      GET   {cdn}/live/{stream_id}/{rendition}/{seq}.m4s  immutable 2-second fMP4 video/audio segment
      POST  /v1/playback/beacons                          sent every 30 s: {stream_id, session_id, rendition, stalls}
    
    Live chat (WebSocket JSON frames)
      client -> {"type": "send", "client_msg_id": "m-42", "text": "Brilliant sacrifice!"}
      server -> {"type": "ack", "client_msg_id": "m-42", "seq": 18213}
              | {"type": "rejected", "client_msg_id": "m-42", "reason": "slow_mode", "retry_after_s": 30}
      server -> {"type": "batch", "messages": [{"seq": 18211, "user": "maya", "text": "gg"}, ...]}
      client -> {"type": "resume", "last_seq": 18190}    sent on reconnect to fill brief gaps
    
    VOD replay
      GET   /v1/vods/{vod_id}                             signed VOD master.m3u8 URL, duration, chat replay URL
    

    Why each endpoint is shaped this way:

    • Edge-verified tokens, shared CDN cache: the query token on master.m3u8 proves authorization at the CDN edge using a local HMAC signature check (zero calls back to our servers), and the CDN strips token from its cache key so 2 million viewers still hit the exact same cached segment file.
    • Built-in CDN failover: returning alternates lets the video player automatically switch from cdn-a to cdn-b if segment downloads stall, without hitting our control API during an outage.
    • client_msg_id (idempotency key): an idempotency key is a unique client-generated tag so that if a viewer's Wi-Fi drops right after sending a chat message and the app retries, the server returns the original seq instead of posting the message twice.
  4. Data model and segment bundling

    Different parts of the platform have very different read/write patterns, so each lives in the store suited to its workload:

    1. Relational metadata (PostgreSQL: primary + read replicas; ~100k active rows, low write rate)
       channels      (channel_id PK, owner_user_id, stream_key_hash, transcode_policy, latency_mode)
       streams       (stream_id PK, channel_id, status [STARTING|LIVE|RECONNECTING|ENDED], title,
                      category_id, started_at, ended_at, ingest_region, packager_pair, ladder_json)
       vod_assets    (vod_id PK, stream_id, status [BUILDING|READY|ARCHIVED|DELETED], duration_s,
                      playlist_key, thumbnails_key, storage_class, expires_at, views_7d)
    
    2. Live segment ring buffer (in-memory on Packager servers; rolling last ~60 seconds per rendition)
       live_index    (stream_id, rendition) -> deque of {seq, duration_s, wall_time, bytes, bundle_offset}
    
    3. Chat history (Wide-column store such as Cassandra/ScyllaDB — partitions data across nodes by key)
       chat_messages partition key: (stream_id, minute_bucket), clustering key: seq ASC
                     columns: user_id, text, is_staff, sent_at, deleted
    
    4. Live viewer counts & discovery rankings (Redis — in-memory key-value and sorted-set store)
       viewers:{stream_id}           STRING      approximate concurrent viewers (updated every 10 s)
       live_category:{category_id}   SORTED SET  score = viewer_count, member = stream_id
    
    5. Object storage (S3 / GCS — durable petabyte blob store)
       live/{stream_id}/{rendition}/{minute}.mp4   1-minute concatenated segment bundles + byte-offset index
       vod/{vod_id}/...                            VOD playlists, sprite-sheet thumbnails, re-encoded renditions
    

    Two storage choices prevent classic production disasters:

    • Bundle 2-second segments into 1-minute objects before writing to S3: writing every 2-second segment across 4 renditions as its own S3 object produces 200,000 PUTs/s at peak (~7 billion PUTs/day at 40% average concurrency). Cloud object stores charge around $5 per million PUT requests — that would burn ~$35,000 every single day in request fees alone! Because our packager already holds the last 60 seconds in RAM to serve live shields, it concatenates thirty 2-second segments into one 1-minute .mp4 bundle and uploads once per minute (30x fewer PUTs, ~$1,150/day). HLS supports byte-range addressing (#EXT-X-BYTERANGE:length@offset), so VOD playlists point directly at exact 2-second slices inside each 1-minute bundle with zero re-cutting!
    • Bucket chat partitions by (stream_id, minute_bucket): in a 2M-viewer room receiving 3,333 messages/s (200,000 messages/minute), a single partition per stream_id (or even per hour) would grow into multi-gigabyte hot partitions. Bucketing by minute keeps every partition to at most ~200k rows x 200 B = ~40 MB and makes VOD chat replay ("fetch minute 42 of stream X") a single sequential partition read.
  5. High-level architecture

     Broadcaster (OBS / Mobile App)
          |  RTMP or SRT push (1080p @ 6 Mbps + stream_key)
          v
     [ Ingest PoPs (~15 global locations) ] ---- auth & lifecycle ----> [ Stream Metadata Service (Postgres) ]
          |  internal backbone relay                                              |
          v                                                                       v
     [ Regional Transcoder Cluster (GPUs) ]                             [ Discovery & Search API ]
       decode once -> encode 720p/480p/360p                               (CDN-cached 10 s; Redis ZSETs)
       aligned keyframes every 2.0 s
          |  4 renditions
          v
     [ Packager / Origin Pair (Primary + AZ Replica) ] --- 1-min bundles ---> [ S3 Object Storage ]
       in-memory 60 s ring buffer + .m3u8 playlists                                   |
          |  ~113 Mbps per viral stream                                               v
          v                                                                   [ Async VOD Pipeline ]
     [ Regional Origin Shields (~10 per CDN, coalescing ON) ]                   instant byte-range .m3u8,
          |                                                                     thumbnails, lifecycle tiering
          v
     [ Multi-CDN Edge PoPs (CDN A + CDN B, coalescing ON) ]
          |  30 Tbps total HLS (.m3u8 + .m4s)
          v
     Viewers' Video Players (Adaptive Bitrate) ---- 30 s beacons ----> [ Beacon Collector -> Kafka -> Flink ]
                                                                          updates viewer counts & CDN health
    
     Viewers' Chat UI <== WebSockets (10M) ==> [ Chat Gateways (~260) ] ---> [ Stateless Chat Ingest ]
                                                       ^                       auth, bans, slow-mode, filters
                                                       | 200 ms batches                 |
                                               [ Room Owners (sharded) ] <--------------+
                                                 assign seq, sample <=20 msg/s, 30 s replay buffer
                                                       |
                                                       v
                                               [ Kafka ] ---> [ Wide-Column Chat Store ]
    

    How the four paths stay isolated:

    • Video path: Ingest -> Transcoder -> Packager -> Origin Shield -> CDN Edge -> Player. Streams map to one transcoder and one primary/replica packager pair via consistent hashing (hashing stream_id onto a ring of servers so adding or losing a server moves only 1/N of active streams).
    • Chat path: completely separate servers and sockets so an emoji flood in a 2M-viewer room can never delay video segments.
    • Discovery path: served from Redis sorted sets and cached at the CDN for 10 seconds so millions of home-page refreshes barely touch backend databases.
    • Measurement path: 333,000 player beacons/s flow through Kafka (a partitioned, disk-backed event stream) into a stream processor (such as Flink) to compute live viewer counts and per-CDN stall rates.
  6. Deep dive 1: the video pipeline and the 10-second latency budget

    Why keyframes govern both quality switching and latency. Raw 1080p60 video is ~3 Gbps; H.264 compresses it to 6 Mbps by sending one complete self-contained image called a keyframe (or I-frame) every 2 seconds, followed by 119 tiny delta frames that only say "move these pixels slightly from the previous frame." Because delta frames are useless without the preceding keyframe:

    1. Every .m4s segment must start with a keyframe so a new viewer can begin playing immediately.
    2. Every rendition (1080p, 720p, 480p, 360p) must place keyframes at the exact same timestamps (0.0 s, 2.0 s, 4.0 s, ...) so a player can drop from 1080p segment #14 to 480p segment #15 with zero visual glitch.

    If the broadcaster sends clean 2-second keyframes, the transcoder passes the 1080p source straight through without re-encoding (saving the most expensive encode) and encodes 720p, 480p, and 360p on aligned 2-second boundaries. If the broadcaster's keyframes are irregular, the transcoder re-encodes 1080p too to enforce 2-second alignment.

    Where the 10-second latency budget actually goes. A common mistake is thinking network travel time causes live-stream lag. Network transfer takes milliseconds; segment buffering causes seconds of lag. By the HLS specification (RFC 8216), a player starts 3 target segment durations behind the end of the playlist so a momentary 2-second Wi-Fi hiccup drains the player's local buffer instead of stalling playback:

    Wall clock t = 21.0 s: Packager just finished segment #10 covering video [18.0 s .. 20.0 s]
      Live playlist index.m3u8 lists: ... #8 [14..16s], #9 [16..18s], #10 [18..20s]
                                           ^
                                           Player starts HERE (3 x 2 s = 6.0 s behind 20.0 s!)
    
    Latency breakdown                      Standard HLS (2 s segments)   Low-Latency HLS (0.5 s parts)
    -------------------------------------  ---------------------------   -----------------------------
    Broadcaster capture, encode & upload             ~1.0 s                         ~1.0 s
    Transcode + package + shield/edge                ~1.0 s                         ~0.8 s
    Playlist age when viewer loads it          0.0 - 2.5 s (avg ~1.25 s)            ~0.3 s (blocking reload)
    Player 3-unit safety buffer                      6.0 s (3 x 2.0 s)              ~1.5 s (3 x 0.5 s parts)
    Player download + decode                         ~0.5 s                         ~0.3 s
    -------------------------------------  ---------------------------   -----------------------------
    Initial glass-to-glass latency             8.5 - 11.0 s (avg ~9.75 s)           ~3.9 s
    Steady state with player catch-up                ~8.0 - 8.5 s                   ~3.5 s
    

    Notice three critical consequences:

    • 6-second segments fail immediately: 3 x 6 s = 18 s of player buffer alone already exceeds our 10-second limit! Choosing 2-second segments is mandatory for standard HLS under 10 seconds, trading ~3x more HTTP requests and ~5–10% larger video files (more frequent keyframes) for 12 seconds less lag.
    • Why player catch-up is needed: a viewer who loads index.m3u8 right before segment #11 is published starts ~10.5 seconds behind, and playing at 1.00x speed would keep them 10.5 seconds behind forever. The packager stamps wall-clock timestamps (#EXT-X-PROGRAM-DATE-TIME) into the playlist; whenever a player sees it is more than 8.0 s behind real time, it plays at 1.04x speed (imperceptible to humans) until its lag settles at ~8.0 s.
    • Low-Latency HLS (LL-HLS) for interactive channels: instead of waiting 2 full seconds to publish a segment, the packager emits 0.5 s partial chunks (EXT-X-PART) as frames arrive and holds the viewer's playlist request open until the next part is ready (blocking playlist reload), reaching ~3.5 s at the cost of 4x higher CDN request rates.

    Audience-tiered transcoding saves ~1/3 of our GPU fleet. Encoding all 100,000 streams into 4 renditions takes ~5,000 GPU servers, yet live viewership follows a steep power law where roughly half of streams have fewer than 5 viewers:

    • < 5 viewers (~50,000 streams): source passthrough (1080p) + 480p only. Comparing output pixels per frame (854 x 480 = 0.41M pixels vs. 1280x720 + 854x480 + 640x360 = 1.56M pixels), encoding just 480p takes ~26% of a full ladder's encode work.
    • >= 5 viewers (or partner channels): automatically spin up 720p and 360p within seconds and update master.m3u8 (our player re-checks master.m3u8 every 60 seconds to discover newly added renditions).
    • Total encode load drops from 100,000 ladders to 50,000 + (50,000 x 0.26) = 63,000 ladder-equivalents — saving over 1,500 GPU servers while still giving slow-connection viewers on tiny streams a 1.5 Mbps 480p fallback.
  7. Deep dive 2: CDN fan-out and request coalescing

    To turn 113 Mbps leaving our origin into 6 Tbps for a 2-million-viewer stream without melting our packagers, we use a two-tier CDN cache with request coalescing (also called collapsed forwarding — merging simultaneous cache misses for the same URL into a single upstream request):

    [ Packager Origin ]
        |  1 fetch per shield = 10 fetches total for segment 1042.m4s
        v
    [ 10 Regional Origin Shields ]   <-- coalescing ON (50 edge misses -> 1 origin fetch)
        |
        v
    [ 300+ Global Edge PoPs ]        <-- coalescing ON (100,000 Seoul viewers -> 1 shield fetch)
        |
        v
    [ 2,000,000 Viewers ]            all requesting .../720p/1042.m4s within the same 2 seconds!
    

    Why live streaming fails without request coalescing. On a normal website, cache misses arrive randomly. On a live stream, the moment index.m3u8 adds 1042.m4s, 100,000 viewers in Seoul all request 1042.m4s within 500 ms, before the Seoul edge PoP has finished downloading it! Without coalescing, all 100,000 requests miss the cache and stampede the origin at once. With coalescing enabled at both edge PoPs (Points of Presence — local CDN data centers in cities worldwide) and regional origin shields, the Seoul edge sends 1 request to its regional shield, holds the other 99,999 requests in memory for ~50 ms until the bytes arrive, and serves everyone from that single response.

    Exact cache TTL (time-to-live) per file type

    File type                 How often it changes    CDN Cache TTL    Why this exact TTL is critical
    ------------------------  ----------------------  ---------------  ---------------------------------------------
    Segment ({seq}.m4s)       Never (immutable)       Hours / days     Once written, bytes never change; 1 fetch/PoP
    Live playlist (.m3u8)     Every 2.0 s             0.5 s            Adds <= 0.5 s lag while coalescing 10M req/s
    Master playlist (.m3u8)   Only on ladder upgrade  5.0 s            Lets upgraded renditions appear quickly
    HTTP 404 on next segment  Becomes 200 ms later    0 s (no-cache!)  Caching a 404 stalls every viewer in that PoP
    

    Multi-CDN traffic steering. No single CDN guarantees 30 Tbps everywhere without regional congestion. We contract at least two global CDNs:

    • Server-side steering: GET /v1/streams/{id} hands out CDN A or CDN B as primary per country (say 60/40) and automatically shifts traffic every minute based on real-time stall rates reported in viewer beacons.
    • Client-side instant failover: if a viewer's ISP loses connectivity to CDN A mid-stream, the player switches to the alternates URL on CDN B on the very next 2-second segment boundary.
  8. Deep dive 3: live chat from 10 viewers to 2 million

    Chat uses three specialized tiers so connection state, validation, and per-room ordering never bottleneck one another:

    1. WebSocket Gateways (~260 servers, ~50,000 sockets each): hold open TLS connections and zero business logic. Crucially, a gateway subscribes to a room once on behalf of all local viewers watching that stream, receives one pre-batched frame every 200 ms, serializes it once into bytes, and writes that shared byte buffer to its ~7,700 local sockets watching a 2M-viewer stream (~38,500 lightweight socket writes/s per gateway).
    2. Stateless Chat Ingest: validates auth tokens, enforces per-user rate limits (1 msg/s normally; 1 msg/30 s in room "slow mode"), checks ban lists, and blocks banned words before a message ever reaches the room owner.
    3. Sharded Room Owners (consistent hashing by stream_id): one server owns each room in memory, assigns gap-free sequence numbers (seq = 1, 2, 3, ...), keeps a 30-second ring buffer for reconnecting clients (resume), publishes every accepted message to Kafka for moderation/VOD storage, and controls broadcast fan-out:
    Room size           Inbound chat rate     Broadcast strategy
    ------------------  --------------------  --------------------------------------------------------------
    < 10,000 viewers    < ~17 msg/s           Broadcast 100% of accepted messages in 200 ms batches
    >= 10,000 viewers   Up to ~3,333 msg/s    Cap broadcast at ~20 msg/s (4 per 200 ms batch): always keep
                                              broadcaster/moderator messages, sample viewer messages, and
                                              always show each sender their own message via local echo
    

    Sampling at the room owner before fan-out cuts a 2M-viewer room from 6.7 billion deliveries/s (3,333 x 2M) down to 40 million message deliveries/s (20 x 2M), packed into 5 frames/s (10M frames/s across 260 gateways) — fast enough to feel electric, slow enough for human eyes to read!

    Here is the exact 200 ms batch sampler on the Room Owner:

    import random
    
    # 5 batches/second x 4 messages/batch = 20 broadcast messages/second max for non-staff chat
    MAX_VIEWER_MSGS_PER_BATCH = 4
    
    
    def pick_for_broadcast(accepted_batch, rng=random):
        """Select one 200 ms batch for broadcast in chronological order.
        Staff/moderator messages always go through; regular messages are uniformly sampled
        when volume exceeds MAX_VIEWER_MSGS_PER_BATCH."""
        # Phase 1: Count staff messages and collect indices of regular viewer messages
        staff_count = 0
        viewer_indices = []
        for index, msg in enumerate(accepted_batch):
            if msg.is_staff:
                staff_count += 1
            else:
                viewer_indices.append(index)
    
        # Phase 2: Compute how many regular viewer messages fit in this 200 ms budget
        budget_left = max(0, MAX_VIEWER_MSGS_PER_BATCH - staff_count)
        if len(viewer_indices) <= budget_left:
            # Small/quiet room: every message fits without dropping anything
            return list(accepted_batch)
    
        # Phase 3: Sample exact budget uniformly and keep original arrival order
        chosen_viewer_indices = set(rng.sample(viewer_indices, budget_left))
        broadcast_list = []
        for index, msg in enumerate(accepted_batch):
            if msg.is_staff or index in chosen_viewer_indices:
                broadcast_list.append(msg)
        return broadcast_list
    

    Why nobody feels ignored when sampled out: the sender's browser renders their own message immediately (local echo) confirmed by the server's ack, @username mentions are routed directly to the mentioned user's session so replies are never lost, and moderation deletes ({"type": "delete", "seq": 18213}) ride the same broadcast channel.

  9. Scaling, failure handling, and trade-off summary

    Instant VOD and storage lifecycle

    • Playable in < 60 seconds: when a stream ends, all 1-minute .mp4 segment bundles are already in S3! The VOD worker simply writes a static .m3u8 playlist referencing each 2-second slice via #EXT-X-BYTERANGE, generates scrubbing thumbnail sprite sheets, and links the chat table for synchronized chat replay.
    • Tiered retention to tame 30–150 PB: keep all renditions on hot storage for days 0–7; drop the heavy 1080p rendition on VODs with zero views at day 7 and move days 7–30 to infrequent-access storage; delete at day 30 unless saved by the creator. Only popular VODs (say > 100 views in 24 hours) pay GPU compute to re-encode with slower, higher-compression codecs (AV1/HEVC) and 6-second segments.

    Surviving the "celebrity went live" thundering herd. When a streamer with 5M followers starts broadcasting, millions of phones tap the push notification at once. Protect the backend in three ways: pace push notifications over 60–120 seconds, cache GET /v1/streams/{id} and browse lists at the CDN for 5–10 seconds, and add 0–5 s of random jitter before opening the chat WebSocket so 260 gateways absorb TLS handshakes smoothly.

    Failure modes and recovery

    Failure User impact Automatic recovery
    Broadcaster Wi-Fi drops briefly Short spinner Stream enters RECONNECTING for a 90 s grace window instead of ending; reconnect resumes the same stream_id and inserts #EXT-X-DISCONTINUITY in .m3u8
    Ingest or Transcoder crashes 2–5 s pause Load balancer shifts reconnect to a healthy node; streams above 10,000 viewers run a hot-standby transcoder in a second availability zone
    Primary Packager / AZ fails Zero drop Replica packager in another AZ holds the identical 60 s segment ring in RAM; origin shields fail over immediately
    One CDN degrades in a region Brief stall Player switches to alternates CDN on the next segment; beacon processor shifts new viewers away within 60 s
    Chat Gateway or Room Owner dies 1–3 s chat pause Clients reconnect with jittered backoff and send resume{last_seq}; new Room Owner rebuilds the 30 s buffer from Kafka

    Summary of key trade-offs

    • 2-second HLS segments over CDNs vs. WebRTC: hits < 10 s latency (~8 s with player catch-up) while offloading 99.998% of 30 Tbps egress to cheap HTTP caches, giving up sub-second two-way interactivity.
    • Audience-tiered transcoding vs. full ladder for all: cuts GPU fleet size by ~1/3 (~1,500+ servers), at the minor cost of offering only source + 480p on < 5-viewer streams until a 5th viewer joins.
    • 1-minute S3 segment bundles vs. per-segment objects: slashes S3 PUT request fees by 30x (~$34k/day saved) while keeping instant VOD via byte-range playlists.
    • Bounded 20 msg/s chat sampling in mega-rooms: cuts a 2M-viewer room from an impossible 6.7B deliveries/s to 40M deliveries/s and keeps chat readable, while preserving staff messages, @mentions, and local echo.

Intuition & how it works

Think of a live streaming platform as a fast flipbook printing press paired with neighborhood newsstands for video, plus a stadium Jumbotron operator for chat. One broadcaster shoots live video, and our workshop cuts it into numbered 2-second flipbooks printed in four sizes (1080p, 720p, 480p, 360p — called renditions, copies of the same stream at different quality levels). Instead of mailing 2 million flipbooks directly from our workshop, we ship one copy to 10 regional warehouses (origin shields), which copy it to hundreds of street-corner newsstands (CDN edge PoPs, local cache servers near users) so millions of viewers grab the exact same cached file next door. Meanwhile, live chat works like a stadium Jumbotron: in a cozy 100-person room everyone's message goes on screen, whereas in a 2-million-person stadium where 3,333 fans shout every second, the operator shows every referee announcement plus a lively 20-message-per-second sample so the board stays readable and the wires never melt.

Why does a naive design collapse immediately? Serving live video directly from your own servers or over WebSockets (persistent two-way network connections) requires 30 Terabits per second of outbound bandwidth at peak — enough to saturate dozens of data centers. Using long 6-to-10-second video chunks breaks the 10-second latency limit because video players hold 3 chunks in reserve to survive Wi-Fi hiccups (3 x 6 s = 18 s of lag before network time even counts), and saving every 2-second chunk as a separate cloud storage file racks up ~$35,000 per day in per-upload fees alone. Finally, naively forwarding every chat message in a 2-million-viewer room requires 3,333 x 2,000,000 = 6.7 billion message deliveries every single second.

Trace one 2-second slice of a broadcast and one chat message to see how all pieces work together:

  1. Ingest & aligned encoding (t = 0.0 s -> 2.5 s): A broadcaster pushes 1080p video at 6 Mbps over RTMP (Real-Time Messaging Protocol) with a keyframe (a complete, self-contained picture frame) every 2.0 s. A GPU transcoder decodes the feed once and encodes 720p, 480p, and 360p with keyframes aligned on the exact same 2-second mark, handing 2-second .m4s segments (#10) to a redundant Packager pair that updates the HLS (HTTP Live Streaming) .m3u8 text playlist in memory and appends segments into a 1-minute .mp4 bundle for VOD (Video on Demand) recording.
  2. Coalesced CDN delivery (t = 2.5 s -> 3.0 s): When 100,000 viewers in Seoul request segment #10 in the same second, the Seoul CDN edge uses request coalescing (merging simultaneous cache misses for the same URL into one upstream request) so our origin only sends segment #10 once per regional shield (~113 Mbps out of origin -> 6 Tbps delivered to 2 million viewers).
  3. Sub-10s adaptive playback (t = 3.0 s -> 8.5 s): Each viewer's player sits ~3 segments (6 s) behind the newest segment for smooth playback, uses wall-clock playlist tags to nudge playback to 1.04x speed whenever startup lag creeps past 8.5 s, and switches seamlessly from 1080p to 480p at the next 2-second keyframe boundary if cellular signal drops.
  4. Sub-second sampled chat (< 300 ms): Viewer Maya sends "Brilliant sacrifice!" with a client-generated idempotency key client_msg_id = "m-42" (a unique tag so network retries never post twice); her screen shows it instantly via local echo, while the stream's single Room Owner saves it to Kafka for replay and includes it in the next 200 ms sampled batch pushed to 260 WebSocket Gateways.

Key trade-offs

  • Segment duration (2 s vs. 6 s vs. 0.5 s): latency vs. CDN request rate and compression. Because HLS players buffer ~3 segments behind the live edge, 6-second segments add ~18 seconds of lag (violating the < 10 s goal), while 2-second segments hit ~8–8.5 s (with player speed catch-up) over standard CDNs at the cost of 3x more HTTP requests and slightly larger files from 2-second keyframes. Low-Latency HLS (0.5 s partial chunks with held HTTP requests) reaches ~3.5 s, but multiplies CDN requests ~4x again, so we enable it per channel rather than everywhere.
  • HLS over HTTP CDNs vs. WebRTC. WebRTC (a peer-to-peer/UDP real-time media protocol used in video calls) achieves < 500 ms latency, but requires stateful UDP media servers for every viewer instead of cheap HTTP file caching. HLS over CDNs trades a few seconds of delay for a 53,000x reduction in origin bandwidth on viral streams.
  • Audience-tiered transcoding vs. full ladder for every stream. Encoding all 4 renditions for all 100,000 streams requires ~5,000 GPU servers. Giving < 5-viewer streams source passthrough + 480p and upgrading automatically at 5 viewers cuts total encoding work by ~1/3, trading away 720p/360p options for tiny streams during their first few viewers.
  • Pull caching with request coalescing vs. pushing segments to edges. Pushing every segment to 300+ global edge PoPs wastes huge bandwidth in cities where nobody is watching that stream. Pull caching with request coalescing sends zero bytes to idle PoPs and still fetches each segment only once where millions watch.
  • Multi-CDN vs. single CDN. Splitting traffic across two CDNs roughly doubles origin-to-shield egress (from ~113 Mbps to ~226 Mbps on a viral stream) and requires dual token/config management, in exchange for surviving a single CDN outage and negotiating better per-GB rates.
  • Bounded chat sampling (20 msg/s) vs. full fan-out. Sampling big rooms drops >99% of raw messages from global broadcast in a 2M-viewer room (20 shown out of 3,333/s), in exchange for cutting fan-out by 167x and keeping chat human-readable while preserving moderator posts, @mentions, and the sender's own local echo.
  • 1-minute S3 bundles + lazy VOD re-encoding vs. per-segment uploads and eager re-encoding. Bundling 30 two-second segments into 1-minute .mp4 objects cuts S3 PUT request fees by 30x and enables instant VOD via HTTP byte-range playlists; re-encoding only VODs that earn views saves massive GPU compute on recordings nobody watches.

Common mistakes

  • Streaming video over WebSockets or directly from backend servers, ignoring that 30 Tbps of peak egress can only be served by globally distributed HTTP CDN caches.
  • Claiming < 10 s latency while using 6-to-10-second HLS segments, forgetting that players start 3 segment durations behind the live edge plus up to 1 segment duration of playlist age.
  • Ignoring keyframe alignment across renditions: if 1080p and 480p segments do not begin with keyframes at identical timestamps, adaptive bitrate switching causes black screens or decoder crashes.
  • Uploading every 2-second segment as an individual S3 object, incurring billions of daily PUT requests (~$35,000/day in request fees) instead of writing 1-minute byte-range bundles.
  • Forgetting request coalescing at CDN edges and origin shields, allowing 100,000 simultaneous requests for a brand-new segment to stampede the origin server.
  • Caching HTTP 404 responses or setting multi-second TTLs on live .m3u8 playlists, which either freezes playback when a player asks 50 ms early or adds unnecessary seconds of live lag.
  • Putting per-viewer auth tokens inside the CDN cache key, which creates a separate cache miss for every single viewer and destroys CDN caching completely.
  • Designing live chat as naive pub/sub with 100% fan-out, which tries to push 6.7 billion messages/s in a 2M-viewer room and scrolls faster than any screen can render.
  • Ending the stream immediately when a broadcaster's socket drops, instead of holding a 90-second RECONNECTING grace window so a brief Wi-Fi blip doesn't split the VOD and kick out every viewer.

Follow-up questions

  • What architectural changes are required to push glass-to-glass latency below two seconds for interactive broadcasts like live auctions? Standard and even Low-Latency HLS struggle below ~2–3 seconds because HTTP segment/part buffering still sits between encoder and player. For sub-second latency, switch delivery to WebRTC backed by a tree of SFUs (Selective Forwarding Units — stateful UDP media routers that forward encoded video packets without re-encoding, arranged with an origin SFU feeding regional edge SFUs). Because stateful UDP sessions cost far more per viewer than cached HTTP files, offer WebRTC selectively for interactive rooms (say under 10,000 viewers) and automatically fall back to Low-Latency HLS once viewership crosses that threshold.
  • How would you maintain accurate real-time viewer counts on a multi-million-viewer broadcast without creating write contention? Every video player already sends a lightweight heartbeat beacon every 30 seconds containing stream_id and session_id into Kafka. Instead of incrementing a single shared database counter 333,000 times per second, a stream processor estimates distinct session_ids seen in the last 60 seconds using HyperLogLog (a compact probabilistic sketch that counts millions of unique IDs in ~12 KB of memory with ~0.8% error, and merges cleanly across parallel shards if one stream is split across multiple partitions). Results are written to Redis once every 10 seconds to serve both stream pages and category leaderboards.
  • How can you add a live DVR feature allowing viewers to pause and scrub up to two hours backward during an active broadcast? Our packager holds the newest 60 seconds in RAM while every completed minute is already stored in S3 as a 1-minute .mp4 bundle cached by the CDN. To support a 2-hour rewind window (3,600 two-second segments), avoid putting all 3,600 lines in the default live .m3u8 playlist (re-downloading a 3,600-line text file every 2 seconds wastes bandwidth for viewers watching live). Keep the default live playlist short (~6 segments) and expose a separate DVR playlist endpoint (or HLS playlist delta updates) using #EXT-X-BYTERANGE pointers into the S3 bundles whenever a viewer drags the scrubber backward.

Follow-up questions

Similar questions

More Other interview questions

All 51 Other questions →