Lesson 3 · Minutes 20-30

Video Streaming: Scaling It

Problem

From minute twenty, the interviewer takes the limits you named and gives each one a person. First a creator loses a long upload close to its end. Then a viewer with little bandwidth receives a file far too large for the connection. Then a creator sits waiting, because encoding an hour of video takes longer than the hour. Last, a crowd presses play on one new video together, and the question is what reaches the object store.

Nothing below arrives until one of those four asks for it, and each arrival has a price.

The Failed Upload

"She was 90 percent through a 4 GB upload on her phone, and the connection dropped. What has she lost?" On this design, nearly everything. Assume 5 megabits a second up. Four gigabytes is 6,400 seconds, nearly two hours, and a drop at 90 percent throws away about 96 minutes.

So the client stops sending one file. It opens an upload session on the app servers and asks them for signed URLs, a few at a time. A signed URL is an address on the object store that carries a signature and a short expiry, so the store takes a part without asking anyone. The client sends the file straight to the store in numbered parts. It reports each part to an app server, with the tag the store gave it, and a session row beside the videos table records them. A final call hands the store those tags, and the store joins the parts.

The upload, in parts
POST /videos                 {"title": "Harbor at dawn", "size": 4000000000}
                             201 {"id": "v-81c2", "part_size": 10000000, "parts": 400}
GET  /videos/{id}/parts      the next parts still missing, each with a fresh signed URL
PUT  <signed URL>             one part's bytes, straight to the object store
POST /videos/{id}/parts/{n}  this part has landed, with the store's tag for it
POST /videos/{id}/complete   join the parts; the status moves to encoding

At 10 MB a part, that file is 400 parts of about 16 seconds each, so a drop costs at most 16 seconds. On reconnecting, the client asks for the next parts still missing, gets fresh URLs for them, and carries on. A part that landed with its report lost is simply sent again.

A drop at 90 percent
One request4 GB at 5 Mbps
6,400 seconds, nearly two hours. A drop loses about 96 minutes.
10 MB parts400 parts, about 16 seconds each
A drop loses at most 16 seconds.

A store such as Amazon S3 takes parts from 5 mebibytes to 5 gibibytes, up to 10,000 of them, so 10 MB fits. Ten thousand parts at 10 MB is 100 GB, and a larger file gets a larger part, which is what the size in that first POST is for. The app servers now hold no bytes at all, only sessions and metadata, which suits the stateless tier better than the first design did.

What it costs: more logic on the client, a session row per upload, and abandoned parts, which are paid for forever unless they expire. Assume a seven-day expiry. A scheduled sweep aborts any session past it, which deletes its parts, and closes the row. A video's status now starts at uploading and leaves it in one of two ways: the final call, or that sweep.

The Wrong Bitrate

"He has a slow connection, he pressed play, and you sent him 40 megabits a second. Now what?" Stop sending one file. Encode the source into a ladder, at 7, 3 and 1 megabits a second, plus 16 for a 4K source. Each rung of the ladder is one rendition.

Then cut each rung into segments of about 4 seconds, each starting on a keyframe, a full picture that decodes without the frames before it. The cuts fall at the same instants on every rung, so a player can change rung at any boundary. Manifests list the rungs and their segments, and the playback URL now points at a manifest.

The player fetches one segment at a time, measures its own throughput and picks the rung for the next one. HLS and DASH are examples of this shape. An assumed 5-megabit viewer takes the 3-megabit rung, where the 4K source wanted about 40. How the player decides can wait, and you say so: "The player picks the rung from what it measures. I'll leave how it chooses as a box for now, and come back to it."

What it costs: 5 GB more stored per hour of video, a step between upload and playable, which is the next push, and a request per segment. A million viewers at one every 4 seconds is 250,000 requests a second at the peak, nearly all of them answered at the edge.

Encoding Slower Than the Video

"The upload's finished, one machine needs three hours for this hour of video, and you promised ten minutes. What gives?" The work stops being one job. Each video gets a graph of tasks: split the source at keyframes into one-minute pieces, encode each piece at each rung, join each rung and cut its segments, write the manifests, mark the video ready. A piece is not an upload part. Parts are cut for the network, and pieces for the encoder.

One video's graph
Splitone-minute pieces
→
Encodeeach piece at each rung
→
Joineach rung
Manifestsrungs and segments
→
Readyplayable

An hour is 60 pieces at 3 rungs, which is 180 tasks of a machine-minute each. With 20 machines free, that is 9 minutes of encoding, which leaves a minute of the agreed ten for the split, the joins and the manifests. Twenty is what one video borrows. The fleet as a whole stays at Scope's 12,500, and that is the average. Uploads peak at twice the average, so through a peak the fleet either grows towards 25,000 or lets a backlog build and drain afterwards.

The final upload call writes the graph to a task store, keyed by the video so that a retried call writes the same graph. The task store is a small service that holds each task's state and knows what is unblocked. It releases unblocked tasks to a work queue, the shape in Chapter 6's Queues, Logs and Pub-Sub, where each task goes to one worker under a lease. A log would tie a slow encode to everything behind it in its partition, so a queue fits tasks that run for a minute. A worker writes its output, tells the task store it is done, and only then acknowledges. If it crashes before that, the queue hands the task to another worker.

