Design problems
Media & streamingHardSDE-2 35 min

Design live streaming (Twitch / YouTube Live)

Asked at
AmazonGoogleJioHotstarMetaShareChat

The interviewer asks

“Design a live streaming platform like Twitch or YouTube Live. Anyone can go live from OBS or a phone, and viewers anywhere watch with a few seconds of delay, adaptive quality and live chat. The stream is saved for replay afterwards.”

What a strong answer looks like

Live streaming is a pipeline with a latency budget, not a storage problem. A strong answer traces one frame: the broadcaster pushes RTMP/SRT (or WebRTC) to the nearest ingest point of presence, which authenticates the stream key and forwards it to a transcoder that produces a bitrate ladder with short, aligned keyframes; a packager cuts low-latency HLS/DASH (CMAF chunks of a few hundred ms); a fan-out tree of origin, mid-tier and edge caches delivers segments to viewers, with request collapsing so a channel with 500,000 viewers sends each chunk upstream only once. The candidate should break down the 2-5 s glass-to-glass latency, explain how the long tail of tiny channels differs from one mega-streamer, handle broadcaster disconnects, and record the stream to object storage for VOD. Chat is a separate real-time system.

Concepts to mention

RTMP/SRT/WebRTC ingest at nearest PoPStream key authenticationReal-time transcoding with aligned keyframesCMAF and low-latency HLS/DASH partial segmentsGlass-to-glass latency budgetOrigin, mid-tier shield and edge fan-outRequest collapsingTiered transcoding for long-tail channelsSession state machine with reconnect grace periodRecording segments directly to object storage for VODApproximate live viewer counts

1 Requirements

Functional

  • Broadcasters go live with a stream key from OBS (RTMP/SRT) or the mobile app
  • Viewers watch live with adaptive bitrate on web, mobile and TV
  • Low-latency mode (2-5 s) by default; an ultra-low-latency option (< 1 s) for interactive streams
  • Live chat alongside the video (separate service)
  • Live rewind (DVR window of a few hours) and automatic VOD after the stream ends
  • Show live viewer count; list live channels by category
  • Clips: viewers cut a 30-60 s clip from the live stream

Non-functional

  • ~100k concurrent live channels; ~3M concurrent viewers normally, a single channel may reach 1M+
  • Glass-to-glass latency 2-5 s p90 in low-latency mode; under 1 s for WebRTC mode with small audiences
  • Rebuffering < 1% of viewing time
  • Go-live: viewers see the stream within ~5 s of the broadcaster pressing start
  • Survive a broadcaster's short network drop (up to ~30-60 s) without ending the stream
  • Playback 99.95% available; an ingest PoP failure moves broadcasters to another PoP automatically

Out of scope (say it out loud)

  • Chat internals (covered in the live comments design)
  • Monetisation: subscriptions, donations, ads
  • Content moderation details (mention hooks only)
  • Recommendations and discovery ranking

2 Estimates

Ingest bandwidth~500-600 Gbps100k channels × ~5-6 Mbps (1080p60 source)
Transcoding~3,000-5,000 transcode serversFull ladder for ~30-50k channels with viewers; one GPU/ASIC server handles ~10-20 1080p ladders in real time. Tiny channels may get source-only or a short ladder.
Viewer egress~9-10 Tbps normal, more at events3M viewers × ~3 Mbps average bitrate
Biggest channel~4 Tbps for one stream1M viewers × ~4 Mbps; each segment requested ~1M times within about one second
Segment request rate~1.5M req/s at edges3M viewers ÷ ~2 s per segment; LL-HLS partial segments multiply request count 4-10x
VOD storage~5-10 PB/day before retention100k concurrent channels × 24 h = 2.4M stream-hours/day × ~2.7 GB/hour (6 Mbps source) ≈ 6.5 PB, plus renditions; retention of 7-60 days keeps the total bounded (a few hundred PB)
Live viewer-count updates~100k-300k heartbeats/s3M viewers sending a heartbeat every 10-30 s, aggregated per channel

3 API

