Skip to lesson
‹

Courses / System Design Interview / Chapter 23

Module 3 · Design Real Products · Chapter 23 of 39

Design a Video Streaming Platform

19 sections · ~40 min✓ Fact-checked

Builds on Back-of-the-Envelope Estimates, Content Delivery Networks, Distributed Caches, Message Queues, Blob Stores, Distributed Search, Distributed Task Schedulers and Sharded Counters. Next up: Design a Q&A Site.

Part 1 · Requirements and Scale

The brief

It is 8 pm on the night before the Class 12 chemistry board exam. A teacher in Kota finishes a one-hour revision lecture and uploads it over patchy hostel Wi-Fi. By 11 pm two lakh students have pressed play: some on home broadband, many on shared Wi-Fi or 4G in crowded rooms. If the site kept one big 1080p file and sent it from one data centre, the upload would restart at every dropped connection, students on weak signals would stare at a spinning wheel, and the data centre's links would choke. This chapter builds the platform that gets that lecture to every one of them.

The product: a video platform for India. Anyone can upload a video, and anyone can watch it, on a phone in a moving train or on a TV at home. Assume about 200 million daily viewers and 100,000 hours of new video uploaded every day. We follow the chemistry lecture through every stage of the design: upload, transcode, package, deliver and play.

What we are building

The chemistry lecture shows two very different workloads hiding in the brief. Uploading happens once, is slow and is heavy on CPU: the teacher's file must be converted into many versions before any student can watch it. Watching happens two lakh times, and every time it is heavy on bandwidth. Most of this design comes from keeping those two paths apart.

Here is what is in scope today, by who uses it:

In scopeOut of scope today
CreatorsUpload a video with a title, description and tags; see when it is readyLive streaming, editing tools, earnings
ViewersWatch on any device and network; search; a home page of suggestionsOffline downloads, comments, playlists
PlatformCount views; never lose an upload; recommend at a high levelAds, copyright matching, moderation in depth

Live streaming is the biggest exclusion: it shrinks the pipeline from minutes to seconds, so it appears only as a variant at the end.

The non-functional requirements decide most of the cost, so pin each one to a number:

  • Fast start: playback begins within about 2 seconds of a tap, even on a slow connection.
  • Few stalls: viewers forgive a softer picture far more than a frozen one, so avoiding buffering beats maximum sharpness.
  • Durable uploads: once the teacher sees "processing", the original file is safely stored.
  • Available for watching: playback survives the loss of a server, a cache location or a whole data centre.
  • Eventually consistent view counts, search and suggestions: a delay of a minute or two is fine.
The key insight

Reads dominate, and each read is a large file. So the design prepares files once, even though every video is then stored several times, and serves them from close to the viewer. How large are those reads and files? The next two pages put numbers on them.

Bandwidth: why the edge is the design

Start with the watch path, because that is where the bytes are. Think of every viewer as a pipe that must stay full for as long as they watch: the question is how many pipes are open at once, and how wide each one is.

Assume 200 million daily viewers who watch 30 minutes each, at an average of about 2.5 Mbps. That average is a mix: phones on 480p at 1.2 Mbps, laptops on 720p, TVs on 1080p at 5 Mbps. The working, row by row:

QuantityWorkingResult
Watch time per day200 M × 0.5 hours100 M hours
Average viewers at any moment100 M hours ÷ 24 hours≈ 4.2 M
Average outgoing bandwidth4.2 M × 2.5 Mbps≈ 10 Tbps
Evening peakabout 2× the average≈ 20 Tbps
Bytes sent per day100 M hours × 2.5 Mbps × 3,600 s ÷ 8≈ 110 PB

No single data centre can send 20 terabits per second across a country with good latency, so a CDN (content delivery network) is not an optimisation here; it is the design.

The lecture makes the same point for one video. If two lakh students each watch the full hour at 2.5 Mbps, each pulls about 1.1 GB: about 225 TB in one night, from a lecture stored as 4.4 GB. If half of them watch at the same moment, that one video needs 1 lakh × 2.5 Mbps = 250 Gbps.

