System Design · Interview breakdown · Free article
Design a Video Streaming Service (YouTube)
Uploads that survive a dropped connection, processing that finishes in minutes, and playback that keeps going on a train. Built one step at a time, with experiments you can run.
A video streaming service lets creators upload videos and viewers watch them on any connection. Split the system into three paths. Creators upload files straight into object storage. Background workers turn each file into short segments at several qualities. Viewers fetch those segments from a CDN, and the player picks the quality its connection can keep up with.
Difficulty: Hard. Reported in interviews at Meta, MongoDB, HubSpot. Also asked as Design YouTube, Design Netflix, Design a video platform.
How do you design a video streaming service like YouTube?
A video streaming service lets creators upload videos and lets viewers watch them on any device and any connection. The hard part is that a video is far larger than the page around it. Viewers also watch on connections that change while they watch.
- Upload: lesson.mp4 · 600 MB. The wifi can drop at 425 MB. The upload must pick up where it stopped.
- Processing: Preparing 3 qualities. A two-hour video has to be ready in minutes, not hours.
- Watch page: Title, thumbnail, Play. The page is small and fast. The video is the heavy part.
- Playback: 0:16, on a train. The connection drops mid-video. The picture has to keep moving.
- Views: 1,204 views. A retried event must not count as a second view.
Picture Dev, who teaches cooking. He uploads a 600 MB lesson from his home wifi. A few minutes later, Asha opens it on a train. The title and thumbnail appear at once. The train pulls out of the station, away from its wifi. Sixteen seconds into the video, the picture freezes. Her phone can now download 2 megabits each second. The video needs 4.
The page was fast. The video was not. The title came from one small request. The pictures come from a long run of large requests. Those are two different workloads, so they get two different paths.
Back at home, the worker preparing Dev’s lesson crashed halfway through. Asha must never be handed a playlist that points at the missing half. Dev must be able to retry without creating two copies. Every screen in the strip hides a failure like these, which is why interviewers ask this problem.
Here is the design in a few sentences. Split the system into three paths. Creators upload files straight into object storage. Background workers turn each file into short segments at several qualities. Viewers fetch those segments from a CDN. The player picks the quality its connection can keep up with.
The rest of this breakdown follows Dev and Asha: one video being made ready, and one video being kept playing.
What is the interviewer testing?
Most candidates draw upload, storage, a transcode queue and a CDN within five minutes. That diagram is correct, and a mid-level answer usually stops there.
The interviewer then pushes on four questions. What happens when the upload dies halfway? How does a two-hour video get processed in minutes? Why does the video freeze when the connection slows, and what does the player do about it? What stops a crashed or late worker from publishing a broken video?
A senior answer handles all four. A staff answer also protects the origin from a viral video, counts each view once, and keeps copies in several regions consistent.
Spend most of the deep-dive time on adaptive playback, safe publishing and the upload that dies halfway. Parallel processing, the viral video and view counting are the usual follow-ups. Copies in several regions are where a staff round goes. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.
What should you ask before drawing anything?
Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.
- Recorded videos, or live?
- Picture a cooking lesson uploaded once and watched for years. Now picture a football match that must reach screens ten seconds after the goal. The second needs a different design, so assume recorded video unless told otherwise.
- Who uploads, and how big are the files?
- A creator on home wifi sending a 600 MB lesson behaves nothing like a studio sending a 50 GB film. Assume creators, and files up to a few gigabytes.
- Which devices and connections must play?
- A laptop on fibre and a phone on a train need different qualities. Ask for the slowest connection the promise has to cover.
- Which extras are in scope?
- Recommendations, comments, ads and live chat could each fill an interview of their own. Agree to leave them out, and say so.
Functional requirements
1. Upload, resumable; see its status 2. Prepare qualities and thumbnails 3. Watch page: details, access rules 4. Play, seek, switch quality 5. View counts (may lag); delete out: live, recs, comments, ads
Say it, don’t write it: The two promises that matter most are an upload that survives and playback that does not freeze.
The brief is a service for recorded videos. A creator uploads a file. A viewer finds it and watches it. Ask which extras matter before drawing anything. Live broadcasts and recommendations each change the design enough to be an interview of their own.
- A creator uploads a video and can resume after the connection drops. The creator sees whether it is uploading, processing, ready or failed.
- The service prepares each upload for different connections and devices, including thumbnails. Viewers only ever see a complete, checked version.
- A viewer reads a video’s details and asks to play it. Public, private and removed videos behave differently.
- A viewer plays, seeks and changes quality while watching, with an audio track and optional captions.
- The service shows a view count that may lag by a minute. A creator can delete a video, and new playback stops.
Out of scope
- Live broadcasts
- Recommendations and the home feed
- Comments, live chat and ads
- Copyright matching
- Search ranking (search returns titles and details only)
Checking that a file is a real video, and deciding whether it may be published, stay in scope. Both happen before a video can become ready.
Non-functional requirements
• First frame < 2 s (p95) • Frozen < 1% of watch time • An upload survives any crash • 10-minute video ready in ~10 min • Ready means every file is reachable • Counts lag 1 min; access never
Say it, don’t write it: Startup, freezing and upload safety are different promises, so each gets its own measurement.
Asha cares about two things: how fast the first frame appears, and whether the next minute plays without freezing. Dev cares about one thing: that his upload survives. One latency number cannot describe all three, so each promise gets its own measurement. The targets are illustrative interview numbers, not measurements of any real service.
- 95% of playback starts show a first frame within 2 seconds, counted from the tap on Play, failures included.
- Less than 1% of watch time is spent frozen.
- 99.9% of playback attempts succeed each month, and playback never waits on the upload workers.
- A confirmed upload survives any worker crash.
- A 10-minute upload is watchable within about 10 minutes.
- A ready video always plays completely: every file its playlist names exists.
- View counts may lag by 1 minute. A change to who may watch may not.
“Two seconds to first frame” cannot hold for a phone on a 0.3 megabit connection. So each target names who it covers: which devices, which formats, and the slowest connection supported. Below that line, the player shows a clear message instead of a spinner.
The numbers on this page come from one made-up workload. 10 million people watch each day, each for 20 minutes at an average of 2 megabits a second. Creators upload 100,000 videos a day, each 10 minutes long and recorded at 8 megabits a second. Units are decimal: 8 bits make a byte, and a terabyte is one trillion bytes. Each deep dive below works out the numbers it needs from these.
Out of scope
- Frame-accurate sync between viewers watching together
- Downloads for offline viewing
- Strict ordering of view counts across regions
Core entities
Video(id, owner, visibility, active_gen) Upload(id, video, parts, checksum) Job(id, video, source_v, recipe, epoch) Generation(id, playlist, files) PlaybackSession · WatchEvent(id, seq)
Say it, don’t write it: A generation never changes once written. Publishing a new one moves a single pointer.
Dev uploads a file called lesson.mp4. The filename cannot say whether processing finished. It cannot say whether Dev made the video private. It cannot say which encoder produced the files viewers are watching. So the video gets a durable identity, and each piece of work done to it gets its own.
Follow the lesson through the system. The video, v73, is the catalog entry: owner, title, visibility, state, and which prepared version viewers get. The upload, u73, is one resumable transfer, with the size and checksum Dev declared. The encoding job is one request to prepare one version of the source with one recipe of qualities. It carries the owner number of the worker running it. Its output is generation g8, one complete, checked set of prepared files. When Asha taps Play, she gets a playback session: a short-lived permission to fetch g8. Her player sends watch events, each with an ID so a repeat can be dropped.
A generation is every prepared file for one encode: the segments, the playlists, the thumbnails and the captions. Once written, a generation never changes. A new encode writes a new folder, such as videos/v73/g8/. It never overwrites files that a player may be downloading right now.
Where the data lives
Small records go in a database. The source file and the prepared segments go in object storage. The database holds one pointer, active_generation, that says which generation viewers get.
The catalog is small next to the video bytes. 100,000 new videos a day is about 37 million rows a year. Say each of the 10 million daily viewers reads video details five times a day. That is 50 million reads, and 50,000,000 ÷ 86,400 is about 579 a second. One relational primary, PostgreSQL in this design, with a cache in front handles that comfortably. When the catalog or its write rate outgrows one machine, shard the video table by video_id. Every query about one video then lands on one shard. YouTube met this problem with Vitess, which was created in 2010 to scale its MySQL databases.
View totals are kept apart from the catalog, in a small store that only the counting path writes. Step 4 shows why.
Two indexes matter. On videos, (owner_id, created_at) lists a creator’s uploads in order. On encoding jobs, (status, updated_at) finds jobs that stopped making progress, so a recovery pass can restart them.
A database transaction can change a job row and the video pointer together. It cannot create a thousand files in object storage at the same instant. So workers write a complete generation first and switch the pointer last. That one boundary shapes the rest of the design.
API
POST /videos (idempotency key)
POST /uploads/:id/parts → signed URLs
POST /uploads/:id/complete → processing
POST /videos/:id/playback → playlist URL
POST /watch-events {eventId, seq}Say it, don’t write it: The API hands out permission. The bytes go straight to storage and come back from the CDN.
A 600 MB upload is far too large to pass through application servers, and daily delivery is millions of times larger again. So the upload API hands out permission to send bytes. The bytes themselves go straight to storage. The playback API decides whether someone may watch. The frames come from the CDN. Each path can then fail and scale on its own.
| Request | Response | Rule it enforces |
|---|---|---|
| POST /videos with an idempotency key | video_id and upload_id | A retry with the same key returns the same upload |
| POST /uploads/{id}/parts | One signed URL per part, valid for minutes | Check the owner, the part count and the declared size |
| POST /uploads/{id}/complete | 202 with processing status | Check the stored parts and the final size, then record one job |
| GET /videos/{id} | Details, state and approximate views | Visibility decides who sees it; the creator also sees processing detail |
| POST /videos/{id}/playback | A playlist URL for one generation, with a short expiry | Check current access, and that a ready copy exists |
| POST /watch-events | The event IDs it accepted | Check the session; a repeated ID never counts twice |
| DELETE /videos/{id} | The video is marked removed | Check the owner; deleting twice returns the same result |
| Concrete exchange | Meaning |
|---|---|
| POST /videos, Idempotency-Key: upload_73, body {"title":"Cooking lesson","sizeBytes":600000000} | 201 {"videoId":"v73","uploadId":"u73","state":"uploading"} |
| POST /uploads/u73/complete with {"parts":[1,2,3],"checksum":"declared-digest"} | 202 {"videoId":"v73","state":"processing","statusUrl":"/videos/v73"} once the parts are verified |
| POST /videos/v73/playback with {"supportedCodecs":["avc1"]} | 200 {"sessionId":"s91","generation":"g8","manifestUrl":"authorized-location","expiresAt":"declared-time"} |
| POST /watch-events with {"events":[{"eventId":"e12","sessionId":"s91","sequence":12,"interval":[10,20]}]} | 202 {"acceptedEventIds":["e12"]}; accepted is not the same as counted |
A completion request can arrive twice when the first response is lost. The job is identified by three values: the video, the version of its source file, and the recipe. A second request with the same three finds the existing job instead of starting another. A worker can still crash and repeat the work itself. Stopping a duplicate request and surviving a repeated execution are two separate problems.
The playback request lists the codecs the device can decode. The playlist it returns names only qualities that device can play. A video still processing cannot return a playback session. A removed video cannot either, even to a viewer holding an old link.
Step 1: accept a resumable upload
Dev creates video v73. The API records the video and an upload, then signs one URL for each part of the file. His browser sends the parts straight to original storage. After a reconnect, it asks storage which parts arrived and sends only the rest. When the browser reports the last part, the API asks storage to complete the upload, and storage checks the whole-file checksum before it accepts. The API shows uploading until then, and processing after.
The interactive version of this example is available when JavaScript loads.
The 600 MB file never passes through the API. Viewers cannot play it yet, because it is still a raw camera file.
Step 2: prepare and publish playable media
When the upload completes, the API records a processing job and puts its ID on a queue. The message carries only the job ID and a pointer to the source file, never the video. A media worker takes the job and reads the original. Workers usually run FFmpeg, the open-source tool most transcoding pipelines are built on. It produces three qualities, an audio track, captions and thumbnails. It cuts each quality into 4-second segments that line up in time. Everything goes into a new generation folder.
The worker then checks the folder: every file the playlist names must exist. Only then does it switch v73 to ready and point active_generation at g8. A worker that fails before the switch leaves the video in processing. Viewers never see half a playlist.
The interactive version of this example is available when JavaScript loads.
One worker processing a whole file is fine for a short clip. A two-hour video would take hours, so the design splits it into chunks later on.
Step 3: read details, play and seek
Asha opens v73 and taps Play. The API checks that she may watch it. It returns a short-lived playlist URL for generation g8. Her player downloads the playlist and the first segments from a nearby CDN server. It finds a nearby one through DNS: the CDN answers the hostname lookup with the address of a server close to her. Some CDNs instead announce one address from many locations, called anycast. The network then routes her to the closest. If that server does not have a segment yet, it fetches it once from prepared storage and keeps a copy for the next viewer.
The interactive version of this example is available when JavaScript loads.
The playlist maps playback time to segments. To seek, the player finds the segment that covers the new time. To change quality, it fetches the next segment from a different quality’s list. Audio and captions follow the same timeline.
Step 4: count views and delete a video
While Asha watches, her player sends small batches of watch events to a separate intake. Each event carries an ID and the seconds watched. The intake appends them to a durable log, such as Kafka, and answers at once, so an event survives even while counting is down. A count processor reads the log and decides when her session becomes a view. Here the rule is thirty seconds of watching, or finishing a shorter video. That is an illustrative product rule, not any real service’s definition.
Every few seconds, the processor refreshes each video’s total in a store of its own, which the catalog API reads when it shows a video’s details. A refresh writes one row for every video watched since the last one, thousands at once, and in the catalog database the next permission check would queue behind that burst. In a separate store, counting can lag or break while videos keep playing.
When Dev deletes the lesson, the API marks the video removed. New playback requests are refused at once. Sessions already running end when their permission expires. Files already downloaded to a phone stay there, because nothing can reach into a device and remove them. The stored files are deleted later, once the retention period allows.
The interactive version of this example is available when JavaScript loads.
That is the full functional design. In an interview, this is the moment to stop and ask where to go deeper. The sections below are the usual pushes, roughly in the order interviewers make them.
The wifi drops at 425 MB. Does Dev start over?
Dev’s lesson is 10 minutes long, recorded at 8 megabits a second. 600 seconds × 8 megabits ÷ 8 is 600 MB. Say his home connection uploads at 20 megabits a second. The file is 4,800 megabits, so it needs 240 seconds: four unbroken minutes. At 425 MB his router restarts, and the connection is gone for half a minute.
Dev is not unusual. Creators upload 100,000 videos a day. 100,000 × 600 MB is 60 terabytes a day, and any of those uploads can lose its connection partway.
The simplest code posts the file to the API, which writes it to object storage. That is how a profile photo usually travels, because the server resizes it on the way in. Here it goes wrong three ways. The API servers now carry 60 terabytes a day of bytes they never need to read. Each upload holds a server connection for four minutes, where an ordinary request holds one for milliseconds. And when the wifi drops at 425 MB, the request fails, and Dev starts again from byte zero.
So take the API out of the path. The API checks that Dev owns v73, then signs a URL, such as an S3 presigned PUT. For a few minutes, that URL lets his browser write one object straight into storage. The API servers now carry none of the 60 terabytes. Replay the drop. One PUT is one attempt, and storage keeps nothing from a request that did not finish. Dev sends 425 MB, loses them, then sends all 600 MB again. That is 1,025 MB to deliver a 600 MB file. On a connection that drops every three minutes, a four-minute upload never finishes at all.
The fix makes the file many small uploads instead of one large one. Cut it into numbered parts of 50 MB, so the 600 MB lesson is 12 parts. The API starts a multipart upload in storage and signs one short-lived URL per part. Each URL names one object, one upload and one part number, so it can write nothing else. The browser sends the parts, usually several at once, which also speeds up a fast connection.
Replay the drop, with one part in flight at a time to keep the arithmetic simple. When the wifi fails at 425 MB, parts 1 to 8 are stored: that is 400 MB. Part 9 was 25 MB in, and that partial part is thrown away. After reconnecting, the browser asks the API what arrived. The API asks storage which parts it holds and gets 1 to 8. It signs fresh URLs for the rest, because the old ones may have expired during the outage. The browser sends part 9 again from its start, then parts 10 to 12. In total 625 MB cross the network, and only 25 MB of them cross it twice.
Move the drop point below and compare the two tabs. A drop that lands exactly between two parts costs nothing at all.
The interactive version of this example is available when JavaScript loads.
Parts raise three new questions.
The first is when the video exists. Dev’s browser says “complete, parts 1 to 12”. If the API accepts that, it is trusting the browser. A buggy client can finish with a part missing. A hostile one can send far more bytes than it declared, because a part URL does not limit the file’s total size. So the completion step checks the list of parts and the final size against what Dev declared at the start.
It also checks a checksum of the whole file. That catches a file damaged or cut short on the way. It does not stop a hostile client, which simply declares the checksum of its own bad file; the size check and the inspection below handle that one.
One detail catches people. The ETag that S3 returns for a multipart upload is not a hash of the whole file, so it cannot serve as that checksum. Instead, the upload asks for a full-object CRC checksum when it starts. The browser computes the same checksum as it reads the file, and sends it with the completion. S3 computes it over the assembled file and refuses the completion if the two differ.
The second is the upload nobody finishes. Dev closes his laptop after part 5 and never comes back. 250 MB of parts now sit in storage. They are not a file anyone can see, and they are still billed. So an upload gets a deadline. Past it, the service aborts the upload, and storage deletes its parts. A lifecycle rule that aborts incomplete multipart uploads after a few days catches anything the service misses.
The third is the file itself. A complete, checked upload is still only bytes, and nothing yet says it is a video. So a worker opens it in isolation before anything trusts it. It checks the container, the codecs, the duration and the dimensions. It runs with limits on CPU, memory, disk and time, because a small crafted file can take a great deal of work to decode. The same inspection feeds the publish decision. A policy check runs before the video can become ready, with human review for flagged files. A rejected video ends in a state Dev can see, never a silent spinner.
Amazon S3 calls this pattern multipart upload: start an upload, send numbered parts, then complete it.
There is a real alternative. The open tus protocol and Google Cloud Storage resumable uploads keep one long upload and resume it from a byte offset. After the drop, the client asks how many bytes arrived and carries on from 425 MB, so it sends about 600 MB in all. That is simpler for the client: one upload, and one number to remember. The price is a server or a store that speaks the protocol, and sending in parallel needs an extension. Underneath, both designs share one idea. Storage remembers how much arrived, and the service checks what arrived before it trusts it.
The gap: A 600 MB file takes minutes to send, and the connection can drop at any byte.
Option 1: Send the file through the API
The browser posts the file to an API server, which writes it to storage.
Works when: Files are small and the server changes them on the way in, like a profile photo.
Breaks when: The API carries 60 terabytes a day it never reads, and a drop restarts from byte zero.
Option 2: One signed URL straight to storage
The API signs one URL, and the browser uploads the whole file directly.
Works when: Files are small enough that starting again costs little, like a thumbnail.
Breaks when: One request is one attempt, so a drop at 425 MB sends 1,025 MB in all.
Option 3: Numbered parts, checked on completion (start here)
One short-lived signed URL per 50 MB part, and after a drop only the missing parts are sent.
Works when: Any upload of more than a few megabytes, on any connection.
Watch for: A completion step that trusts the browser, abandoned parts that keep costing money, and a file that is not really a video.
Fix within it: Check the part list, the size and a whole-file checksum on completion, abort uploads past their deadline, and inspect the file in isolation.
In the interview: Open with option 3, and say the arithmetic: a drop at 425 MB resends 25 MB, not 425. Mention option 2 only to say why one request still restarts. Offer a byte-offset protocol such as tus if the interviewer wants something simpler on the client.
Say this: Dev must not lose the 425 MB he already sent, and video bytes should never pass through our servers. So the API signs one short-lived URL per numbered part, and the browser sends the parts straight to object storage. After a reconnect it sends only the missing ones. On completion we check the part list, the size and a whole-file checksum, and abandoned uploads expire.
A two-hour lecture takes three hours to process. How do you make it minutes?
Dev’s upload is complete and checked. Now it has to become something a phone can play. That is transcoding: decode the camera file, then encode it again at each quality viewers need. This design prepares three, at 0.5, 1.5 and 4 megabits a second, plus an audio track and thumbnails.
Transcoding is slow. Say one worker needs 1.5 minutes of computer time for every minute of source to produce all three qualities. The number is illustrative; measure your own for each recipe. The promise was that a 10-minute upload is watchable within about 10 minutes. On one worker, Dev’s 10-minute lesson takes 10 × 1.5 = 15 minutes, so it has missed the promise already. The same week he uploads a two-hour lecture. 120 × 1.5 is 180 minutes, and his students wait three hours.
The queue already has many workers, so the first idea is to add more. It does nothing. A job belongs to one worker, and that worker reads the lecture from its first frame to its last. Ten idle workers do not make one busy worker faster.
The next idea gives each quality its own worker. Three workers encode the three qualities at the same time, and the wait becomes the slowest of the three. That would help most if the three cost the same, and they do not. A 1280 × 720 picture has four times the pixels of a 640 × 360 one, and encoding work grows roughly with pixels. So the top quality alone does more than half the work, and the wait falls from 180 minutes to something over 90. Each worker also still reads all two hours. A four-hour video waits twice as long again, so the wait still grows with the length of the video.
The fix splits the video, not the qualities. Cut the lecture into chunks two minutes long. 120 ÷ 2 is 60 chunks. Each chunk is a small job of its own: 2 × 1.5 is 3 minutes of encoding. Sixty workers take one chunk each and finish together in 3 minutes. Add a minute to split the source and a minute to put the pieces back together, and the lecture is ready in 5 minutes instead of 180. Dev’s lesson is 5 chunks, and it is ready in 5 minutes too. With 16 workers, the 60 chunks run in four waves of 16, 16, 16 and 12. That is 12 minutes of encoding, and 14 in all. The longest chunk, not the whole video, now sets the wait.
The cut cannot go just anywhere. Compressed video stores most frames as changes from an earlier frame. Only a keyframe carries a whole picture and can be decoded on its own. In H.264 the safe kind is an IDR frame, which no later frame looks back past. Suppose the splitter cuts at exactly 2:00, and the last keyframe was at 1:58. The first frames of chunk 2 describe changes to pictures in chunk 1, which chunk 2’s worker never reads. So the splitter cuts only at keyframes, and a chunk is about two minutes long, not exactly two. Encoders usually place one at least every ten seconds or so. When a file has few, the worker can instead start decoding at the keyframe before its cut and throw away the frames before the cut. That costs a little extra decoding.
Pick a worker count below and watch the chunks light up in waves.
The interactive version of this example is available when JavaScript loads.
Splitting creates new problems.
The pieces have to be put back together in order. The work is now a small graph of tasks. Split the source. Encode every chunk at every quality. Encode the audio once, since it is cheap. Pull frames for thumbnails. Assemble each quality into segments and playlists. Check the result, then publish. A task starts when the tasks it waits for have finished. A workflow engine can run this graph. So can a job table where each task lists the tasks it depends on.
The seams can show. Each chunk is encoded without seeing its neighbours, so the encoder cannot save bits in an easy chunk to spend on a hard scene in the next one. Picture quality can step at a boundary. Check the chunk edges whenever you tune a recipe.
The player will switch between qualities mid-video, as the next deep dive shows. That switch is clean only when segment 35 covers the same seconds in every quality. So each chunk worker forces a keyframe at every multiple of 4 seconds on the video’s own clock, in all three qualities. After the chunks are joined, the assembly step cuts each quality at those keyframes into 4-second segments. A chunk edge that falls between two multiples only adds one extra keyframe inside a segment.
Five minutes is still five minutes. For a long video, run each chunk’s lowest quality as its own task, ahead of the others. Publish those as a generation of their own, so students can start watching. Publish the full set as a new generation when it is done.
Chunking cuts the wait, not the work. 100,000 uploads × 10 minutes × 1.5 is 1.5 million worker-minutes a day. A day has 1,440 minutes, so about 1,040 workers are busy on average. A two-hour lecture that takes 60 of them at once competes with the short uploads behind it. So the queue needs priorities and a cap on how many workers one video may hold, and the fleet grows and shrinks with the queue. Cheap machines the cloud can reclaim at any moment fit well here, because a later deep dive makes the design survive a worker that vanishes.
Which qualities, and in which codec? A common start is H.264, because almost every device can decode it. In Apple’s example H.264 ladder, a 640 × 360 picture uses 365 kilobits per second and 1280 × 720 uses 3,000 to 4,500. So this design’s 0.5 and 4 megabit rungs are roughly a 360p and a 720p picture. Newer codecs such as VP9 and AV1 need fewer bits for the same picture. They cost more to encode, and older devices cannot play them.
Whether a newer codec pays is arithmetic. Use invented prices. Say an extra encode costs $2 and saves 0.02 GB on every full viewing. At $0.05 per GB of delivery, each viewing saves 0.02 × 0.05 = $0.001. The encode pays for itself after $2 ÷ $0.001 = 2,000 full viewings. Most of Dev’s lessons never get there. So start every video on a small H.264 ladder, and add the expensive codec once a video proves it will be watched.
Storage follows the same logic. The three prepared qualities total 6 megabits a second. 100,000 videos × 600 seconds × 6 megabits ÷ 8 is 45 terabytes a day, beside 60 terabytes of originals. (60 + 45) × 365 is about 38 petabytes a year, for one copy. Keeping all of it on the fastest storage tier is the largest waste in the system. Lifecycle rules move originals and rarely watched videos to cheaper, slower tiers. Keep one high-quality source, so any video can be encoded again if it suddenly becomes popular.
One more saving is in the packaging. Apple devices play HLS playlists. Many web and Android players use DASH, an open standard. Both can point at segments stored as fragmented MP4, a layout standardised as CMAF. So package the segments once in that layout and write two small playlists. You then store and cache one set of segments instead of two. With DRM, sharing one set also needs every target player to accept the same encryption scheme, and some older devices do not.
The gap: One worker reads a video from its first frame to its last, so the wait grows with the video.
Option 1: One worker transcodes the whole file
A single worker reads the source and writes every quality.
Works when: Clips of a few minutes, where the whole encode fits inside the ready target.
Breaks when: A two-hour video takes 180 minutes, and more workers cannot help.
Option 2: One worker per quality
Three workers encode the three qualities at once, each reading the whole source.
Works when: Qualities that cost about the same, which a ladder of picture sizes rarely has.
Breaks when: The top quality does over half the work, and the wait still grows with the video.
Option 3: Split at keyframes, encode chunks in parallel (start here)
Cut 2-minute chunks at keyframes; with 60 free workers, the lecture is ready in 5 minutes.
Works when: Any video longer than a few minutes.
Watch for: Seams at the chunk edges, and qualities whose segments must line up.
Fix within it: Check quality at the edges when tuning a recipe, and force keyframes on the same 4-second grid in every quality.
In the interview: Open with option 3, with the arithmetic: 60 chunks on 60 workers is 3 minutes, plus a minute either side. Name the keyframe rule before the interviewer asks for it. Option 2 is worth a sentence as the idea that stops helping once videos get long.
Say this: One worker needs 180 minutes for a two-hour lecture, and more workers cannot help while one holds the whole file. So I cut the source at keyframes into 2-minute chunks and encode all sixty at once. That takes about 5 minutes, including the split and the assembly. The lowest quality can publish first, so a long video becomes watchable even sooner.
The train leaves the station and the video freezes. What does the player do?
Asha taps Play on the station platform. The station wifi moves 8 megabits a second, and the first frame appears in 2 seconds. The train pulls out, and the open track gives her 2 megabits a second. Sixteen seconds into the lesson, the picture freezes and a spinner turns.
To see why, look at what the player keeps. It holds a few seconds of video downloaded ahead of what Asha is watching. That reserve is the buffer. While a segment downloads, the buffer drains at one second per second, because Asha keeps watching. When the segment lands, four seconds are added. The player stops downloading once it holds 20 seconds.
Start with the simplest player: every viewer gets the 4 megabit version. At the station, one 4-second segment is 4 × 4 = 16 megabits, and 8 megabits a second downloads it in 2 seconds. Each segment adds 4 seconds of video and costs 2 seconds of waiting, so the buffer grows.
Now do the arithmetic on the open track. Say Asha has 6 seconds buffered. The next segment is still 16 megabits, and at 2 megabits a second it takes 8 seconds to arrive. The buffer runs out after 6, so the video freezes for 2 seconds. Then the segment lands and plays for 4 seconds, and the next one needs 8 again. The experiment below rides a whole journey: the station, the open track, a tunnel at 0.6 megabits and the next town at 3. On it, the fixed 4 megabit player is frozen for 26 of the 70 seconds.
The next idea prepares several qualities, 0.5, 1.5 and 4 megabits, and puts a menu on the player. Take the 1.5 megabit version of the same 4 seconds. It is 6 megabits and downloads in 3 seconds. The buffer drops from 6 to 3, then gains 4, ending at 7. The lower quality kept the video playing and grew the buffer.
But Asha has to choose, and she learns the connection dropped only after the picture has frozen. If she stays on 1.5 to be safe, she never freezes on this train. She also watches a blurry picture on the station’s fast wifi. And on a weaker signal of 1.2 megabits, even 1.5 freezes. The right quality changes every few seconds, and a person cannot keep up with that.
So the player chooses, once per segment. This is adaptive bitrate. After each download, the player knows how many megabits arrived and how long they took. A 16-megabit segment that took 8 seconds says the connection is moving 2 megabits a second. For the next segment, the player picks the highest quality at or below 80% of that speed. 80% of 2 is 1.6, so it picks 1.5. If less than one segment is buffered, it drops straight to the lowest.
It also starts low. The first segment at 0.5 megabits is 2 megabits, which the station wifi moves in a quarter of a second. So the first frame appears after 0.25 seconds instead of 2, and the player steps up once it has measured the connection.
Replay the train. At the station the player climbs to 4. On the open track, the first slow download pulls it down to 1.5. In the tunnel it falls to 0.5. In the next town, 3 megabits a second, it climbs back to 1.5, because 80% of 3 is 2.4. It never freezes, and the picture averages about 1.9 megabits a second.
Ride the journey below. The first tab is the fixed 4 megabit player. The second is Asha choosing 1.5 and never changing it. The third adapts.
The interactive version of this example is available when JavaScript loads.
Switching creates the next problem. Say the player plays segment 34 at 1.5 megabits and fetches segment 35 at 4. For the join to be seamless, segment 35 must cover exactly the next seconds in both qualities. It must also begin with a keyframe, an IDR frame in H.264. If its first frames point back to a 4 megabit picture the player never downloaded, the moment after the switch breaks up. A player can switch between qualities that do not line up. It has to download overlapping pieces of both and throw some away, which spends bytes at the worst moment. So every quality shares the same segment boundaries, and every segment starts with a keyframe. That is why the last deep dive forced keyframes on the same 4-second grid in every quality. RFC 8216, the HLS standard, requires matching timestamps across the alternative streams. Apple’s authoring specification requires every video segment to start with an IDR frame, and recommends 6-second segments.
A download can also go wrong halfway. Say the player starts a 4 megabit segment just as the train enters the tunnel. At 0.6 megabits a second, 16 megabits take about 27 seconds, far longer than the buffer lasts. So the player watches each download as it runs. When one falls behind the buffer, the player abandons it and fetches the 0.5 megabit version of the same segment. That is 2 megabits, about 3.3 seconds in the tunnel.
Segment length is a trade. Shorter segments let the player react sooner, and they also mean more requests. And no player can beat a connection slower than its lowest quality. On a 0.3 megabit link, even the 0.5 rung cannot keep up. That is why the promise names the slowest connection it covers.
The rule in the experiment is deliberately simple. Real players do better. Some decide mainly from how full the buffer is, not from the measured speed. BOLA is a well-known example. Many players combine both signals: the speed says what the link can carry now, and the buffer says how much risk is affordable. The model also assumes a segment plays only once it has fully arrived, and it ignores connection setup and packet loss.
None of this touches a server. The player chooses the quality one segment at a time, from what it just measured and what it has left.
The gap: A segment must finish downloading before the buffer runs out, and the connection can halve between one segment and the next.
Option 1: One fixed high quality
Every viewer gets the 4 Mbps version.
Works when: Every viewer has a fast, steady connection.
Breaks when: On the train each 16-megabit segment takes 8 seconds, and the video is frozen for 26 of 70 seconds.
Option 2: Several qualities, chosen by the viewer
The video exists at 0.5, 1.5 and 4 Mbps, and a menu lets the viewer switch.
Works when: The viewer knows the connection in advance, such as someone saving mobile data.
Breaks when: The viewer learns the connection dropped only after the picture froze.
Option 3: Adaptive bitrate (start here)
The player picks each segment’s quality from the last measured speed and the buffer left, starting low.
Works when: Recorded video on any connection the service supports.
Watch for: A switch into a segment that does not line up, or a download that falls behind in a tunnel.
Fix within it: Give every quality the same segment boundaries with a keyframe at each start, and abandon a slow download for a smaller copy of the same segment.
In the interview: Open with option 3, and do the one-segment arithmetic out loud: 16 megabits at 2 megabits a second is 8 seconds, against 6 buffered. Name the two rules that make a switch clean, shared boundaries and a keyframe at each start, before you are asked.
Say this: The video freezes because a 4-second segment at 4 megabits takes 8 seconds on a 2 megabit connection, and the buffer runs out first. So the player measures every download and picks the next segment’s quality from that speed and the buffer left. It starts low, so the first frame comes fast. Every quality shares segment boundaries and every segment starts with a keyframe, so a switch lands cleanly.
A worker crashes after writing half the files. What does the viewer see?
Worker A is preparing Dev’s 10-minute lesson. At 4-second segments, each track is 600 ÷ 4 = 150 segments. Three qualities and the audio make 600 segment files, plus playlists and thumbnails. A has written 300 of them when its machine loses power. The queue never got an acknowledgement, so once its redelivery timer runs out, it delivers the job again, to worker B.
Two questions matter. Can a viewer ever see the half-written files? And can the retry do damage?
To keep the story small, picture one worker doing the whole job. With chunks, every task has its own lease, and the same rules apply to the task that publishes.
The simplest design writes every attempt to the same paths, such as videos/v73/720p/seg34.m4s, and points the playlist at them. Replay the crash with a video that is already live and being encoded again with a better recipe. B rewrites the same 600 paths. Each file lands whole, because a storage write is all or nothing, but the set does not. Halfway through, the folder holds 300 files from the new encode and 300 from the old one. Edge caches hold whichever version they fetched first under the same URLs, and they have no reason to fetch again. Two encodes need not share timestamps or settings, so a player crossing from one to the other can stutter or break.
So never write where a viewer can look. Each attempt writes its own folder. When B finishes, it checks that every file its playlist names exists. Only then does one database transaction point v73’s active_generation at B’s folder, g8, and set the state to ready. Replay the crash. A’s 300 files sit in a folder nothing points at. B’s folder is complete before any viewer can reach it. Going from processing to ready is one row changing, so a viewer sees either no video or the whole video.
That hides the half-written files. It opens a quieter problem, because A may not be dead. A power cut is the easy case. A long garbage-collection pause, a lost network or a stuck disk leaves a process that is frozen, not gone.
Workers keep a job through a lease. Say a worker sends a heartbeat every 10 seconds, and if none arrives for 30, the lease expires and another worker may claim the job. The queue only delivers messages; the lease, in the job row, decides who owns the job. A worker that receives a message claims the job only if nobody holds it or its lease has expired. A redelivered message that finds a live lease is left on the queue for later. So a duplicate never pushes out a healthy worker, and a message still exists if that worker dies.
Now watch the timeline. A freezes at 10:03. Its lease expires at 10:03:30, and the next delivery of the message lets B claim the job. B needs about 15 minutes and publishes g8 at 10:19. At 10:20 A wakes up. It does not know its lease expired. It finishes writing its own folder, checks it, and moves the pointer to it. A frozen process has just replaced a finished video.
The same bug has a second version that needs no crash at all. Dev’s video was encoded with recipe 3, and that encode is live. A slow job for recipe 2, started earlier, finishes afterwards and publishes. Viewers are moved back to the older encode.
The fix gives every claim a number. Each time a worker claims the job, the job row’s owner number, its epoch, goes up by one, and the worker keeps its copy. A claimed the job as 41. B’s claim made it 42. Publishing is then one transaction with three conditions. The job row must still carry the worker’s epoch. The files must encode the video’s current source, because Dev may have replaced the file while the job ran. And the recipe must not be older than the one already live, so the pointer only moves forward.
Replay the timeline. At 10:20 A tries to publish as 41. The job row says 42, so the transaction changes nothing and rolls back. g8 stays live. A leaves a folder of files behind, nothing worse, and a cleanup job deletes folders no generation points at. It waits longer than any job takes, because a folder still being written is unreferenced too. The late recipe-2 job passes the owner check, because it is a different job with a valid owner of its own. It fails the forward-only check. Distributed locking calls a number like this a fencing token. The check sits inside the same transaction that moves the pointer, because anything checked earlier can change before the write.
Dev may also edit the title while the job runs. That edit changes the same video row. The publish step deliberately ignores the title and description, so a title edit never blocks a transcode.
Step through A freezing, B taking over, and A waking up. The first beats look the same with or without the epoch. When A wakes, the epoch check refuses it.
The interactive version of this example is available when JavaScript loads.
Here is the publish step as one transaction. The first statement is the epoch check. The second moves the pointer only for the current source and a recipe that is not older, and it refuses a removed video.
The interactive version of this example is available when JavaScript loads.
One gap remains, and it opens before any worker runs. When Dev’s upload completes, the API commits the job row, then sends a message to the queue. If it crashes between the two, the job exists and nothing will ever run it. Send the message first instead, and a crash leaves a message for a job the database never recorded. Two systems cannot be written in one step.
So write only to the database. The API commits the job row and an outbox row in one transaction. A small relay reads unsent outbox rows and puts them on the queue, retrying until the queue accepts. The relay can send a message twice. The job’s identity, the video with its source version and recipe, makes the second one harmless. A worker finds the job already complete and reuses g8 without transcoding anything. The worker acknowledges the queue message only after publishing. A crash before the acknowledgement then causes a redelivery, never a lost job. The idempotency article follows the same lost-response problem at an API boundary.
The interactive version of this example is available when JavaScript loads.
Storage events need the same care. S3 delivers event notifications at least once, so the same event can arrive twice. Handle each one idempotently, and never treat notifications as the only record of unfinished work. A reconciliation job regularly finds uploads and jobs that stopped moving. A file that fails the same way every time gets a few retries, then a visible failed state. Retrying a broken file forever only burns money.
The diagram barely changed, but the guarantee did. A job recorded in the database always reaches the queue. A worker holding an old number can leave files behind, but it can never change what viewers see.
The gap: Writing a generation takes minutes and many files, and the queue delivers a job again whenever it gets no acknowledgement.
Option 1: Overwrite the same file names
Every attempt writes to the same paths, and the playlist points at them.
Works when: Nobody reads the files while they are written, and one worker runs each job.
Breaks when: A retry mixes two encodes in one folder, and caches keep whichever copies they fetched first.
Option 2: A folder per attempt, published after a check
Each attempt writes its own folder, and the pointer moves only after every file is checked.
Works when: Only one attempt ever reaches the publish step.
Breaks when: A frozen worker wakes after its lease expired and moves the pointer to its own folder.
Option 3: Owner epochs and a publish that only moves forward (start here)
The publish transaction checks the worker’s epoch, the current source and the recipe order before moving the pointer.
Works when: Always: a late worker can leave files behind but never change what viewers see.
Watch for: A job committed to the database whose queue message was never sent.
Fix within it: Commit an outbox row with the job, and let a relay send it until the queue accepts.
In the interview: Open with option 3, and reach it through option 2: a folder per attempt hides half-written files, but two workers can still both publish. Say “the epoch is checked in the same transaction that moves the pointer”. Add the outbox when the interviewer asks what happens if the queue never hears about the job.
Say this: A crashed worker leaves half its files, and the queue hands the job to another worker. Each attempt writes its own folder, checked before viewers move to it. Each claim raises the job’s epoch, and the publish transaction refuses a stale epoch, an old source or an older recipe. The job and its outbox row commit together, so no job is lost between the database and the queue.
A video goes viral. What protects the origin?
Start with how much video leaves the system. 10 million viewers each watch 20 minutes, which is 1,200 seconds, at 2 megabits a second. 10,000,000 × 1,200 × 2 megabits ÷ 8 is 3 petabytes of video a day. Spread over the day’s 86,400 seconds, 10,000,000 × 1,200 ÷ 86,400 is about 139,000 people watching at any moment. 139,000 × 2 megabits is about 278 gigabits a second. Evenings are busier. Assume the peak is three times the average: about 834 gigabits a second.
Now the scene. One evening, at that peak, a cooking video of Dev’s goes viral. Tens of thousands of viewers, spread across hundreds of cities, press Play on it within a minute.
The simplest design streams segments from the application servers, which read them from storage. A server with a 10 gigabit link pushes at most 10 gigabits a second. So 834 at the peak needs about 84 servers doing nothing but pushing bytes. They also sit in one or two regions, far from most viewers, so segments cross oceans to reach phones. The 2-second first frame does not survive that. The requests never stop, either. One video segment every 4 seconds for each of 139,000 viewers is about 34,750 requests a second on average, three times that at the peak, before counting audio. Segments have to be plain files a cache can hold, not API calls.
So put a content delivery network, a CDN, in front of storage. Its edge servers sit in hundreds of cities near viewers. Each edge keeps copies of the segments it has served. It asks the origin, the prepared storage behind it, only for what it lacks. The number that sizes the origin is the share of bytes the edges serve from their own copies, the byte hit ratio. Say it is 95% at the evening peak. The origin then serves 5% of 834, about 41.7 gigabits a second.
Now replay the viral video. Nobody has watched it yet, so it is missing from every edge at once. Say 500 edge servers each get their first request for segment 1 in the same second. Each misses, and each fetches the file from the origin. At 4 megabits, a 4-second segment is 2 MB. So the origin sends 500 × 2 MB = 1,000 MB, 8 gigabits, in one second, all of it the same file. Then the crowd reaches segment 2, and it happens again, for every segment of every quality the crowd watches.
The fix is a middle layer called an origin shield. Edges ask the shield before the origin, and the shield keeps at most one fetch per file in flight. When 500 edges miss on segment 1 together, the first request goes to the origin, and the other 499 wait for its answer. That move is request coalescing. Replay the viral video. Each of its files costs the origin one fetch per shield, not one per edge: 2 MB instead of 1,000. Once the shield holds a file, every edge fills from the shield.
The interactive version of this example is available when JavaScript loads.
The shield merges misses for the same file. It does nothing for many different files going cold at once. Say an evening brings a burst of new uploads that people start watching, and the byte hit ratio at the peak falls from 95% to 80%. The origin now serves 20% of 834, about 166.8 gigabits a second. The audience did not change, and the origin’s load quadrupled. A cache still refilling after it was emptied, at 50%, would send 417. So limit how long waiting requests wait and how many different files the shield fills at once, and size the origin for the misses at the peak.
Measure those misses in bytes, not requests. A playlist and a 2 MB segment each count as one request. So a request hit ratio can look healthy while the misses are the largest files.
Slide the byte hit ratio below and watch the origin against an illustrative budget of 60 gigabits a second.
The interactive version of this example is available when JavaScript loads.
Some misses can be predicted. A creator with a large following is watched the minute a video goes up. For those creators, push the first segments of each quality to the edges before the new-video notification goes out. Every warmed video nobody watches is storage and transfer spent for nothing, so warm only uploads that are sure to be watched. Netflix works this way at scale: its Open Connect program describes nightly content fills to servers placed inside internet providers.
The second new problem is permission. Dev’s video may be private, or removed tomorrow, and the edges must still check who may watch. The obvious move puts a per-viewer token in each segment URL. If the CDN treats the whole URL as the cache key, a hundred thousand viewers make a hundred thousand keys for one file. The byte hit ratio collapses, and origin traffic climbs with the same audience. When origin traffic jumps with no more viewers, count the cache keys first. CDNs can check a signed URL and leave its signature out of the key, which fixes the cache. A chore remains: the playlist lists every segment, so each viewer would need a playlist of their own with every URL signed.
So keep identity out of the URL. Segment URLs include the generation. A file’s content therefore never changes, and it can be cached for a long time. The playback API gives Asha’s player a signed cookie that covers one folder, the folder of g8, for a few minutes. The CDN serves video from a subdomain of the site, so the cookie reaches it. Every segment request carries the cookie, and the edge checks the signature before serving. Every authorized viewer then shares one cached copy of each segment.
Before the cookie expires, the player asks the API for a fresh one, and that renewal is where a removed video stops playing. The renewal covers the generation the player is using as well as the live one. So a player still on g8 keeps working after a new generation is published, and moves to the new one when it next fetches the playlist. Old generations stay until no session can reference them. Anyone who copies the cookie can use it until it expires, the way anyone can use a paper ticket. So keep the expiry short. The CDN article covers how cache lifetime and origin load trade against each other.
Deletion runs in order. Mark the video removed, so no new playback starts. Let running sessions expire. A cookie or signed URL that lasts five minutes means up to five minutes of continued access. One signed cookie cannot be cancelled on its own. Cutting access short means changing the signing key, or an edge check against a list of revoked sessions. Video already buffered on a phone plays on after that. Purge the edges where needed. Delete the stored files after the retention period. Encrypting the video and requiring a license key to play it, known as DRM, gives stronger control. It also adds a license request to every start, and another service that can fail.
A second CDN provider is sometimes offered as resilience. During an origin outage, it helps only if it can reach a working origin. It starts with almost nothing cached, and every miss goes to the origin that is down.
So the edges carry the audience. The origin is sized for what the edges miss, and the shield makes each missing file cost one fetch.
The gap: Every byte an edge does not hold comes from the origin, and a new video is missing from every edge at once.
Option 1: Serve video from the application servers
The API servers read segments from storage and stream them to viewers.
Works when: A private tool with a handful of viewers.
Breaks when: 834 Gbps at the peak needs about 84 servers pushing bytes, far from most viewers.
Option 2: A CDN in front of storage
Edge servers near viewers cache segments, and the origin serves only the misses.
Works when: Videos are already warm in the cache, as on an ordinary evening.
Breaks when: A new viral video misses on every edge at once, and each edge fetches the same file separately.
Option 3: A CDN with an origin shield (start here)
A middle cache keeps one origin fetch per file in flight, so 500 edges missing together cost one request.
Works when: Any service where a video can go viral.
Watch for: Many different files going cold at once, which the shield cannot merge.
Fix within it: Limit waiting requests and concurrent fills, and size the origin for byte misses at the peak.
Option 4: Warm the cache before viewers arrive
Push a popular creator’s first segments to the edges before the notification goes out.
Works when: Demand is predictable, such as a creator with a large following.
Watch for: Warmed videos nobody watches, which cost storage and transfer for nothing.
In the interview: Open with option 3, and size the origin in bytes from the peak and the byte hit ratio. Add option 4 when the interviewer asks about creators whose every upload is watched at once.
Say this: The CDN carries the bytes, and the origin is sized for the share of bytes that miss at peak. A new viral video misses on every edge at once, so an origin shield merges those misses into one fetch per file. For creators whose uploads are always watched, we warm the edges before the notification goes out. Permission is a short-lived signed cookie, checked at the edge and kept out of the cache key.
Retries inflate the view count. How do you count each view once?
Asha watches thirty-one seconds of Dev’s lesson, then the train enters a tunnel. Her player had just sent a batch of watch events, and the acknowledgement never came back. So after reconnecting, it sends the same batch again.
Decide what a view is before choosing a counter. Here, a view is one playback session that reaches thirty seconds of watching, or finishes a shorter video. One person can produce several sessions, so this counts views, not unique viewers.
Now the scale. Each player sends a batch every 10 seconds. The last deep dive found about 139,000 people watching at any moment, and 139,000 ÷ 10 is about 13,900 batches a second. That is twenty-four times the 579 detail reads a second the catalog serves, so watch events are the busiest write path in the system. A viral video aims a large share of them at one total.
The simplest counter adds one for every event that reaches the server. Replay the tunnel. Asha’s batch arrives twice, and her one view counts twice. Counting segment requests is worse. Thirty seconds is eight 4-second segments, and every retried download is one more request.
So give the view an identity. When a session reaches thirty seconds, it gets a qualification with a fixed ID. The database adds one only for an ID it has not seen. It inserts the ID into a table with a unique key, and increments the video’s count in the same transaction. Replay the tunnel. The second copy finds its ID already stored and adds nothing. For most videos, that is enough.
Then a video goes viral. At a premiere, tens of thousands of sessions a second qualify for one video. Every one of them must update the same row, and each update waits for the row lock the one before it holds. The row takes them one at a time. The queue behind it grows until the database falls behind, and that database also serves the catalog.
The fix counts in a stream and writes totals in batches. Watch events go to their own intake, never to the catalog database. A stream processor, partitioned by session ID, merges each session’s watched seconds. Resending seconds 10 to 20 then adds nothing. When a session reaches thirty seconds, the processor emits one qualification with a fixed ID. Qualifications are partitioned by that ID, so an ID and all its repeats reach the same processor. That processor keeps the IDs it has seen and a running total per video. Every few seconds, it writes one small update per video to the view-count store. A viral video’s views land in every partition, so each flush writes one update per partition for it, instead of one per view.
Replay the tunnel. The repeated batch lands on the same partition as the first. Its seconds are already merged, so nothing new qualifies. Replay the premiere. Tens of thousands of qualifications a second become one small write per partition every few seconds. Counting now scales on its own. It can fall behind, or fail, without delaying a single playback start.
Deliver the five messages below one at a time. The “+1 per message” counter is the simplest one. The “+1 per new ID” counter is the rule the other two designs share.
The interactive version of this example is available when JavaScript loads.
The stream brings two problems of its own.
A processor can crash after writing a batch to the database but before recording that it did. When it restarts, it replays that batch, and the totals grow twice. Apache Flink and similar engines checkpoint each partition’s state, so a crash resumes from the last checkpoint. The database write needs the same care. Tag each update with its batch number, and let the database apply each number once. A replayed batch then adds nothing. That holds only if a replayed batch has the same number and the same contents, so batches are cut at checkpoints, never by the clock.
The set of seen IDs cannot grow forever, so it keeps a window, say seven days. That window creates the second problem. After an outage, somebody replays a month of events through the live path to repair the counts. Those IDs left the window weeks ago, so every repeat looks new, and the counts jump. So never replay old data live. Rebuild it into a separate table, check it, then swap it in.
Another tool often comes up here. HyperLogLog estimates how many distinct items it has seen, using very little memory. Adding the same ID twice changes nothing, so over qualification IDs it gives a view count that retries cannot inflate. Over viewer IDs it answers a different question: about how many unique viewers. Either way the answer is an estimate. Redis describes the error of its HyperLogLog as a standard error of 0.81%, which is not a maximum. It suits a rough total, not a count that must be exact.
A view gets an identity before it is counted, and the counter adds one per new identity, never one per message.
The gap: A phone that hears no acknowledgement sends its events again, so the same view can arrive twice, or ten times.
Option 1: Add one for every event received
Each watch event that reaches the server adds one to the count.
Works when: Events are never retried, which no phone in a tunnel promises.
Breaks when: The retry after the tunnel counts Asha’s one view twice.
Option 2: Deduplicate, then update one counter row
The database adds one only for a qualification ID it has not seen.
Works when: Views arrive slowly enough for one row to take them, as on most videos.
Breaks when: A viral video sends every update to the same row, one lock at a time.
Option 3: Deduplicate in a partitioned stream, write totals in batches (start here)
Partition qualifications by ID, keep the IDs seen, and write each video’s totals in small batches every few seconds.
Works when: Any video, viral or not.
Watch for: A replayed batch after a crash, and replays older than the deduplication window.
Fix within it: Number each batch so a replay adds nothing, and rebuild old data into a separate table instead of replaying it live.
Option 4: Estimate with HyperLogLog
Add each qualification ID, or each viewer ID, to a HyperLogLog, which ignores repeats and estimates the distinct count.
Works when: A rough total is enough, or the question is unique viewers.
Watch for: An estimate whose error has no fixed ceiling, never an exact count.
In the interview: Open with option 3, and define the view first: one session reaching thirty seconds, with a fixed ID. Option 2 is right until one video goes viral. Mention option 4 if the interviewer asks about unique viewers or a rough total.
Say this: Phones retry, so the same watch event can arrive twice, and a view needs an ID before it is counted. The processor merges each session’s watched seconds and emits one qualification with a fixed ID at thirty seconds. Qualifications are partitioned by ID, so repeats land where they can be caught. Each partition writes totals in numbered batches every few seconds, and a replayed batch adds nothing.
The interactive version of this example is available when JavaScript loads.
That completes the design. The two sections below are shorter follow-ups that a staff round often adds.
If they push: how does seeking work with audio and captions?
Asha drags the playhead to 2 minutes 13 seconds, which is 133 seconds. The player adds up the segment durations in the playlist to find the segment covering that time. With 4-second segments starting at zero, it is the one from 132 to 136 seconds. Real durations can vary slightly, so the player sums the listed durations instead of dividing.
That segment starts with a keyframe at 132 seconds. The player decodes from there and starts showing frames at 133. It throws away downloads that no longer help. It usually fetches the first new segment at a low quality, because the buffer is nearly empty right after a seek.
Audio and captions sit on the same timeline. After the seek, the player fetches the audio segment that covers 133 seconds. It shows the captions active at that moment, including one that began before the segment did. Switching language picks another audio or caption list from the playlist without moving the playhead. Check each track’s timing during processing: two files that are each valid can still put the voice half a second ahead of the lips.
If they push: what if the playlist reaches another region before the video does?
Dev’s video finishes processing in region A. The database copy in region B learns within a second that g8 is ready. The segments are still copying across the ocean. A viewer in region B gets a valid playlist, then a 404 for the first segment.
The database and the file storage replicate separately, on different clocks. A ready flag in the database says nothing about which region holds the files. So when new videos return 404s in one region only, look first at the generation’s file list and that region’s readiness time.
Sending every cache miss to the one origin that certainly has the files works, but viewers far from that origin wait longer on every miss. So record readiness per generation and per region. Region B sends misses to region A until its own copy is complete and checked, then switches to the local copy. For recorded video, prefer the fallback: a slower first segment beats a video that looks broken. Hold the video back in region B only if crossing the ocean would miss the startup target. Say which one you chose, and why.
Within one region, S3 gives strong read-after-write consistency for each object. That does not turn the database, many files, cross-region copies and CDN caches into one transaction. The generation pointer and the readiness records tie them together.
Titles and permissions need different freshness. A creator who edits a title should see the new title at once, so read the creator’s own view from the primary region. Other viewers can see the old title for a few seconds. Making a public video private is different. A permission change needs a stated upper bound on how long the old permission keeps working. Read replication explains why two reads of the same row can need different freshness.
Walk one upload and one viewing through the final design
Dev receives v73 and u73 and sends numbered parts. The API verifies the file and commits the job with its outbox row. The relay puts the job on the queue, possibly twice. Workers split the source at keyframes, encode the chunks in parallel, assemble generation g8 and check it. The owner with the current epoch publishes g8 in one transaction. Readiness records say which regions can serve it.
Asha asks to play. The API checks her access and returns a short-lived playlist URL for g8. Her player fetches segments through the CDN, and cold misses share one fetch through the shield. Each download changes her buffer, so the player picks the next quality. A seek moves her position on the timeline and changes no files. Her watch events become one qualification, which the stream processor adds to the video’s total.
If Dev deletes the video, new playback stops regardless of counting. If a worker wakes late, its old epoch is refused. If Asha’s connection slows, a lower quality keeps the picture moving.
| Requirement | Where it is met | The trade-off |
|---|---|---|
| FR1 resumable upload and status | API, signed part URLs, original storage, upload record | Part bookkeeping and cleanup of abandoned parts |
| FR2 prepare and publish | Outbox, queue, parallel chunk workers, checked generation | Work can repeat; a stale result is refused |
| FR3 details and access | Catalog, current permissions, short-lived session | Revocation takes up to the signature lifetime |
| FR4 play, seek, audio, captions | Playlist timeline, player buffer, CDN, ready origin | Lower quality protects playback; very slow connections can still fail |
| FR5 views and deletion | Partitioned counting; removal in the catalog | Counts lag; downloaded bytes cannot be recalled |
How does the answer change for YouTube, Netflix or live video?
| Interview variant | What carries over | What changes |
|---|---|---|
| YouTube-style upload platform | Resumable uploads, parallel processing, adaptive playback, counts | Anyone can upload, so abuse review, a long tail of rarely watched videos and creator status pages matter |
| Netflix-style licensed catalog | Prepared qualities, regional delivery, player adaptation | Rights per country, DRM on every start, planned releases, and caches filled before a release |
| Live sports streaming | Segments, adaptation, CDN delivery, playback measurement | Video arrives as it is filmed, so delay from camera to screen, backup encoders and a moving playlist become central |
| Video calls | Codec and network adaptation | Two-way conversation needs a delay far below what segments allow; this design does not fit |
| Short video feed | Prepared qualities and CDN delivery | Many quick starts, prefetching the next clip, and bytes wasted on skipped clips change the startup and cost budget |
For live video, a viewer cannot fetch a segment that has not been filmed yet. Shorter segments cut the wait, but add requests and leave less buffer to absorb a slow download. A recorded film can be prepared completely before the first viewer arrives. That difference changes the design far more than the product name does.
What should an answer reach at each level?
| Level | What the answer shows |
|---|---|
| Intern or mid-level | Separates video details from video bytes. Uploads straight to storage, processes in the background, delivers through a CDN. Shows with numbers why delivery dominates. Explains segments and several qualities. |
| Senior | Designs resumable multipart upload with verification. Splits processing into parallel chunks cut at keyframes. Walks a buffer example and explains adaptive switching. Publishes only checked generations. |
| Staff | Stops stale workers with owner epochs and a publish check that only moves forward. Protects the origin from a viral video with a shield, keeps permission out of the cache key, and counts each view once. Handles regional readiness. |
| Principal | Sets freshness and failure budgets per path. Prices codecs and storage tiers from their break-even. Explains how the design changes for live video or a licensed catalog. |
Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.
By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.