EndpointWhat it does
POST/v1/streamsCreate or fetch a stream key and ingest URL for a channel
RTMP/SRTrtmp://ingest-bom.example.com/app/{stream_key}Broadcaster pushes audio/video to the nearest ingest PoP
WHIP/v1/whip/{channel}WebRTC ingest for browser and ultra-low-latency streams
GET/v1/channels/{id}/playbackReturns a signed master playlist URL, latency mode and the CDN host to use
GEThttps://edge…/live/{channel}/{rendition}/chunk_{seq}.m4sMedia segment or partial segment from an edge
POST/v1/channels/{id}/heartbeatViewer presence for live viewer counts
POST/v1/clipsCreate a clip from {channel, start_time, duration}
GET/v1/live?category=gaming&cursor=…Directory of live channels ordered by viewer count

4 Data model

channelsPostgres
channel_id (PK)owner_idstream_key_hashtitlecategorysettings (latency mode, transcode tier)

Small relational data; stream keys stored hashed and rotatable.

live_sessionsPostgres + Redis for live state
session_idchannel_idingest_poptranscoder_idorigin_idstate (starting/live/reconnecting/ended)started_atended_at

Redis holds the live routing (which origin serves this channel) with short TTLs refreshed by heartbeats.

segments (live window)Origin memory/SSD + mid-tier caches
channel/rendition/seq → bytes; playlist with last N segments

Only the last few minutes are hot; the DVR window is kept on SSD.

vod archiveObject storage (S3/GCS)
session_id/rendition/segment filesVOD manifest

Written continuously during the stream so the VOD exists as soon as the stream ends.

viewer_countsRedis (HyperLogLog or counters per channel)
channel_id → approximate concurrent viewersupdated every ~10 s

Approximate counts are fine; drives the live directory sorting.

stream_eventsKafka
channel_idevent (went_live, ended, reconnect, bitrate_drop)ts

Feeds notifications to followers, directory updates, analytics and moderation.

5 Architecture

CLIENTSEDGESERVICESASYNCDATARTMP / SRTauth stream keysource feedCMAF chunkssegmentsVODlive routingwent liveplayback, heartbeatorigin lookupLL-HLS chunkscollapsed fetchBroadcaster (OBS /app)Viewer playerIngest PoPs (RTMP/SRT)CDN edge cachesAPI gatewayStream control servicePlayback serviceKafka (stream events)Transcode + packagerVOD recorder / clipsPostgres (channels)Origin + mid-tiershieldRedis (routing,counts)Object storage (VOD)
ClientEdge / gatewayService / workerQueue / streamCacheDatabase / storageAI / modelThird partyrequestasync (event / queue)

Hover a box to highlight its connections.

6 Request flows

Go live

  1. 1OBS resolves ingest.example.com via GeoDNS/anycast to the nearest PoP (e.g. Mumbai) and opens RTMP with the stream key.
  2. 2The ingest server asks the control service to validate the key (hashed lookup), checks the channel is not banned, and creates a live session.
  3. 3The control service assigns a transcoder close to the PoP based on load and the channel's tier, and records routing (channel → transcoder → origin) in Redis.
  4. 4The transcoder decodes the source and encodes a ladder (e.g. 1080p60 6 Mbps, 720p 3 Mbps, 480p 1.2 Mbps, 160p 300 kbps) with keyframes every 2 s aligned across renditions.
  5. 5The packager emits CMAF segments of 2 s, split into ~250-500 ms parts for LL-HLS, and updates the playlists on the origin.
  6. 6A 'went live' event goes to Kafka; followers get notifications and the channel appears in the directory.

Watch a live stream

  1. 1The player calls /channels/{id}/playback and gets a signed master playlist URL on a CDN hostname.
  2. 2It loads the media playlist from the nearest edge and joins near the live edge, a couple of parts behind the newest.
  3. 3With LL-HLS the player issues blocking playlist reloads and preload hints, so the edge answers as soon as the next part exists instead of the player polling.
  4. 4Each edge fetches a new part from the mid-tier only once even if 20,000 viewers request it at the same moment (request collapsing); the mid-tier does the same towards the origin.
  5. 5The ABR logic watches throughput and buffer; live buffers are small (~1.5-3 s), so it switches down early on congestion.
  6. 6A heartbeat every ~30 s feeds the viewer count.