Every number here scales with the average bitrate. If the mix shifts towards TVs, the average rises towards 5 Mbps and the peak towards 40 Tbps; if most viewing moves to phones on 480p, it falls by half. The 4.4 GB came from the upload side, which is next.

Storage: what one hour becomes

Now the upload path. Creators upload 100,000 hours of video a day, and each video is stored as several renditions: versions of the same video at different resolutions and bitrates. So the real question is how many bytes one hour of video becomes.

Try it first: one hour of video is stored at 5, 2.5, 1.2, 0.7 and 0.3 Mbps, from 1080p down to 240p. How much storage is that, and how much new storage arrives each day?
  • Add the bitrates first (9.7 Mbps), then convert once: 9.7 Mbps × 3,600 s ÷ 8 bits per byte ≈ 4.4 GB per hour of video.
  • 1080p alone is half of it: 5 Mbps × 3,600 s ÷ 8 = 2.25 GB. The top rung decides the storage bill.
  • Per day, multiply by 100,000 hours: about 440 TB, before any extra copies.

The table carries that forward to a year, with the two ways a blob store keeps data safe:

StorageWorkingResult
One hour, all renditions9.7 Mbps × 3,600 s ÷ 8≈ 4.4 GB
New storage per day4.4 GB × 100,000 hours≈ 440 TB
One year, three copies440 TB × 365 × 3≈ 480 PB
One year, erasure coded (6+3)440 TB × 365 × 1.5≈ 240 PB

Storage grows by hundreds of petabytes a year, so it lives in a blob store that grows by adding machines.

Two choices follow from that. Erasure coding (from the blob store chapter) halves the bill compared with three copies, at the cost of slower rebuilds after a disk fails, which suits files that are written once. And rarely watched videos move to cheaper, slower tiers: last year's lectures on a topic nobody studies any more do not need fast disks.

The original upload is not in that estimate. A phone's 1080p recording is often as big as all five renditions together, so it usually goes to cold storage, kept so the video can be encoded again later with better settings. With the numbers set, the next page designs the calls that carry an upload in.

Part 2 · API, Data and the Big Picture

The API

Clients need only a handful of calls. Notice what is missing: no endpoint streams video. Watching happens through files served by the CDN: a manifest that lists the versions of a video, and the short segments of video it points to. The API accepts uploads and hands out metadata.

http
POST /v1/uploads                        { title, sizeBytes }       -> 201 { uploadId, chunkSize }
PUT  /v1/uploads/{uploadId}/chunks/{n}  <bytes of chunk n>         -> 200
GET  /v1/uploads/{uploadId}                                        -> 200 { chunksReceived[] }
POST /v1/uploads/{uploadId}/complete                               -> 202 { videoId, status: "processing" }
GET  /v1/videos/{videoId}                                          -> 200 { title, status, manifestUrl }
GET  /v1/search?q=organic+chemistry&cursor=c2                      -> 200 { results[], nextCursor }
GET  /v1/home?cursor=c2                                            -> 200 { videos[], nextCursor }
POST /v1/videos/{videoId}/views         { sessionId, watchedSec }  -> 202

The player gets manifestUrl from the metadata call, then talks only to the CDN.

The upload is resumable. The teacher's 2 GB lecture goes up as about 250 chunks of 8 MB, each acknowledged on its own. When the hostel Wi-Fi drops at 70%, the app asks which chunks arrived and sends only chunks 176 to 250 instead of starting over. Smaller chunks waste less on a drop but cost more requests; 8 MB is a common middle on mobile networks.

Each chunk carries a checksum, so the service rejects one that was corrupted on the way and asks for it again. A checksum of the whole file also allows de-duplication: when a byte-for-byte identical file is uploaded again, as happens with a viral clip, the platform reuses the renditions it already made. An edited copy has a different checksum, so this catches only exact copies.

complete returns 202 Accepted, not 200, because the video cannot be watched yet. Processing takes minutes, so the app polls the status or receives a push notification when it becomes ready. Views are a 202 too: the player sends the event and never waits for the counting system.

