Sub topic 15
Extending the design to live streaming
This chapter assumes you have read the earlier chapters on segmentation and packaging, CDN delivery, and adaptive bitrate playback. You should know what an HLS media playlist is, what a segment is, and why a CDN caches segments. Live streaming reuses most of that design. The main change is that the content does not exist yet when viewers start asking for it.
What changes when the video is live
In video on demand (VOD), the whole file is transcoded before anyone watches it. Live content is produced while it is watched. Three consequences follow.
- The pipeline runs in real time. Each second of video must be encoded in under one second. You cannot queue a job and wait for it.
- The playlist keeps changing. The player cannot download a complete list of segments. It must re-fetch the playlist to learn about new ones.
- Latency matters. The gap between the camera and the viewer's screen is called glass-to-glass latency. Viewers care about it for sports, auctions and chat.
| Concern | VOD | Live |
|---|---|---|
| Transcoding | Batch, can retry, can be slow | Real time, no time to retry |
| Playlist | Fixed, ends with `#EXT-X-ENDLIST` | Grows, no end tag until the stream stops |
| Caching | Segments cached for days | Segments cached briefly, playlist for about one segment duration or less |
| Failure | Re-run the job | Gap or glitch visible to viewers |
| Main metric | Startup time, rebuffering | Latency, plus startup and rebuffering |
The live pipeline
The broadcaster sends a continuous stream to an ingest endpoint. Common ingest protocols are RTMP (older, widely supported by encoders such as OBS) and SRT (better over lossy networks). WebRTC is also used when sub-second latency is needed. The platform then transcodes into the ladder, packages segments, and publishes them to the origin. The CDN serves them to players.
Each stage has its own failure behavior, so treat them as separate services.
- Ingest terminates the broadcaster's connection. It authenticates the stream key and hands raw frames to the transcoder. Place ingest points near broadcasters to reduce packet loss on the first mile.
- Live transcoder produces every rung of the bitrate ladder at the same time. The rungs must stay aligned. Keyframes must fall at the same timestamps in every rendition, or the player cannot switch cleanly.
- Packager cuts the encoded output into segments and updates the playlist.
- Origin stores the newest segments and playlists. It is the only place the CDN falls back to.
Keep renditions aligned
The VOD command from earlier fixed the keyframe interval with -g 48 -keyint_min 48 -sc_threshold 0. Live needs the same rule, applied to every rendition. A live encoder cannot look ahead at scene changes, so a fixed interval is also the simplest way to guarantee segment boundaries. At 24 frames per second, -g 48 gives a keyframe every 2 seconds, and a 4-second segment holds exactly two keyframe intervals.
Live playlists
A live HLS media playlist uses a sliding window. It lists only the most recent segments, and the media sequence number rises as old segments drop off.
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:4
#EXT-X-MEDIA-SEQUENCE:2681
#EXTINF:4.000,
seg_2681.ts
#EXTINF:4.000,
seg_2682.ts
#EXTINF:4.000,
seg_2683.tsThere is no #EXT-X-ENDLIST line. The player sees that and reloads the playlist about once per target duration. When the broadcast ends, the packager appends #EXT-X-ENDLIST. The player then stops polling.
You can ask FFmpeg to produce this kind of output. The command below reads a live source and writes a rolling window of five segments, deleting old ones.
ffmpeg -i rtmp://localhost/live/streamkey \
-vf scale=-2:720 \
-c:v libx264 -preset veryfast -b:v 2800k -maxrate 3000k -bufsize 6000k \
-g 48 -keyint_min 48 -sc_threshold 0 \
-c:a aac -b:a 128k \
-f hls -hls_time 4 -hls_list_size 5 \
-hls_flags delete_segments+independent_segments \
-hls_segment_filename "live720/seg_%05d.ts" \
live720/index.m3u8Note the differences from the VOD command. -preset veryfast trades compression efficiency for speed so the encoder keeps up with real time. -hls_list_size 5 sets the window. delete_segments removes old files from disk. independent_segments tells the player each segment can be decoded on its own. The -hls_playlist_type vod option is gone, because it would write an end tag.
Latency budget
Latency in segmented live streaming is mostly set by segment duration and player buffering. A player usually starts a few segments behind the live edge so it has a buffer.
Rough budget for 4-second segments with a 3-segment player buffer:
- Capture and encoder: 1 to 2 seconds
- Ingest and transcode: 1 to 3 seconds
- Segment must finish before publishing: 4 seconds
- Player buffer: about 12 seconds (3 segments)
Total is about 18 to 21 seconds. That is typical for classic HLS. To reduce it, you can attack each term.
| Technique | Effect | Cost |
|---|---|---|
| Shorter segments (1 to 2 s) | Less waiting for a segment to finish, smaller buffer | More requests, more playlist reloads, more overhead per segment, lower CDN hit efficiency |
| Smaller player buffer | Lower latency | Higher rebuffering risk on unstable networks |
| Low-Latency HLS (LL-HLS) or Low-Latency DASH | Typically 2 to 5 seconds | More complex origin and CDN support |
| WebRTC | Under 1 second | Hard to cache, so costly to scale to large audiences |
How low-latency HLS works
LL-HLS splits each segment into smaller parts, often 200 to 500 ms long. The origin publishes each part as soon as it is ready, so the player does not wait for the whole segment. The player uses blocking playlist reload: it requests the playlist with a parameter naming the next part it needs, and the server holds the request open until that part exists. This removes the polling delay.
The cost is in the CDN. Held-open requests and many tiny objects need CDN support for the low-latency extensions, and the origin must handle many concurrent waiting requests. Ask whether your CDN supports this before committing.
Scaling and caching live traffic
Live traffic is bursty and synchronized. Thousands of viewers request the same new segment at nearly the same moment. If the CDN cache is cold for that segment, all those requests can reach the origin together.
Defenses:
- Request coalescing (also called request collapsing). The CDN edge sends one origin request for a missing segment and makes other viewers wait for it.
- Origin shield. A middle caching tier sits between edges and origin, so the origin sees one request per segment instead of one per edge location.
- Short playlist TTL. Cache playlists for a time shorter than the segment duration, or the player sees stale data and stalls. Cache segments for much longer, since they never change once published.
Failure modes
- Encoder drops. If the broadcaster's connection fails, the stream stops. Support a reconnect window and keep the playlist open, rather than ending the stream. Insert a discontinuity tag (
#EXT-X-DISCONTINUITY) when the stream resumes with different timestamps. - Transcoder falls behind. If encoding is slower than real time, segments arrive late and viewers rebuffer. Alert on the ratio of encode time to segment duration. Keep it well under 1.
- Single transcoder failure. Run a redundant pair, with a second encoder producing identical segments to a separate path. The packager can switch to the backup. Both must use the same segment numbering and timestamps or the player will see a jump.
- Origin overload. Handle with shielding and coalescing as described above.
- Clock drift. Segment timestamps from different machines can disagree. Derive them from the incoming stream's timestamps, not wall-clock time on each server.
Recording and live-to-VOD
Many platforms want a replay after the stream ends. Because the packager already produces segments, you can keep them instead of deleting them. Write all segments to durable object storage, then build a full playlist with every segment and an #EXT-X-ENDLIST tag. This reuses the VOD path. A separate step can re-transcode the recording at higher quality, since there is no real-time limit anymore.
Content protection and access control
The signed URL and DRM approach from the protection chapter still applies. Two live-specific points matter. Token expiry must be long enough to cover the whole broadcast, or must be refreshed by the player, because a single viewer may watch for hours. Also, per-viewer tokens in segment URLs reduce cache hit ratio. Prefer signed cookies or a token on the playlist path that the CDN can validate without changing the cache key.
Exercises
Exercise
A live stream uses 6-second segments and a player that buffers 3 segments. Estimate the player-side delay from these two factors alone, and name the first change you would try to cut latency without changing the CDN.
Show answer
The player buffer is 3 × 6 = 18 seconds, and the segment must also finish before it is published, adding about 6 seconds, so roughly 24 seconds before encoder and ingest delay. The first change is to shorten segments to about 2 seconds and reduce the buffer to 2 to 3 segments. This gives roughly 6 to 8 seconds. It needs no special CDN support but increases request volume, so check rebuffering afterwards.
Exercise
Viewers report that a live stream freezes every few seconds, but the origin logs show new segments are being produced on time. What is the most likely caching mistake, and how do you fix it?
Show answer
The CDN is caching the live playlist for too long, so players keep receiving an old playlist that lacks the newest segments. Set the playlist TTL to less than one target duration (or no-cache with revalidation) while keeping long TTLs on the immutable segments.
Exercise
Why must keyframe intervals be identical across all renditions of a live stream?
Show answer
The player switches renditions only at segment boundaries, and each segment must start on a keyframe. If renditions place keyframes at different times, segments do not line up, and switching causes glitches, gaps or repeated frames. A fixed interval (such as -g 48 with -sc_threshold 0) keeps them aligned.