Systemsfor Aravinda
0 / 78 core
Week 10 · Case studies

Design video streaming

2 hours · core path

Read first: DNS and CDNs, Object storage

In one sitting

The bytes of a video are immutable and the same for every viewer, so they belong in an edge cache. Upload lands in object storage, an offline job cuts bitrate rungs, and the player switches rungs as the network moves. Account state and the entitlement decision stay on a small control path and are never the cache key.

The player should not be reading video out of the database that knows the viewer’s name. The bytes are large, identical for every allowed viewer, and useless to personalize. The decision that this account may watch is small, personal, and has to be fresh. Those are two paths. Mixing them is how a CDN cache hit rate falls to zero.

The published split worth copying is the one in the Netflix writeup: a small control decision, and a large cache of immutable bytes close to the user. Appliances in that design store encoded media and do not store viewing history, DRM state, or member data. Titles are filled off the peak, including overnight. Playback is adaptive across several encoded sizes. What follows is an interview design of that shape. It is not a claim about their traffic, their hardware, or this year’s org chart.

Requirements

Two users, with different paths. A creator uploads a title. A viewer presses play.

The viewer path must:

  • Start playback after a control check: the account exists, and this account may watch this title.
  • Fetch media in small pieces at several bitrates, and keep playing when bandwidth drops.
  • Resume near where they left off. Resume position is account state, not media.

The creator path must:

  • Accept a large upload that can fail halfway and be retried.
  • Produce playable rungs off the viewer’s clock. A title is not watchable until transcode finishes, and the product says so.

Non-goals:

  • Building a codec, a player UI, or a recommendation system. Recommendations can be a link on the page. They are not on the byte path.
  • Editing video in place. A new cut is a new object.
  • Storing the account, the watch history, or the entitlement decision on the edge cache.

Latency assumption: the control response, the “you may play, here is how,” is back within a few hundred milliseconds. The first media segment can take longer than that on a cold title. A seek should reuse cached segments and a fresh control token, not re-upload anything.

Estimation

Assumptions, labeled as assumptions:

  • 5 million viewers in a day.
  • Each watches 1 hour. Watching is not uniform across the day. The even spread is only how you get an average.
  • The mix of rungs they actually sit on averages 2 Mbps. That is a planning assumption about a mix of phones and home connections, not a measurement of a service.
  • Four stored rungs, at 0.5, 1.5, 4, and 8 Mbps. Planning assumptions for the ladder.
  • The master file, kept for a future re-encode, is 20 Mbps. Another assumption.
  • Catalog is 20,000 hours of content.
  • Peak egress is 3 times the average. Chosen inside the 2x to 5x band.
  • Cache hit rate at the edge is 95 percent. Assumption you must say. It is not a figure from the Netflix writeup.
  • A segment is 4 seconds. A control call happens twice per viewer per day: play, and one token refresh. Assumption.

A day is 86,400 seconds.

watch-seconds per day = 5e6 * 3,600 = 1.8e10

average egress bits/s = 1.8e10 * 2e6 / 86,400
                      = 3.6e16 / 86,400
                      = 4.17e11 bits/s
                      = 417 Gbps average at the viewers

shortcut, divide by 1e5 instead of 86,400
                      = 360 Gbps, about 14 percent low

peak, assumption 3x   = about 1.25 Tbps leaving the edge

origin fraction, 5 percent assumption
                      = 0.05 * 417 Gbps
                      = about 21 Gbps average the origin must feed

concurrent viewers, average = 5e6 * 3,600 / 86,400
                            = 5e6 / 24
                            = about 208,000
peak concurrency, 3x        = about 625,000

That 417 Gbps is edge egress, the bytes viewers download. It is derived from the assumptions above. It is not a measured total for any company. The origin does not serve it. The cache does, if the cache key is stable.

Control-path rate, for contrast:

control calls per day = 5e6 * 2 = 10e6
average                = 10e6 / 86,400 = about 116 per second
peak at 3x             = about 350 per second

Segment rate, if every watch-second is one 4-second fetch:

segments per day = 1.8e10 / 4 = 4.5e9
average          = 4.5e9 / 86,400 = about 52,000 per second
peak at 3x       = about 156,000 per second
origin at a 95 percent hit rate = about 2,600 per second average

Storage for one hour of title, decimal gigabytes:

0.5 Mbps * 3,600 s = 1.8e9 bits = 0.225 GB
1.5 Mbps * 3,600   = 5.4e9 bits = 0.675 GB
4 Mbps * 3,600     = 1.44e10 bits = 1.8 GB
8 Mbps * 3,600     = 2.88e10 bits = 3.6 GB
ladder, one hour                       = 6.3 GB

20,000 hours * 6.3 GB = 126 TB encoded

master at 20 Mbps * 3,600 = 7.2e10 bits = 9 GB per hour
20,000 * 9 GB                          = 180 TB of masters