At larger scale

The API can hand out short-lived signed URLs so chunk bytes go straight into the blob store, as in the blob store chapter, and only track which chunks have arrived. If originals average about 10 Mbps, 100,000 hours a day arrive at about 40 Gbps, and none of it then passes through the API servers.

The data model

The upload has created three kinds of data, and they belong in different places: small structured metadata, huge video files, and a stream of events such as views.

usersid (pk)handlecreated_at
videosid (pk)owner_idtitledescriptionstatusduration_secmanifest_keycreated_at
renditionsvideo_id + codec + height (pk)bitrate_kbpskey_prefix
uploadsupload_id (pk)owner_idchunks_receivedexpires_at
video_statsvideo_id (pk)viewslikesupdated_at

Each kind goes to the store that suits how it is written and read:

DataWhere it livesWhy
Video and user metadataA relational database, sharded by video id when it growsSmall (about 1 KB a video); status changes need transactions
Originals and segmentsA blob store, with keys like v/42/720p/seg_0042.m4sPetabytes; written once, read many times
View and watch eventsA message queue, then counters and an analytics storeHuge volume; counted in batches, not row by row
Search indexA search clusterFull-text queries over titles, descriptions and captions
Watch historyA wide-column store keyed by user idAppend-heavy; read latest-first for one user

The rule behind the table: put each kind of data where its access pattern is cheap, not all of it in one database.

Segments are not rows. With 4-second segments, the one-hour lecture has 900 per rendition, 4,500 in all; a two-hour film has 9,000. Manifests list them and sit next to them in the blob store; the database keeps only the top-level manifest's key.

Metadata is read far more often than it changes. If 200 M viewers open about 10 videos a day, that is 2 billion reads a day, about 23,000 per second. Keep each video's metadata in the distributed cache for a few minutes and delete the entry when the creator edits the video; the database then sees a small share of those reads.

The big picture

With the calls and the stores in place, here is how they connect. The upload path turns one file into many renditions in the background; the watch path serves them from the edge. The two paths meet only at stored data: the blob store and the video's status. The scene follows the lecture through all five stages, and the teacher's Wi-Fi drops on the way.

Animated sceneOne lecture, from upload to a student0:25

The teacher's app sends 8 MB chunks; each is stored and ticked off as it lands

Read it as steps

The lecture travels the whole spine: a resumed upload, 360 jobs, packaging, then the first and second students in a city.

Each stage hands over to the next through stored data, so a failure stays where it happens: a dropped connection costs only the missing chunks, and a slow transcoder delays one video, not the CDN. A burst of uploads after results day breaks nothing either; videos wait longer in the queue while more workers start to drain it.

Two paths, two scaling knobs

Workers scale with uploads, measured by the age of the oldest job in the queue. The CDN scales with viewers, measured by bandwidth and hit ratio. Because the paths are separate, a flood on one does not slow the other.

The scene hid the hardest stage inside one box. What happens between "360 jobs" and "ready"? The deep dives start there.

Part 3 · Deep Dives

Transcoding: one upload, 360 jobs

Core deep dive

This is the stage unique to video: one upload must become files that every device can play, within minutes, even when workers crash or run a job twice.

A phone records one file at one size, often 1080p at a high bitrate. That file suits almost nobody: it is too big for a student on weak 4G, and an old TV may not decode its format. Transcoding decodes the original and encodes it again into a set of renditions called a bitrate ladder: the same picture at several sizes, so every network gets one it can carry. Our ladder has five rungs:

RenditionResolutionBitrate (about)Typical viewer
240p426 × 2400.3 MbpsWeak signal, data saver mode
360p640 × 3600.7 MbpsCrowded mobile network
480p854 × 4801.2 MbpsA phone on ordinary 4G
720p1280 × 7202.5 MbpsGood 4G, laptops
1080p1920 × 10805 MbpsHome broadband, TVs
240p

Resolution426 × 240

Bitrate (about)0.3 Mbps

Typical viewerWeak signal, data saver mode

360p

Resolution640 × 360