Broadcaster's Wi-Fi drops for 20 seconds

  1. 1Ingest stops receiving data; the session moves to 'reconnecting' rather than 'ended'.
  2. 2The packager keeps the playlist open; players reach the end of available media and show a buffering or 'reconnecting' slate (some platforms insert a slate image segment).
  3. 3OBS reconnects with the same key, possibly to a different PoP; the control service reattaches it to the same session and transcoder (or a new one with a discontinuity marker).
  4. 4If no reconnect happens within ~60-90 s, the session ends and the recorder finalises the VOD.

7 Deep dives

Where the latency goes

Glass-to-glass latency is a sum of stages, and you should budget it. Capture and encode at the broadcaster: ~100-500 ms depending on encoder settings (B-frames and look-ahead add delay). First-mile upload to ingest: ~50-200 ms, more on a bad connection. Transcoding: one frame-group of delay, ~200-500 ms with low-latency presets. Packaging: classic HLS waits for a full 6 s segment, and players buffer three segments, which is why old HLS sat at 15-30 s. Low-latency HLS and LL-DASH use CMAF chunks: a 2 s segment is published as parts of ~250-500 ms that can be sent with chunked transfer before the segment is complete, so the packaging delay drops to one part. CDN delivery: ~50-150 ms if edges answer blocking playlist requests immediately. Player buffer: the biggest knob; 1.5-3 s of buffer gives 2-5 s total latency with tolerable rebuffering. For under one second (auctions, interactive game shows, co-streaming) you need WebRTC end to end through SFUs, which costs much more per viewer and scales to thousands rather than millions per channel without a large relay tree.

Fan-out: the long tail vs the mega-streamer

Live traffic has two extremes. Most of the 100k channels have under 10 viewers; a few have hundreds of thousands. For the long tail, do not pay for a full transcode ladder: give source quality plus one or two low renditions, or transcode only when viewers exceed a threshold, and serve from the origin region with little caching benefit. For the mega-streamer, the problem is a thundering herd: one new 500 ms part is requested by 1M players within about a second. Build a distribution tree: the origin holds the part; a few mid-tier (shield) caches per region fetch it once; hundreds of edges fetch from mid-tiers; every cache layer collapses concurrent requests for the same object into one upstream fetch and makes the others wait for it. With collapsing, the origin serves each part only a handful of times regardless of audience size. For very large events, push segments proactively to edges (pre-positioning) instead of waiting for pulls, and spread the channel over several CDNs. The playback service assigns viewers to CDN hosts so popular channels are spread across many edges while small channels are concentrated, which keeps cache hit rates high.

Ingest reliability and stream state

The broadcaster's uplink is the weakest link: a home Wi-Fi or 4G connection with jitter and drops. Ingest PoPs are close to broadcasters (anycast or GeoDNS) to keep the first mile short. RTMP over TCP is the common standard but suffers on lossy links; SRT (UDP with retransmission inside a latency window) handles packet loss better, and many platforms now accept both, plus WebRTC (WHIP) from browsers. The control plane tracks each live session as a state machine: starting, live, reconnecting, ended. A disconnect moves the session to reconnecting and keeps the transcoder and playlists alive for a grace period, so a short drop does not end the stream or split the VOD. Stream keys are secrets: hash them at rest, allow rotation, and reject a second simultaneous connection with the same key (or let the newest win, with a notice). Monitor ingest bitrate and dropped frames and show broadcasters a health indicator, because most 'the stream is laggy' complaints start at their upload.

Recording, DVR and clips