unique bytes, encoded plus master      = about 306 TB
assumption: 3 replicas of the origin   = about 920 TB

Edge caches hold another copy of whatever is popular. That copy is the point. Three replicas of the origin do not put the bytes near the viewer. Do not quote a price. The shape of the bill is egress at the edge, and origin storage that grows with the replica count and with every rung you add.

High-level design

flowchart LR
  creator[Creator]
  upload[Multipart upload]
  objects[Object storage]
  workers[Offline transcoder]
  rungs[Immutable segments]
  shield[Origin shield]
  edge[Edge cache]
  control[Control service]
  rights[Entitlement check]
  player[Player]
  creator --> upload --> objects --> workers --> rungs
  rungs --> shield --> edge
  player --> control --> rights
  player --> edge

Upload uses multipart upload into object storage. A single PUT of a master is fragile. Each part carries a checksum. The metadata row for the title stores the owner, the status, and the object key of the master. The database does not store the master.

A worker picks up titles in the uploaded state, writes each rung as immutable segments, writes a small manifest that lists the segments per rung, and flips the title to playable. None of this is on the viewer’s request. Filling edges with a new title happens before the evening peak, the same way the published design moves bytes off-peak. A title that drops at 18:00 was encoded and copied hours earlier, or the first viewers pay origin misses and everyone else should not.

The player asks the control service for permission. Control checks the account and the entitlement, writes nothing into the media cache, and returns three things: the manifest URL, a short-lived token, and the resume position. The player then fetches segments from an edge cache and switches rungs on its own.

Deep dive

What is cached, and what is never cached

A CDN caches under a key, usually the URL plus the headers you chose to vary on. Media segments are a good citizen because they never change. Dynamic account HTML is a bad one. A purge is eventual, so you do not plan on purging a segment. You publish a new name. Segment URLs include the title, the rung, the sequence, and a content hash. A re-encode is a new hash. Old URLs stay valid until nothing references them, which is what immutable means.

The trap is the token. If every viewer gets a distinct URL because the signature is inside the path, the cache stores one copy per viewer and the 95 percent assumption dies. The segment URL is identical for every viewer. The token travels in a header or a query parameter that is not part of the cache key. The edge checks the token, then serves the shared bytes. Wrong token, no bytes. Valid token, one cached object.

The token is a signed claim: this account, this title, this expiry. Assumption: expiry is 5 minutes. It is not encrypted. Anyone who has it can read it. You cannot take it back before it expires unless you add a denylist, and a denylist is a lookup you just put on the data path. Keep the token short instead. Revocation waits up to 5 minutes. Say that out loud. It is the trade for not calling the account service on every segment.

Never stored at the edge:

  • The account record. Name, email, payment state.
  • The entitlement decision as a durable “yes” beside the file. The token is a short capability, not a replica of the decision.
  • Viewing history and the resume position. Those are writes to the account’s row. They go to the control service on a timer, and a stale resume is a few seconds of replay, which is acceptable if you said so.

If the entitlement service is down, control refuses new playback. It does not fail open. An edge that already has a token can keep serving that token until expiry. That is the blast radius you wanted: new sessions stop, in-flight sessions play.

The player picks the rung

Adaptive bitrate is a player behavior. Each segment is 4 seconds of one rung. The player measures how long the last fetch took, picks a rung that fits, and at the next segment boundary it can step up or down. The origin does not guess the household’s bandwidth. The manifest lists the rungs and the segment URLs. That file is small and cacheable, and it is the same for everyone.

A switch is cheap only because the segments are aligned. If rung A and rung B cut at different timestamps, the player cannot switch without a glitch or a rebuffer. The transcoder makes the boundaries line up. That is a requirement on the offline job, not a runtime negotiation.

Cold title, hot title. A title nobody has watched misses at the edge, misses at the origin shield, and reads object storage. The shield exists so a miss storm from many edge sites collapses into one fetch of each segment. Without it, every site asks the origin at once. That is a stampede, and the cache page is where single-flight is defined for the smaller case. The shield is single-flight for bytes. A premiere you care about is pushed to the edge before it is announced, so the miss never happens at peak.

Anycast can steer a viewer toward a nearby edge announcement. It is not a promise that the nearest city wins. The control service can also hand back a specific edge host that has the title and is healthy, which is the same idea as the published steering control plane. If you do that, the media host is still serving immutable bytes, not running the entitlement query.

Upload and the offline job

The creator’s client splits the master into parts, uploads them, and completes the multipart request with the checksums. A lost connection resumes at the last confirmed part. The metadata status moves from uploading to uploaded in one write after the complete succeeds. If you mark it uploaded first and the complete fails, a worker will transcode a partial master.