Bitrate (about)0.7 Mbps

Typical viewerCrowded mobile network

480p

Resolution854 × 480

Bitrate (about)1.2 Mbps

Typical viewerA phone on ordinary 4G

720p

Resolution1280 × 720

Bitrate (about)2.5 Mbps

Typical viewerGood 4G, laptops

1080p

Resolution1920 × 1080

Bitrate (about)5 Mbps

Typical viewerHome broadband, TVs

Each rung is roughly half the bitrate of the one above, so a viewer whose speed halves drops one or two rungs, not to the bottom.

Encoding is slow: five rungs from one long job can take longer than the video itself, so the lecture would sit in "processing" for over an hour. The fix is to split the original at keyframes (complete pictures that need no earlier frame to decode) into pieces of about 10 seconds. The lecture becomes 360 independent jobs, and a few hundred workers finish them in minutes.

Across the platform, 100,000 hours a day is 36 M pieces, about 420 a second. If a worker needs about a minute per piece for all five rungs (an assumption; it depends on the codec and the machine), about 25,000 workers are busy on average, more after a festival. Shorter pieces finish sooner, but every cut adds a keyframe and costs a little quality per bit, so 10 seconds is a common middle.

Splitting creates a new problem: with 360 jobs per video, some will run twice. Why is that dangerous?

When a job runs twice

The job queue hands each piece to a worker with a lease, the visibility timeout from the message queue chapter. If the worker has not finished when the lease runs out, the job reappears for another worker. That is how a crashed worker's piece still gets done. But a lease cannot tell a dead worker from a slow one, so sometimes two workers encode the same piece, and both report success.

Two things could then go wrong. Storage could hold two copies of the piece. Worse, if the pipeline counts finished pieces with a running total, the duplicate pushes the count to 360 while another piece is still missing, and packaging builds a lecture with a hole in it. Watch both being prevented:

Animated scenePiece 17 runs twice0:17

Watch for piece 17: two workers finish it, yet the tracker counts it only once

Read it as steps

A slow worker loses its lease, a second worker repeats the piece, and fixed keys plus a set of piece numbers keep the lecture whole.

Two rules make a repeat harmless. Every output goes to a key fixed by the job, such as v/42/720p/piece_017, so a second run overwrites the first. And the tracker stores piece numbers, not a count, so a second "done" changes nothing; packaging starts only when all 360 numbers are in.

The lease length is a trade-off. Set it a little above the slowest normal piece, say 3 minutes for a 1-minute job: too short and healthy jobs run twice, wasting CPU; too long and a crashed worker's piece waits, delaying the whole lecture. A piece that fails on every worker is a poison piece: after 3 attempts it goes to a dead-letter queue and the video is marked failed with a reason, instead of retrying forever. With all 360 pieces encoded, the renditions still cannot be streamed. Packaging is next.

Packaging: segments and manifests

An encoded rendition is one long file. A player could download it from the start, but it could not change quality halfway or jump to minute 40 cheaply. Packaging fixes that by cutting each rendition into segments of 2 to 6 seconds and writing a manifest, a small text file that lists what exists. Think of a textbook: the segments are its pages, the manifest is its table of contents.

Two details make switching possible. Every rendition is cut at the same moments, and each segment starts with a keyframe, so segment 23 at 480p covers exactly the same seconds as segment 23 at 1080p and decodes on its own. A player can change rendition at any segment boundary without losing its place.

The top-level manifest names each rendition and its bitrate; each rendition has its own playlist of segments. A trimmed example in HLS, Apple's format:

text
#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080
1080p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1200000,RESOLUTION=854x480
480p/index.m3u8

Each index.m3u8 lists that rendition's segments in order.

DASH, an MPEG standard, describes the same thing in one XML manifest, and both formats can share the same fragmented MP4 segments, so one copy of the files serves both. They are plain files over HTTP, which is why any CDN can cache them.