A worker whose lease runs out may also still be running while a second takes its task, as Chapter 6's Delivery Semantics at Scale expects. So each task writes to a key made from the video, the rung and the piece, and a second run overwrites the first with an equivalent piece. The store replaces an object whole, so a join reads one run or the other. A duplicate costs only work, the case Chapter 5's Leases, Locks and Fencing sets apart from one that costs data.

The alarm watches the oldest task's age, the signal in Chapter 6's Backpressure and Load Shedding, because that age is the wait a creator feels. What it costs: a task store to run, pieces that must join without a seam, and that backlog. Put the rest on the shelf by name: "The graph stays one box on the board for now, because workers that run twice need more room than I have here."

The Million in One Minute

"A new video goes up, and a million people press play inside sixty seconds. How much of that lands on your object store?" On this board, more than it needs to. Assume 100 edge locations, the number in Chapter 2's lesson on the edge. Each misses on its own, so the first segment, at three rungs, is 300 fetches in the same second.

Add a regional shield, a cache between the edge locations and the object store, and collapse misses at each layer, so that concurrent requests for one segment wait on one fetch. One shield turns those 300 into three, and each further shield adds its own three. For this one video, that is three fetches every 4 seconds, about 11 megabits a second for each shield. That is what your origin sees.

Segments help on their own. They get versioned names and long expiry times, so they stay on the edge, and a location holds the segments people watch, where the first design had it fetch whole files. A scheduled premiere is warmed through the shield, because its time and audience are known.

An ordinary peak is the harder sum, because the same million are spread across the catalogue, and the origin's bytes come from the hit rate. Of 7 terabits a second, 95 percent edge hits leave 350 gigabits, three and a half 100-gigabit links. Ninety-nine percent leave 70 gigabits, under one. Whatever the shield catches comes off those, so they are the most the origin sees.

The same crowd also asks the app servers for a playback URL, about 17,000 requests a second for one row. That answer is the same for every viewer, so it goes on the edge too. So do manifests, on a short expiry, because a rung can change behind them. Assume one minute for both, which is also how long a status change can take to show.

What it costs: a cache tier that repeats what the edge holds, and an origin still sized for a cold edge, because a purge of a hot video sends the misses at once. Collapsed, that burst is one fetch per segment per shield, not 7 terabits, which is why an origin can be sized for it at all.

The Design After Four Probes

Creators reach the app servers through the load balancer for sessions and metadata only, and go straight to the object store for the bytes. A task store, a task queue and an encoding fleet stand between the source and the segments. Viewers go to a CDN edge, then a shield, then the object store, where the renditions and manifests sit beside the source. The playback answer sits on the edge too, with the app servers behind it. The videos table stays, with the status running from uploading to encoding to ready, and the session rows beside it. One arrow is gone: whole files through the app servers.

The full design, with what changed since the first design marked new
Viewerpicks the rung CDN edgenear the viewer Creatorresends a part Shieldcollapses missesNEW Load balancerany server Renditionssegments, manifestsNEW App serverssessions, metadata Object storethe source Videos tablestatus, session rows Encoding fleetmay run a task twiceNEW Task storewhat is unblockedNEW Task queueone worker, a leaseNEW a hit playback URL miss miss parts one row graph unblocked a piece segments taken, done status readwriteasynccache missNEWsince the first design
Interview Pitfalls
  • Answering the slow viewer with "transcode it" and stopping. Renditions without segments and a manifest leave the viewer on one rung for the whole video.
  • Treating workers as exactly-once. The queue redelivers by design, and the interviewer asks what a second run writes.
  • Mixing the two transcoding numbers: 12,500 machines all day, and 9 minutes for one video on 20 of them.
  • Saying the origin "only sees the misses" with no hit rate. The interviewer asks how many bytes that is, and the answer has to be links.
What Interviewers Listen For
  • Parts, rungs, tasks and the shield, each traced to the complaint that forced it.
  • The drop priced before and after the change: 96 minutes against 16 seconds.
  • What a second run of a task writes, said without being asked.

Knowledge Check

A creator stops at part 200 of 400 and never comes back. What does the design still pay for those parts?

  • Nothing, as the store drops any part not joined within the hour
  • Storage, until the session's expiry deletes parts nobody will join
  • Nothing, as the app server frees its copy of them on the disconnect
  • One encode, as the fleet processes every part that reaches the store

Set against the first design, what do renditions and segments add to the bill?

  • About 5 GB stored per hour of video, and no further load on the edge
  • Nothing stored past the source, as each segment is encoded when asked
  • No new storage past one rung, as the edge derives the others when asked
  • About 5 GB stored per hour of video, and 250,000 requests a second

The queue redelivers a task while the first worker is still encoding it. What makes the second run harmless?

  • A key from the video, rung and piece, so both runs write the same object
  • The queue's lease, which holds back a second worker until the first ends
  • A lock on the video, held by the first worker until the whole graph ends
  • An exactly-once setting on the queue, checked before each worker starts

What does the shield add, and what can it not remove?

  • Extra delay on every edge hit, and the request per segment at the origin
  • A copy of each video at every location, and the need to purge on takedown
  • A second cache tier to run, and an origin that must handle a cold edge
  • A second egress bill on every view, and the need for any edge location

You got correct