Because the packager already produces segments, recording is almost free: a recorder consumes the segment stream and writes each segment and an updated VOD manifest to object storage as the stream runs. When the stream ends the VOD is immediately available, and it does not need re-transcoding. The DVR window (rewind up to a few hours during the live stream) is served from the same segments: the live playlist exposes a long sliding window, recent segments come from caches, and older ones from object storage. Clips are just references: a clip is (session, start time, duration), and playback reads the existing segments covering that range; a background job later renders a standalone file trimmed exactly at frame level for sharing. VOD storage grows fast, so apply retention (e.g. 7 days for regular channels, 60 days for partners, permanent only for highlights) and move older files to cheaper storage classes.

8 Trade-offs

LL-HLS/LL-DASH vs WebRTC

LL-HLS runs over ordinary HTTP CDNs, scales to millions and reaches 2-5 s. WebRTC gets under 1 s but needs stateful SFU servers per viewer connection and is expensive to scale. Use LL-HLS by default and WebRTC for small interactive audiences.

Transcode every channel vs only popular ones

Full ladders for 100k channels waste most GPU time on channels with three viewers. Tiered transcoding (source-only for small channels, full ladder for partners or above a viewer threshold) saves a large share of compute but gives small channels a worse mobile experience.

Segment and part size

Shorter parts lower latency but increase request count and CDN cost. 2 s segments with ~300-500 ms parts is a common balance; keyframe interval must match the segment boundaries.

Pull vs push to edges

Pull with request collapsing is simple and works for most channels. Pushing segments to edges is worth it only for scheduled mega events where the audience is known in advance.

9 Bottlenecks

A raid or host sends 200k viewers to one channel in seconds

Playback API and playlist requests spike. Cache playback responses briefly, keep request collapsing at every tier, and pre-assign the channel to more edges when its viewer count jumps.

Transcoder capacity at evening peak

Autoscale transcoders on active sessions, keep warm capacity in each region, and degrade gracefully by giving new small channels a shorter ladder instead of refusing to go live.

Playlist request rate in LL-HLS

Blocking playlist reloads multiply requests. Edges must hold the request open and answer when the next part appears, and use delta playlist updates to keep responses small.

10 Failure handling

Transcoder crashes

The control service detects missed heartbeats and starts a new transcoder fed from the ingest server's short buffer. Viewers see a few seconds of buffering and a discontinuity; the stream continues. Critical streams can run a hot standby transcoder.

Ingest PoP fails

Anycast/DNS routes the broadcaster's reconnect to the next PoP; the session is reattached within the grace window.

Origin region problem

Edges and mid-tiers keep serving what they have for a few seconds; the control plane moves the channel's packaging to another region and updates routing. For big events, run redundant packaging in two regions and let the player fail over between playlist URLs.

VOD recorder falls behind

Recording is asynchronous and reads from a buffer of segments; if it fails, it resumes from the origin's DVR window. The live stream is never blocked by recording.

11 What impresses

  • Breaks down end-to-end latency stage by stage and names the player buffer as the biggest knob
  • Explains request collapsing and why the origin load is independent of audience size
  • Treats the long tail and the mega-streamer differently, including tiered transcoding
  • Knows when WebRTC is worth its cost and when LL-HLS is enough
  • Handles broadcaster disconnects with a reconnect window
  • Gets VOD almost for free by recording packaged segments

12 Mistakes

  • Reusing the YouTube upload-transcode design with no real-time path
  • Using WebRTC for millions of viewers without discussing cost
  • Ignoring keyframe alignment, so ABR switches glitch
  • Letting every edge or viewer hit the origin directly
  • Ending the stream on the first network blip from the broadcaster
  • Putting chat messages through the video pipeline

13 Follow-ups

Q1How would you reach under one second latency for a live auction?
Q2How would you insert ads into a live stream (server-side ad insertion)?
Q3How would you moderate live streams for policy violations in near real time?
Q4How do you keep chat and video in sync when the video is 4 s behind?
Q5How would co-streaming (two broadcasters in one stream) work?
Q6How would you scale this for a single 25M-viewer cricket match?

Saved on this device. Create a free account to keep it on every device.

Practise this with Sam

A real mock interview, out loud, with an honest scorecard. Free to start.

Start free