With 4-second segments the lecture has 900 per rendition. A 1080p segment is 5 Mbps × 4 s ÷ 8 = 2.5 MB; a 480p one is 0.6 MB. Segment length is the trade-off: 2-second segments start faster and react sooner to a changing network, but double the requests and the keyframes; 6-second segments do the reverse. 4 seconds is a common choice for recorded video. The files are ready. Next: getting them to two lakh students without melting the origin.

Delivering from the edge

Segments are ideal CDN content: they never change once written, their URLs are stable, and many viewers ask for the same ones at once. Popularity is very uneven, too. A small share of videos, such as the lecture everyone watches the night before the exam, gets most of the views, while a long tail of old videos is watched a few times a day. Edges hold the head; the tail mostly comes from regional caches or the blob store.

The hit ratio, the share of requests an edge answers from its own cache, decides how hard the origin works. At 20 Tbps of peak traffic, a 95% hit ratio leaves 1 Tbps for shields and origin; 99% leaves 0.2 Tbps. For the lecture alone, even if 200 edge locations each pulled every rendition once, the origin would send 200 × 4.4 GB, under 1 TB, against about 225 TB delivered. Popular video is cheap to serve from the edge; the long tail is what costs.

Three ways to fill edges, and when each fits:

ChoiceUse it forWhy
Pull: cache on first requestThe long tailNo copies of videos nobody watches
Push: load edges in advanceScheduled releases, trending videosFirst viewers get hits; the origin sees no burst
Origin shieldEverythingMany edge misses for one segment become one origin fetch

Pull is the default; push and shields exist to stop the bursts that pull alone would send to the origin.

At 9 pm thousands of students may ask an edge for segment 1 of the lecture in the same second. The edge sends one request upstream and makes the rest wait for it (request collapsing). The largest platforms also put cache servers inside internet providers' networks: the provider saves on its paid links, and the platform pays far less per GB.

Private and paid videos

Use signed URLs that expire in minutes, checked at the edge, with the token left out of the cache key so each segment is still cached once. Paid films add DRM: segments are stored encrypted, and the player gets the key from a licence server only after the platform confirms payment.

How the player picks a quality

The segments now sit at an edge near every student. The last stage of the spine runs on the student's phone: which rendition should it fetch next? The player does not choose once and stick with it: it decides again before every segment. This is adaptive bitrate streaming.

It uses two signals: how fast recent segments downloaded, and how many seconds of video wait in the buffer (downloaded but not yet played). A full buffer allows a step up. A draining buffer forces a step down before the picture freezes. Most players also keep a safety margin, choosing the highest rung below about 80% of the measured speed.

Predict before you watch: a student has 30 seconds buffered at 1080p (5 Mbps, 4-second segments) when the hostel Wi-Fi falls to 2 Mbps. If the player changed nothing, how long until the picture freezes?
  • About 50 seconds: each 2.5 MB segment takes 10 s to fetch but plays for 4, so the buffer loses 6 s per segment, and 30 ÷ 6 = 5 segments.
Animated sceneA player steps down before it stalls0:26

Watch for the buffer badge: video downloaded but not yet played

Read it as steps

At 1080p over 2 Mbps the buffer drains 6 s per segment, so the player drops to 480p and it refills.

The player steps down before the buffer runs dry, and it may skip a rung: 720p would still drain 1 s per segment at 2 Mbps. It climbs back one rung at a time, because a step up that fails costs a stall, while a slow climb costs only a few seconds of softer picture.

Three habits follow from cutting every rendition at the same moments:

  • Start low, then climb. Starting at 480p puts the first frame on screen sooner.
  • Switch only at segment boundaries. A switch changes the sharpness, never the position.
  • Seeking is cheap. Jumping to minute 40 fetches the segment covering minute 40 and nothing before it.

Part 4 · Bottlenecks, Failures and Trade-offs

What breaks, and what you do

The spine is complete. Now walk it again one stage at a time and ask what fails, what a viewer would notice, and how the system recovers:

ProblemWhat it looks likeWhat you do
Upload spikeThe job queue grows after a festival or results dayAdd workers based on the age of the oldest job; process short videos first. Cheap machines that can be reclaimed at short notice are fine, because jobs retry safely
A poison fileOne corrupt video crashes every worker that touches itAfter 3 failures, move the job to a dead-letter queue and tell the creator
Premiere rushThousands ask one edge for the same first segments at oncePush to edges in advance; edges collapse identical misses into one fetch
Edge location downViewers in one city lose their nearest cacheDNS or anycast sends them to the next nearest edge: a little slower, still playing
A zone or region failsA zone: little, because every tier spans three zones. A region: its uploads and metadata writes stopEdges keep serving cached segments and fetch misses from blob copies in another region; promote the metadata replica there and resume uploads, which are resumable
Hot metadata rowA viral video's page hammers one database rowCache video pages; counts come from counters, not that row

The pattern: failures on the upload path are handled by making work safe to retry; failures on the watch path by having another copy somewhere else.

What dominates the bill: delivery. About 110 PB leaves the edges each day. Even at a tenth of a list egress price of $0.05 per GB, that is about $16 million a month, more than three times the $4.8 million a month for storing a full year of renditions (240 PB at $0.02 per GB-month); check current prices.

Trade-offs, side by side

Every stage of the spine had a dial. Each choice below buys smoother playback or a lower bill with something else, and the table names both sides:

ChoiceGainCost
More renditionsSmoother playback on every networkMore storage and transcoding time
Shorter segments (2 s instead of 6 s)Faster start and quicker quality switchesMore requests, longer manifests and slightly bigger files (more keyframes)
A newer codecLess bandwidth for the same qualityMuch more encoding CPU; older devices cannot play it
Keep the originalRe-encode later with better settingsOften the biggest file of all; keep it in cold storage
Push to the CDNFirst viewers get hitsWasted copies when you guess popularity wrong

None of these has a right answer in general; each depends on how often a video is watched.

Codecs show that best. A common middle path is to encode every video in a widely supported codec such as H.264, so almost every device can play it, and add a newer, more efficient codec only for popular videos, where the bandwidth saved pays for the extra encoding. For a lecture watched two lakh times, an encode that saves 30% of the bits saves about 70 TB of delivery in one night; for a clip watched ten times, it saves almost nothing and still costs the CPU.

The same logic sizes the ladder. A slide-based lecture with a still background needs far fewer bits than a cricket match for the same sharpness, so platforms with enough volume tune the ladder per video instead of using one fixed table.

Part 5 · Going further

Views, search and suggestions

Optional: view counts, search and suggestions, the systems built around the videos once the spine works.

View counts. The lecture can collect thousands of views per second at 9 pm. Writing each view to one database row would make that row the hottest spot in the system. Instead, players send view events to a queue; workers drop bots and repeated refreshes, sum the rest per video every few seconds, and add the totals to sharded counters (see the sharded counters chapter). The number on the page lags by a minute or so, which nobody minds.

Search. When a video becomes ready, an event sends its title, description, tags and auto-generated captions to the search indexer. Ranking mixes text relevance with signals such as views, recency and watch time. An index that is a minute or two behind is fine here.

Suggestions. At a high level, recommending is a funnel that narrows millions of videos down to about twenty:

Picking 20 videos for a home page
  1. 1Candidate generationa few hundred videos from creators the viewer often watches, videos often watched together with recent ones, and what is trending in the viewer's language
  2. 2Rankinga model scores each candidate by how long this viewer is likely to watch it
  3. 3Filtering and mixingdrop watched or blocked videos; mix topics so the page is not twenty clips of one thing

Candidates are mostly prepared offline by batch jobs; ranking runs at request time with fresh signals, such as the video the viewer just finished. If ranking is slow or down, the home page falls back to a cached list of popular videos so it still loads.

Part 6 · Interview kit

The 45-minute answer

A 45-minute interview leaves about 40 minutes of design once introductions and your own questions are done. Here is how to spend them on a video platform.

