Upload, transcode and play video smoothly for millions, on any device and network.
โDesign YouTube. Or Netflix. Users upload or watch videos, and it has to work on every device.โ
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Splitting the problem in two | Upload and processing is a slow, heavy, background job. Playback is a fast, huge, read-only job. A strong candidate separates them early and designs each for its own load. |
| Doing the egress maths | Video is mostly bandwidth. When the numbers show tens of terabits per second, a CDN is not an option but the core of the design. Interviewers watch for whether you find that out yourself. |
| Pipelines and parallelism | Transcoding a long video on one machine takes hours. Splitting it into chunks, encoding in parallel and retrying safely is the standard answer. |
| Adaptive streaming | Networks change second by second. Knowing why video is cut into short segments with several qualities, and how the player picks between them, shows you understand playback. |
| Cost and trade-offs | Storage, encoding and egress all cost real money. Which renditions to keep, what to cache at the edge and what to leave cold are product-and-money decisions. |
Split the system in two. Upload path: the client sends the file straight to object storage in resumable pieces, an event starts a transcoding pipeline that cuts the video into chunks, encodes each chunk in several qualities in parallel, and packages them as short segments plus a manifest. Playback path: the player reads the manifest and downloads segments over plain HTTP from a CDN, switching quality as the network changes.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | User-uploaded or licensed catalog, devices and networks, max length, what is out (live, DRM, ads, recommendations). |
| 2. Estimate | 4 | Peak viewers, egress in Tbps, storage per day, transcoding cores. Let the numbers justify the CDN. |
| 3. API and data | 4 | Resumable upload, the manifest, the renditions and job records. |
| 4. High-level design | 8 | Upload path, pipeline, origin, CDN tiers, player. Walk one upload and one view. |
| 5. Deep dives | 15 | Pipeline first, then adaptive bitrate, then delivery at scale, then views and metadata. |
| 6. Scale and failures | 7 | Viral video, failed encode, CDN miss storm, cost, monitoring. |
| 7. Wrap up | 3 | Recap, trade-offs, what you would do next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| Is this user-uploaded video like YouTube, or a licensed catalog like Netflix? | Uploads are unpredictable and need fast processing of anything. A catalog is a known set that can be processed carefully and pushed to caches ahead of time. | User uploads, like YouTube. Mention what changes for a catalog. | We need an upload path, a pipeline that handles any input, and a long tail of rarely watched videos. |
| Is live streaming in scope? | Live has no time to prepare: encoding, packaging and delivery all happen in seconds, and the design is different. | No. Video on demand only. | We can process before we publish, and cache segments for as long as we like. |
| What devices and networks must we support? | Phones on weak networks and TVs on fibre need very different qualities. | Phones, browsers and TVs, on anything from 3G to fibre. | Several qualities, adaptive streaming, and short segments so the player can adapt fast. |
| How long and how large can an upload be? | A 5-minute clip and a 4-hour film need different upload and encode handling. | Up to 4 hours and a few GB. The average is about 100 MB. | Resumable multipart upload, and splitting into chunks to encode in parallel. |
| How many users, and how much do they watch? | Sets peak concurrent viewers, and so egress bandwidth. | 100M daily users, about 5 videos a day, about 10 minutes each. | About 10M peak viewers and tens of Tbps. A CDN is mandatory. |
| How many videos are uploaded each day? | Sets storage growth and transcoding capacity. | About 500,000 a day, 100 MB on average. | 50 TB of raw video a day. A large, queue-driven encoding fleet. |
| How soon after upload must a video be watchable? | A target such as minutes (not hours) forces parallel encoding and progressive publishing. | A few minutes, with a low quality first if needed. | Chunked parallel encoding and publishing the low rungs before the high ones. |
| Do we need view counts, likes, comments, search and recommendations? | Each is a system of its own. Say which you design and which you only reference. | View counts yes. The rest are separate services, only mentioned. | A counter pipeline that stays off the playback path. Search and recommendations are black boxes. |
| Do we need DRM, ads, or per-country licensing? | These add key servers, ad insertion and geo rules. | Out of scope. Mention signed URLs for access control. | Plain HLS with signed URLs. Say that DRM would add a licence server. |
| What availability and start-up time do we target? | Playback is the product. A target makes the trade-offs concrete. | 99.99% for playback, start-up under 2 seconds, and very little freezing. | Multi-zone origin, a tiered CDN, and monitoring of start-up time and freeze ratio. |
| Assumption | Value |
|---|---|
| Daily viewers | 100 million |
| Videos watched per viewer per day | 5, about 10 minutes each |
| Peak versus average concurrency | about 3 times |
| Average stream bitrate (a mix of qualities) | 3 Mbps |
| Uploads per day | 500,000, average 100 MB and about 5 minutes |
| Stored per upload | the original plus renditions, about 4 times the original in total |
| Encoding effort, all renditions | about 10 CPU-minutes per minute of video |
| Segment length | 4 seconds |
| CDN edge hit ratio on playback | about 95% |
| Egress price (illustrative only) | $0.005 per GB |
| What | Maths | Result |
|---|---|---|
| Views per day | 100M ร 5 | 500 million |
| Watch time per day | 500M views ร 10 min | 5 billion minutes |
| Average concurrent viewers | 5B min รท 1,440 min per day | about 3.5 million |
| Peak concurrent viewers | 3.5M ร 3 | about 10 million |
| Peak egress | 10M ร 3 Mbps | 30 Tbps (3.75 TB per second) |
| Egress per day | 5B min ร 60 s ร 3 Mbps รท 8 | about 112 PB |
| Segment requests at peak | 10M viewers รท 4 s | about 2.5 million per second |
| Raw upload per day | 500,000 ร 100 MB | 50 TB (about 5 Gbps average, 14 Gbps at 3ร peak) |
| Stored per day, all renditions | 50 TB ร 4 | 200 TB per day, about 73 PB per year (about 110 PB with 1.5ร erasure coding) |
| Encoding work per day | 500,000 ร 5 min ร 10 CPU-min | 25 million CPU-minutes, about 417,000 CPU-hours |
| Encoding cores, average, then with 2ร headroom | 417,000 รท 24 h, then ร 2 | about 17,000 cores, then about 35,000 (roughly 540 machines of 64 cores) |
| Traffic reaching the origin if the edge hits 95% | 30 Tbps ร 5% | 1.5 Tbps (0.3 Tbps if a regional tier absorbs 80% of those misses) |
| What one point of hit ratio is worth at peak | 30 Tbps ร 1% | 300 Gbps |
| Egress bill at the illustrative price | 112 PB = 112M GB ร $0.005 | about $560,000 per day, so volume pricing and own caches matter |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | /v1/videos | { title, description, size, contentType } | 201 { videoId, uploadId, partUrls[] } | Starts a resumable multipart upload. Returns pre-signed URLs so the client sends bytes straight to object storage. Auth required. |
| PUT | {pre-signed part URL} | one part of the file (for example 8 MB) | 200 { etag } | Goes to object storage, not to our API. Failed parts are retried alone. The upload can resume after a lost connection. |
| POST | /v1/videos/{id}/complete | { uploadId, parts: [{ n, etag }] } | 202 { status: processing } | Idempotent. Completes the multipart upload and emits an uploaded event that starts the pipeline. |
| GET | /v1/videos/{id} | none | 200 { title, status, thumbnailUrl, manifestUrl, durationSec } | Small metadata read, cached. manifestUrl is a signed CDN URL that expires. Status is processing, ready or failed. |
| GET | {manifestUrl} and {segmentUrl} | none | 200 playlist (.m3u8 or .mpd) or a segment (.ts or .m4s) | Served by the CDN, never by the API. The playlist lists the qualities, the segments are 2 to 10 seconds each. |
| POST | /v1/videos/{id}/views | { position, sessionId } | 204 | Fire and forget. Goes to a queue and is counted later, so it never slows playback. |
| Table or store | Key fields | Notes |
|---|---|---|
| videos | video_id, owner_id, title, description, status, duration, created_at, original_key | Small, read-heavy. SQL or a key-value store. Cached hard. About 1 KB per row. |
| renditions | video_id, quality, codec, bitrate, manifest_key, status | One row per quality per video. Tells the packager and the manifest what exists. |
| transcode_jobs | job_id, video_id, chunk_no, quality, state, attempts, worker, updated_at | One row per task. State: queued, running, done, failed. Makes retries and progress visible. |
| object store: originals | videos/{id}/original | The source of truth, kept in a durable and cheap tier. |
| object store: segments | videos/{id}/{quality}/seg_00001.m4s, plus the manifest | Immutable files, so they cache perfectly. This is what the CDN fetches. |
| view counts | video_id, day, count | A separate store fed by a stream. Sharded counters. Never on the playback path. |
#EXTM3U #EXT-X-STREAM-INF:BANDWIDTH=500000,RESOLUTION=426x240 240p/index.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=1500000,RESOLUTION=854x480 480p/index.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=3000000,RESOLUTION=1280x720 720p/index.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=5500000,RESOLUTION=1920x1080 1080p/index.m3u8
| Component | What it does |
|---|---|
| Object storage | Durable home of the originals and of every segment. The CDN and the encoders read from it. |
| Upload service | Creates the multipart upload and the pre-signed URLs, and completes it. Never touches the video bytes. |
| Job queue | Holds one task per chunk and quality. Gives retries, priorities and back pressure when the workers are busy. |
| Transcoding workers | Split, encode and package. Stateless, so we can add thousands on demand (spot or preemptible machines work well). |
| Metadata service and DB | Title, status, manifest location and job records. Small data, cached, replicated across zones. |
| CDN with tiers | Edge caches near viewers, regional caches behind them, and an origin shield in front of storage to collapse misses. |
| Player | Reads the manifest, downloads segments, measures speed and buffer, and picks the quality of the next segment. |
| View, moderation and thumbnail pipelines | Asynchronous consumers of events. A failure here never stops a video playing. |
The problem: A raw upload must become many qualities, for every device, fast. One machine encoding a 4-hour film for every quality takes many hours, a crash loses all the work, and a burst of uploads must not swamp anything.
| Option | How it works | Good | Bad |
|---|---|---|---|
| One worker encodes the whole file | A worker takes the video and produces every quality in sequence. | Simple. Easy to reason about. | A 4-hour film takes hours, a crash restarts everything, and one slow job blocks a worker. |
| Split into chunks, encode in parallel | Cut at keyframes into chunks of a few minutes. Queue one task per chunk and quality. Merge by listing segments in the manifest. | Fast: wall-clock time is about the slowest chunk. A failed chunk retries alone. Scales with workers. | More moving parts. Needs a planner, a task table and care at chunk boundaries. |
| Fixed ladder for every video | Always encode the same set of qualities (for example 240p to 1080p). | Predictable cost and easy packaging. | Wastes work on simple videos (a slideshow) and may under-serve complex ones. |
| Per-title or per-chunk ladder | Analyse the content and choose bitrates that give good quality for the least data. | Saves storage and egress, which are the big bills. | Extra analysis cost and more complexity. Worth it for the most-watched content. |
Chunking turns one slow job into many small, independent and idempotent tasks. A 4-hour film is about 60 chunks of 4 minutes. At 5 qualities that is 300 tasks. At about 10 CPU-minutes per video minute the work is 2,400 CPU-minutes, so on 300 workers each task takes about 8 minutes, instead of 40 hours on one core.
Publish progressively: encode the lowest quality first, so the video is watchable within minutes, and add higher qualities as they finish. Each task writes to a fixed path, so a retry after a crash just overwrites the same file. Use cheap preemptible machines, since a lost task only costs a retry.
| Codec | Compression | Cost and reach |
|---|---|---|
| H.264 (AVC) | Baseline. Plays almost everywhere. | Cheapest to encode. The safe default for every device. |
| VP9 or HEVC | Roughly 30% to 50% smaller at the same quality (varies by content). | Slower to encode. Support differs by device and licence. |
| AV1 | Smaller again, often by another large margin. | Much slower to encode and needs newer devices. Worth it for very popular videos where egress savings are large. |
The problem: Viewers are on Wi-Fi, trains and weak 3G, and the speed changes second by second. A fixed quality either freezes when the network drops or wastes quality when it is fast. The player must adapt, using only plain HTTP.
| Option | How it works | Good | Bad |
|---|---|---|---|
| One file, one quality | Serve a single MP4 at one bitrate. | Simplest. | Freezes on slow networks, wastes data on fast ones, and a seek needs a range request. |
| Real-time protocol (RTMP or WebRTC) | Push a continuous stream from a media server. | Very low delay. Good for live and calls. | Stateful servers, hard to cache and hard to scale to millions. A poor fit for on-demand video. |
| Segmented HTTP streaming (HLS or DASH) | Cut each quality into 2 to 10 second segments. A manifest lists them. The player picks a quality for each next segment. | Plain HTTP, so CDN caches work and firewalls allow it. Adapts every few seconds. | Some start-up delay, and many small files to store and cache. |
Segments are ordinary static files, so every cache and CDN already knows how to serve them, and they work through proxies and firewalls. The server has no per-viewer state: the player decides, and each request is independent. That is what lets one origin and a CDN serve millions.
A common player combines two signals. Throughput: pick the highest quality below a safe share of the last measured speed. Buffer: if the buffer is low, step down, and if it is full, step up. Start at a low quality so the first picture appears fast, then climb. Shorter segments adapt faster and start faster, but add more requests and slightly less efficient encoding.
| Rung | Resolution | Bitrate (illustrative) |
|---|---|---|
| 1 | 240p | 0.4 Mbps |
| 2 | 360p | 0.8 Mbps |
| 3 | 480p | 1.5 Mbps |
| 4 | 720p | 3 Mbps |
| 5 | 1080p | 5 Mbps |
The problem: 30 Tbps at peak, 2.5 million segment requests a second, viewers everywhere, and a long tail of videos that nobody has watched for a week. The origin must stay small, and the egress bill must stay sane.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Serve everything from the origin | Players fetch segments straight from our storage or servers. | Simplest. | Impossible at 30 Tbps. High latency far from the origin, and the origin is a single big target. |
| Pull-through CDN, one tier | Edge nodes cache what viewers ask for and fetch misses from the origin. | Easy. Popular segments are cached after the first request. | Every edge misses on its own, so a new popular video can send many parallel misses to the origin. |
| Tiered CDN with an origin shield | Edge, then regional caches, then one shield in front of storage. Misses are collapsed at each tier. | The origin sees one request per segment, not one per edge. Far less origin traffic. | More layers, a little more latency on a cold miss, and more to monitor. |
| Pre-positioned caches near or inside ISPs | Push the most popular titles to cache boxes close to viewers ahead of time, often at night. | Cheapest egress and best quality for popular content. Systems like Netflix are known to place caches inside ISP networks. | Needs predictable popularity and relationships with ISPs. Not useful for unpredictable uploads. |
Segments are immutable, so the cache key is just the segment URL and the TTL can be very long. Popular videos live at the edge and cost almost nothing to serve. The long tail is rarely watched, so it is fine if it comes from the origin and is cached for a while.
The danger is a miss storm: a new video goes viral and thousands of edges ask for the same segment at once. Request coalescing (one fetch, many waiters) at each tier and an origin shield make the origin see one request. Each hit-ratio point is about 300 Gbps at peak, so it is worth tuning.
| Traffic | Where it comes from | Why |
|---|---|---|
| Popular videos (a small share of titles, most of the watch time) | Edge cache, nearly always a hit | Small set, watched constantly. Can be pre-positioned. |
| Mid-popularity videos | Regional cache | Not hot enough for every edge, but hit often enough to stay cached. |
| The long tail | Origin, cached on the way | Rarely watched. Each first view is a miss. Keep the origin cheap and fast. |
The problem: Every play wants to increment a counter and read metadata, at millions per minute. A single database row for a viral video is a hot spot. And a video URL must not become a permanent public link to something that should be private.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Increment a database row on every view | UPDATE videos SET views = views + 1. | Simple and always current. | One hot row for a viral video. Locks and contention, and it puts writes on the playback path. |
| Sharded counters in a fast store | Spread one video's count over N keys and add them up when reading. | Removes the hot key and handles high write rates. | Reads add up several keys. Slightly more work. |
| Events through a queue, aggregated in batches | Players send view events. A stream job counts per video per minute and writes totals. | Off the playback path. Cheap. Can also dedupe and filter bots. | The count is delayed by seconds to minutes. Exact real-time numbers need more care. |
A view count does not need to be exact to the millisecond, but playback must never wait for it. Sending events through a queue keeps the cost off the video, and a stream aggregator can count, dedupe and drop bots in one place. For the number on the page, show a cached total that is a few seconds old.
Metadata is small and read-heavy, so cache it hard and invalidate on edit. For access control, give each viewer a signed, expiring manifest and segment URL, so a link cannot be hotlinked or kept forever. Moderation and copyright checks (for example matching fingerprints of known content) run as asynchronous stages before a video becomes public.
A simplified model with fixed numbers (no random values). Each 4-second segment downloads at the speed shown for its slot. Playback starts when the first segment arrives, and the player stops fetching at 20 s of buffer. Speed mode picks the highest rung at or below margin ร the last measured speed. Buffer mode starts at 240p, moves up one rung for roughly every 3 s of buffer above 6 s, and drops back to 240p below 6 s. Real players combine both signals.
| Bottleneck | Fix |
|---|---|
| Origin traffic on a new viral video | Request coalescing and an origin shield. Pre-warm the first segments of a video that is spreading fast. |
| Encoding backlog after a burst of uploads | A queue with priorities, autoscaled spot workers, and low qualities first so videos become watchable early. |
| Egress cost | Raise the hit ratio, use efficient codecs for hot videos, tier cold segments, and negotiate or use cheaper delivery routes. |
| Hot metadata row for a viral video | Cache metadata at the edge or in memory, and keep the view counter separate and sharded. |
| Storage growth (about 200 TB a day) | Keep originals in cold storage after encoding, drop rarely used renditions, and move old videos to cheaper tiers. |
| Small files: millions of tiny segments | Use object storage with high request rates, keep keys spread out, and longer segments for the cold tail if the cost of requests dominates. |
| Start-up time on slow networks | Begin at a low quality, short first segments, and a manifest that is small and cached. |
| Failure | How the design copes |
|---|---|
| A transcoding worker dies mid-task | The task lease expires and the task goes back to the queue. It is idempotent, so the retry overwrites the same output. |
| A chunk fails repeatedly (a corrupt frame) | After a few attempts move the task to a dead-letter queue, mark the video failed with a reason, and tell the uploader. |
| The upload connection drops | The client resumes from the last good part. The upload stays open for a limited time, then is cleaned up. |
| A CDN edge or a region is down | DNS or anycast routes viewers to another edge. The tier behind it serves the content, and the player retries another host. |
| Object storage is slow or unavailable in one zone | Multi-zone storage with replication. The shield retries and serves stale segments if it must. |
| The metadata database fails over | A replica is promoted. Cached metadata keeps playback going for videos already known, and writes retry. |
Two paths. Uploads go straight to object storage in resumable pieces, an event starts a chunk-parallel transcoding pipeline that publishes low qualities first, and the results are immutable segments plus a manifest. Playback is HLS or DASH over a tiered CDN with an origin shield, and the player picks every next quality from its speed and buffer. Metadata is a small cached database, and view counts, thumbnails and moderation are asynchronous, so they never slow a video.
| Decision | What we gain | What it costs |
|---|---|---|
| Pre-signed direct upload to object storage | Our API never carries video bytes. Uploads resume and scale on their own. | More client logic, and a cleanup job for abandoned uploads. |
| Chunk-parallel encoding | Minutes instead of hours, and cheap retries. | A planner, a task table and care at chunk boundaries. |
| Segmented HTTP streaming (HLS and DASH) | Works with caches and firewalls, no per-viewer state, adapts per segment. | Some start-up delay and many small files. |
| Tiered CDN with an origin shield | A tiny origin load, and a much better hit ratio. | More layers to run, and a slightly slower cold miss. |
| Asynchronous view counts | Playback is never slowed by counting. | Counts are a few seconds to minutes late. |
| Several renditions per video | Smooth playback on every device and network. | About 4 times the storage and a large encoding bill. |
The core of the product. Know why segments exist and how the player decides.
Where most of the compute goes. Show parallelism, idempotency and failure handling.
Where the money is. Show you know the CDN is the design, and the hit ratio is the dial.
The smaller systems around the video, and the questions that change the problem.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Add live streaming | A separate real-time ingest and encoding path, very short segments, and short TTLs on the playlist. The playback and CDN side is reused. |
| Add DRM and licensed content | Encrypt segments, add a licence server and key delivery, and tie signed URLs and keys to a subscription and device. Pre-position popular titles. |
| Most viewers are on mobile networks in poor-coverage regions | Add lower rungs (for example 144p), shorter segments, audio-only mode, and a cap on top quality. Measure start-up and freeze ratio by region. |
| Add a download-for-offline feature | Package a chosen quality as a bundle with a time-limited licence. Track downloads per user and expire them. |
| Videos can be edited after publish | Version the segments and the manifest. New edits get a new path, and the manifest pointer is switched atomically. Purge or let old caches expire. |
| Cut the cost by half | Higher hit ratio, efficient codecs for hot videos, fewer renditions, colder storage for the tail, and cheaper delivery routes. |
| Add personalised thumbnails and previews | Generate several candidate thumbnails and short preview clips in the pipeline. Choose by a model or an experiment. Keep it asynchronous and cached. |
| A region must keep data inside its borders | Regional object storage and CDN configuration, regional metadata, and signed URLs scoped to the region. Ingest and encode in the same region. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts drawing. Does not ask about live, devices or scale. | Asks about uploads versus catalog, devices, length and scale, and names what is out of scope. | Also asks how soon a video must be watchable and the start-up target, and says what changes for a catalog like Netflix. |
| Estimation | No numbers, or skips egress. | Computes peak viewers and bandwidth, and storage per day. | Gets to tens of Tbps, concludes the CDN is mandatory, sizes encoding cores, and names the hit ratio as a cost dial. |
| Design | One box for the video server. | Separates upload and playback, with object storage, a pipeline and a CDN. | Direct pre-signed upload, a chunk-parallel pipeline, immutable segments, tiered CDN with a shield, and async side systems. |
| Deep dives | Says use a CDN and transcode, with no detail. | Explains chunked encoding, HLS or DASH and how the player adapts. | Covers idempotent tasks, progressive publishing, coalescing and miss storms, codec trade-offs, and sharded view counters. |
| Trade-offs and cost | No mention of cost. | Names storage and egress as the big bills. | Quantifies a hit-ratio point, argues which videos get slow codecs, and tiers cold storage. |
| Communication | A long list of technologies. | Follows the steps and explains choices. | Summarises each step, checks in, and says what it would not build in 45 minutes. |
| Mistake | Do this instead |
|---|---|
| Serving video from the application servers | Say the origin cannot serve tens of Tbps, and make the CDN the core of the playback path. |
| Streaming the original file to everyone | Transcode to a ladder of qualities, cut into segments, and let the player adapt. |
| Encoding a whole video on one machine | Split into chunks at keyframes, encode in parallel, and make every task idempotent. |
| Uploading video bytes through the API servers | Use pre-signed multipart uploads straight to object storage, resumable, with the API only creating and completing. |
| Counting views with a database update per play | Send events to a queue and aggregate into sharded counters, off the playback path. |
| Ignoring the cost | Do the egress and storage maths, and name the levers: hit ratio, codecs, tiering and cheaper delivery routes. |
| Saying ready before every file exists | Write the manifest last, flip the status only after a check, and avoid caching 404s. |
| Permanent, guessable video URLs | Use signed, expiring URLs, and check access when signing. |
The core of the playback path and the biggest cost lever.
Pulling on demand versus pre-positioning popular content.
The home of originals and segments.
The shape of the transcoding fleet.
How to keep petabytes affordable.
Why egress, not latency, is the problem.
The viral video and its counter.
Where the edge caches live.