Sub topic 10
Delivering video through a CDN
This chapter assumes you know HTTP caching basics (Cache-Control, TTL, cache keys), have read the earlier chapters on segmentation and storage, and can read short Python and shell snippets. By this point the pipeline has produced HLS segments and playlists in object storage. Now they must reach millions of viewers. Serving them straight from storage would be slow and expensive, so a content delivery network (CDN) sits in front.
Why a CDN is required
A CDN is a set of cache servers placed near viewers, called edge servers or points of presence (PoPs). A viewer's player requests segments from the nearest edge. On a cache hit, the edge answers directly. On a miss, it fetches the object from the origin (your storage plus any origin service), stores it, and returns it.
Three problems make this necessary for video:
- Bandwidth. If 500,000 viewers watch at 3 Mbps, that is 1.5 Tbps of egress. No single origin serves that.
- Latency. Each segment request pays a round trip. A nearby edge keeps this small, which helps startup time and reduces rebuffering.
- Origin protection. Without a cache, a popular release sends one request per viewer per segment to storage.
The goal is a high cache hit ratio (the fraction of requests served from cache) so that origin traffic is a small fraction of viewer traffic.
The delivery path
Large designs use more than one cache layer. Edges are numerous and small. A shield (also called a mid-tier or regional cache) is a smaller set of caches between the edges and the origin. Edges that miss ask the shield, and only the shield's misses reach the origin.
The shield matters because edges do not share contents. A segment requested in 40 cities misses at 40 edges. Without a shield, that is 40 origin fetches. With one, it is 1.
What to cache and for how long
The packaging chapter gave each segment a unique name such as seg_0042.ts. For on-demand video, the contents of a named segment never change, so it can be cached for a very long time. Playlists need more care.
| Object | Example | Suggested Cache-Control | Reason |
|---|---|---|---|
| Media segment (VOD) | `720p/seg_0042.ts` | `public, max-age=31536000, immutable` | Content never changes for that name |
| Rendition playlist (VOD) | `720p/index.m3u8` | `public, max-age=86400` or longer | Complete once publishing finishes |
| Master playlist (VOD) | `master.m3u8` | `public, max-age=300` | You may add or retire renditions |
| Live playlist | `live/index.m3u8` | `max-age=1` to the target duration | Changes every few seconds |
| Signed manifest or token endpoint | `/play/v123` | `private, no-store` | Per-user data |
Set these headers when you upload, so the origin does not need logic to add them:
# Segments: long-lived and immutable
aws s3 cp 720p/ s3://my-video-bucket/videos/v123/720p/ --recursive \
--exclude "*" --include "*.ts" \
--content-type video/mp2t \
--cache-control "public, max-age=31536000, immutable"
# Playlists: shorter lifetime
aws s3 cp 720p/index.m3u8 s3://my-video-bucket/videos/v123/720p/index.m3u8 \
--content-type application/vnd.apple.mpegurl \
--cache-control "public, max-age=86400"Avoid invalidation by versioning paths
CDN invalidation is slow, often rate-limited or billed, and unreliable as a normal workflow. If you re-encode a video, publish it under a new prefix (videos/v123/r2/...) and update the metadata so the master playlist URL points to it. Old objects age out. Treating objects as immutable removes the need to purge.
Cache keys and signed URLs
The cache key is what the CDN uses to decide whether two requests are the same object. By default it includes the path and often the full query string.
This causes a common failure with access control. If you protect content with signed URLs such as seg_0042.ts?sig=abc&exp=1700000000, each viewer's signature is different. If the signature is part of the cache key, every viewer has a unique key, and the hit ratio drops to near zero.
The fix is to validate the signature at the edge, then exclude the signature parameters from the cache key. Most CDNs support this through edge functions or cache-key policies. Signed cookies are an alternative: one cookie covers every segment under a path, so segment URLs stay identical across users. The Content Protection chapter covers how to sign them.
Two more cache-key rules:
- Ignore query parameters that do not change the response, such as analytics tags.
- Include a header like
OriginorAccept-Encodingonly if the response varies by it. Extra variation fragments the cache.
Range requests and partial objects
Players using fragmented MP4 (CMAF) may fetch byte ranges of one large file, rather than separate segment files. Check how your CDN handles Range requests. Some fetch and cache the whole object on the first range request. Others cache each range separately and may fetch the same bytes repeatedly. If you use byte-range addressing, test a cold cache and watch origin bytes. Separate segment files avoid this question, at the cost of more objects.
Estimating origin load
You can predict how much traffic reaches storage from the hit ratios of each layer. A miss at the edge becomes a request to the shield, and a miss there becomes a request to the origin.
def origin_load_gbps(viewer_gbps, edge_hit, shield_hit=None):
"""Traffic reaching the origin, in Gbps."""
after_edge = viewer_gbps * (1 - edge_hit)
if shield_hit is None:
return after_edge
return after_edge * (1 - shield_hit)
peak = 1500 # 1.5 Tbps of viewer traffic
print(origin_load_gbps(peak, 0.95)) # 75.0
print(origin_load_gbps(peak, 0.95, 0.80)) # 15.0The edge hit ratio sounds high at 95%, yet 75 Gbps would still hit the origin. Adding a shield with an 80% hit ratio cuts that to 15 Gbps. Small gains in hit ratio near 100% have large effects on origin load.
Popularity, long tails and cold starts
Video catalogs follow a long-tail pattern. A small number of titles account for most views, and a large number are rarely watched. This shapes caching:
- Popular titles stay hot in every edge's cache, so hit ratios are excellent.
- Tail titles are requested rarely, get evicted, and miss often. Each miss costs a trip to the origin and a slower first segment for that viewer.
- New releases are the opposite problem. Millions of viewers request the same uncached segments at the same moment.
For the release case, use these techniques:
- Request collapsing (coalescing). When many requests for the same uncached object arrive together, the cache sends one origin request and holds the rest until it returns. Confirm that your CDN enables this.
- Pre-warming. Before a known launch, fetch the first segments of each rendition through the CDN to fill the shield and key edges. Early segments matter most because every viewer starts there.
- Origin shielding as described above, which turns many edge misses into one.
Handling errors at the edge
CDNs cache error responses too. If the origin returns a 404 because a segment is still being written, a long negative-cache TTL can keep serving that 404 after the file appears. Keep error TTLs short, usually a few seconds. If you publish segments to storage before the playlist that references them, players will not request a segment that does not yet exist.
Also decide what happens when the origin is down. Options such as "serve stale on error" let the edge keep returning expired but valid segments. For immutable VOD, stale content is almost always correct, so enable it.
Multi-CDN and ISP caches
Large services often use more than one CDN. The reasons are resilience (one provider's outage does not stop playback), regional performance differences, and price negotiation. The cost is complexity. You need DNS or client-side steering, consistent cache-key and signing behavior across providers, and duplicated monitoring. Some providers also place appliances inside ISP networks, which keeps traffic off transit links and lowers both latency and cost. Treat these as later optimizations, once a single CDN is configured well.
Measuring delivery
Track these numbers per CDN and per region:
- Edge and shield hit ratio, by bytes and by requests.
- Origin egress and requests per second.
- Time to first byte for segments on hits and on misses.
- Status code rates, especially 4xx and 5xx.
Byte hit ratio is usually the one that determines cost, because segments are large. A good request hit ratio can hide poor byte efficiency if large files miss more often.
Exercise
Your CDN hit ratio drops from 95% to near 0% after you add signed URLs of the form seg_0042.ts?sig=...&exp=... with a different signature for each viewer. Explain the cause and give one fix.
Show answer
By default the signature is part of the cache key, so each viewer's URL is a different cache key and no request can reuse another viewer's cached copy. The fix is to validate the signature at the edge and exclude sig and exp from the cache key. Alternatively, use signed cookies so segment URLs are identical for all viewers.
Exercise
A new episode launches, and the origin receives thousands of simultaneous requests for seg_0001.ts even though you use a CDN. Name two CDN features that reduce this and say what each does.
Show answer
Request collapsing sends one origin request for an uncached object and holds the other requests until it returns. Origin shielding adds a mid-tier cache so that misses from many edges go to the shield first, and only the shield's misses reach the origin. Pre-warming the first segments before launch also helps.