MinutesWhat you say and drawKey number or decision
0–5Upload, watch on any device and network, search, a home page; start within 2 s, few stalls, no lost uploads; live and comments out.Two paths: rare heavy uploads, constant heavy watching
5–84.2 M watching at once × 2.5 Mbps ≈ 10 Tbps, about 20 Tbps at peak; 100,000 hours a day × 4.4 GB ≈ 440 TB a day.20 Tbps makes the CDN the design
8–13Resumable chunked upload, complete answering 202, metadata with a manifest URL; metadata in a relational database, segments in a blob store, views in a queue.No endpoint streams video
13–22The spine: upload → transcode → package → CDN → player, with the job queue between upload and workers.The paths meet only at stored data
22–37Transcoding: 360 pieces in parallel, leases, fixed output keys, a set of done pieces. Then segments, the edge and adaptive bitrate.One hour → 360 jobs; 99% hit ratio leaves 0.2 Tbps
37–40Failures (poison file, premiere rush, region loss), trade-offs, player-side monitoring.Delivery dominates the bill

Pick the transcoding pipeline if they ask how an upload becomes watchable, how long that takes or what happens when a worker crashes. Pick the edge and the player if they ask about slow networks, start time or serving 20 Tbps. Offer view counting only if time remains.

Say
"A one-hour upload becomes 360 ten-second jobs with fixed output keys, so a few hundred workers finish it in minutes and a repeated job is harmless."
Say
"Five renditions cut into 4-second segments at the same boundaries, so on weak Wi-Fi the player drops to 480p at the next segment instead of freezing."
Say
"At 20 Tbps the hit ratio is the number I watch: at 95% the origin serves 1 Tbps, at 99% only 0.2 Tbps."
Avoid
"The server streams the video to the user." Video bytes never pass through API servers; players fetch segments from the CDN.
Avoid
"Count finished pieces and package at 360." A repeated job double counts; track the set of piece numbers.

Interview drill

Interviewers change one thing to see whether your design bends or breaks. Try each question before opening the answer.

Results day: uploads jump to ten times normal for a few hours, and new videos take two hours to become ready. What do you do?
  • Scale workers on the age of the oldest job; cheap machines that can be reclaimed at short notice are fine, since every job retries safely.
  • Publish a fast first version: encode 480p and 720p first and mark the video ready, then add the other rungs at lower priority.
  • Take jobs round-robin by creator, so one channel's 500 uploads do not delay everyone else's single video.
Add "continue watching": a video resumes where you stopped, on any device. What changes?
  • New data: a position per (user, video) with a timestamp, in a wide-column store keyed by user, next to watch history.
  • Writes are the hard part: if players report every 30 s, 4.2 M people watching at once send about 140,000 updates a second.
  • Batch through a log partitioned by user and write only the newest position every few minutes or on pause; last write wins across devices.
Finance asks you to halve the delivery bill. Where do you look?
  • Delivery dominates: about 110 PB leaves the edges each day, far more than storage or encoding costs.
  • Put cache servers inside internet providers' networks, where a GB delivered costs far less than over the open internet.
  • Send fewer bits: a newer codec for popular videos, a ladder sized to the content, and 720p as the default cap on small screens.
Common miss
Drawing one video server that both transcodes and streams: the two paths scale differently and must fail separately.
Common miss
Measuring only servers: stalls and startup time live in the player, so a bad encode can hide behind green dashboards.

Wrap-up

Next: Design a Q&A Site. The reads become small pages instead of large files, but the same idea returns: cache what everyone sees, and count votes and views off the hot path.

Part 7 · Check yourself

Quick check

Q1After a player update, students on hostel Wi-Fi report more freezes during the lecture, yet the average quality served went up. Why, and how should you have caught it?

Think it through, then check.

Q2Students must now be able to download the lecture and watch it offline on a train with no signal. What changes?

Think it through, then check.

Q3A teammate wants 1-second segments so quality switches react faster. What do you gain, and what do you pay?

Think it through, then check.

Q4Three of the lecture's 360 pieces fail on every worker that tries them. What happens to the video, and what should the system do?

Think it through, then check.

Q5Which building block sits between students and the blob store, and why not let players read the blob store directly?

Think it through, then check.

Next chapter · 24 of 39Design a Q&A Site~39 min · 2 animated scenes