Transcode reads the master, writes segments, and records the manifest key. It can run for longer than a request timeout. It is a queue of jobs, retried, idempotent on the output key. Re-running a rung overwrites nothing that is already named by that content hash. It writes the same bytes again or finds them present. The viewer’s play button reads status. Until the status is playable, there is no manifest to cache.

Bandwidth on the way in is much smaller than playback, unless the product is a live ingest. This design is on-demand. Live is a different pipeline: you cannot wait for the whole master, ladders are produced continuously, and the “immutable” segment is immutable only after it is closed. If the interviewer asks for live, say you closed the segment every few seconds and the player can only see closed segments. Do not pretend the on-demand estimate still holds.

Tradeoffs

Choice What you gain What you spend
Immutable segment URLs, cache key excludes the token One copy of the bytes serves every allowed viewer A leaked token works until it expires
Recheck the account service on every segment Revocation is immediate You put the account store on the data path and threw away the split
Precompute a ladder of rungs offline Playback is a file fetch, and the player can switch Storage grows with every rung, and a new title waits on the job
Transcode a rung on first request You store only the master until someone watches The first viewer eats the encode latency, and a hot premiere does it under load
Origin shield in front of object storage A cold title misses once per segment, not once per edge site Another tier to operate, and a shield failure looks like an origin failure
Push popular titles to the edge before peak The hit rate holds when the audience shows up You might copy bytes nobody watches
Resume position stored with the account The edge stays free of member data A cross-region viewer can see a stale offset if you read a lagging replica

Failure modes

  • Object storage is down. Edges keep playing titles they already hold. New encodes stop. Control can still authorize a title the edge has. The symptom of mixing the paths is the opposite failure: storage down, and playback stops everywhere because every segment was a dynamic request.
  • The entitlement service is down. New tokens stop. In-flight tokens play out. Fail open here and you give the catalog away. Fail closed and you take an outage on new plays only.
  • A premiere is not on the edge. Symptom: origin bandwidth spikes toward the full egress number, which your origin was not sized for. The shield absorbs repeated misses. It does not create capacity you did not plan. Pre-position the title, or shed new starts. A retry storm from players re-requesting the same missing segment is idempotent and still expensive. Bound the retries.
  • The token is baked into the cache key. Symptom: hit rate collapses, origin egress climbs toward the viewer egress, and adding edge machines makes it worse because each of them misses. Pull the token out of the key.
  • A transcode job retries forever on a corrupt master. Symptom: the queue stalls behind one title. After a few attempts, mark the title failed and move on. The creator can replace the master. That is a poison input, and the upload status has to be able to say failed.
  • Resume writes are asynchronous and the replica is behind. Symptom: the viewer restarts and loses the last few seconds. Read resume from the primary, or accept the lag in the requirements. Do not cache resume at the edge to “fix” it.

Durability sits on the master and the segments, with checksums, before the title is marked playable. Consistency of the account is a normal database problem on a small QPS path. Do not spread it onto the segment cache to make it look fast.

In the interview

Open with the split. “Control is a few hundred requests a second and decides whether this account may play. Data is tens of thousands of segment fetches a second, immutable, cached at the edge. The player picks the rung.” Put the 417 Gbps derivation on the table as edge egress under your assumptions, then the 5 percent that actually reaches origin, and say the hit rate is an assumption.

Skip codecs, DRM mathematics, and recommendation models. Name DRM as a decision you do not cache.

The follow-up is almost always “what is in the cache key?” or “the hot title is not at the edge yet.” Answer with the stable segment URL, the token beside it, and the shield plus a pre-positioned copy. If they ask what happens when the account service dies, draw the blast radius: new sessions stop, current tokens drain.

Check yourself

Why does putting the playback token inside the segment URL defeat the CDN?

The cache key is the URL, plus any header you chose to vary on. A distinct token per viewer makes a distinct key per viewer, so the edge stores a private copy and then misses. The segment URL has to be the same for everyone. The token is checked and then ignored by the cache key.

Five million viewers watch one hour each at 2 Mbps. What is the average edge egress, and what did you divide by?

Watch-seconds are 5e6 times 3,600. Times 2e6 bits per second is 3.6e16 bits per day. Divide by 86,400 to get about 417 Gbps. Dividing by 100,000 instead gets about 360 Gbps, which is the shortcut and a low estimate. This is derived from the assumptions, not a measured traffic total.

The entitlement service is down and a viewer is ten minutes into a film. What still plays, and what stops?

Segments for a token that was already issued keep coming until that token expires. A new play, or a refresh after expiry, needs a new decision and fails closed. The edge never had the account, so it cannot invent a yes.

A one-hour master is uploaded as a single PUT and the connection dies at 80 percent. What should have happened instead?

Multipart upload commits parts as they succeed, with checksums, and a retry resumes at the last good part. The title stays in uploading until the complete call succeeds. Marking it ready on the first byte, or transcoding a partial object, publishes a broken ladder.

Based on: Netflix Open Connect; Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.