SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design Video Streaming (YouTube/Netflix)

Upload, transcode and play video smoothly for millions, on any device and network.

โฑ 36 min readMedium case studyAdvanced25 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

โ€œ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 checkWhy it matters
Splitting the problem in twoUpload 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 mathsVideo 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 parallelismTranscoding a long video on one machine takes hours. Splitting it into chunks, encoding in parallel and retrying safely is the standard answer.
Adaptive streamingNetworks 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-offsStorage, 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.

TL;DRThe whole design in 60 seconds

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.

  • Scale: 100M daily users watching 5 videos of 10 minutes is about 10M viewers at peak. At 3 Mbps each that is about 30 Tbps. No origin can serve that, so almost everything must come from the CDN.
  • Upload: pre-signed multipart upload to object storage. The API servers never carry the video bytes.
  • Processing: a job queue and a pool of workers. Split into chunks, encode in parallel, retry safely. A 4-hour file finishes in minutes, not hours.
  • Playback: HLS or DASH. 2 to 10 second segments, a ladder of qualities, and a player that picks the next segment from its measured speed and buffer.
  • Delivery: a tiered CDN (edge, regional, origin shield). Popular titles sit at the edge. The long tail comes from the origin and is cached on the way.
  • Off the hot path: view counts, thumbnails, moderation and recommendations are asynchronous, so they never slow the video.
๐Ÿ’กHow to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
4
4
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4User-uploaded or licensed catalog, devices and networks, max length, what is out (live, DRM, ads, recommendations).
2. Estimate4Peak viewers, egress in Tbps, storage per day, transcoding cores. Let the numbers justify the CDN.
3. API and data4Resumable upload, the manifest, the renditions and job records.
4. High-level design8Upload path, pipeline, origin, CDN tiers, player. Walk one upload and one view.
5. Deep dives15Pipeline first, then adaptive bitrate, then delivery at scale, then views and metadata.
6. Scale and failures7Viral video, failed encode, CDN miss storm, cost, monitoring.
7. Wrap up3Recap, trade-offs, what you would do next.

Step 1Clarify requirementsabout 4 min

๐Ÿค”
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change your design. Hint: think about who uploads, which devices and networks watch, how long videos are, and what you would leave out in 45 minutes.

Questions to ask, and why

AskWhy you ask itTypical answerHow 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.

Write the scope on the board

Functional (must do)
  • โ€ขUpload a video (resumable, up to a few GB)
  • โ€ขProcess it into several qualities and formats for every device
  • โ€ขStream it with adaptive quality, with seek and resume
  • โ€ขShow title, description and thumbnail, and count views
  • โ€ขLet the owner delete or hide a video
Non-functional (how well)
  • โ€ขPlayback availability 99.99%, start-up under 2 seconds
  • โ€ขSmooth: few freezes, quality adapts to the network
  • โ€ขScale: about 10M concurrent viewers and 500K uploads a day
  • โ€ขA new video is watchable within minutes of upload
  • โ€ขDurable: an uploaded video is never lost
  • โ€ขCost-aware: egress, storage and encoding are the big bills
Out of scope (say it)
  • โ€ขLive streaming
  • โ€ขSearch, recommendations and comments
  • โ€ขDRM, ads and per-country licensing
  • โ€ขVideo editing and the creator studio
๐ŸŽค
Say it out loud
โ€œLet me confirm the scope. This is on-demand video with user uploads, like YouTube, and I will say what changes for a catalog like Netflix. Up to four hours and a few GB per upload, 100 million daily users watching about five videos of ten minutes, and half a million uploads a day. Phones, browsers and TVs on any network, so adaptive quality. A video should be watchable within minutes of upload, playback should be 99.99% available with a start-up under two seconds. Live, search, recommendations, DRM and ads are out. Does that match?โ€

Step 2Estimate the scaleabout 4 min

๐Ÿค”
Pause. Try it yourself first
On paper: how many people watch at the same moment, and what bandwidth is that? How much video is stored per day, and how many CPU cores does encoding need? Which of these decides the whole design?

Assumptions (say them first)

AssumptionValue
Daily viewers100 million
Videos watched per viewer per day5, about 10 minutes each
Peak versus average concurrencyabout 3 times
Average stream bitrate (a mix of qualities)3 Mbps
Uploads per day500,000, average 100 MB and about 5 minutes
Stored per uploadthe original plus renditions, about 4 times the original in total
Encoding effort, all renditionsabout 10 CPU-minutes per minute of video
Segment length4 seconds
CDN edge hit ratio on playbackabout 95%
Egress price (illustrative only)$0.005 per GB

The arithmetic, line by line

WhatMathsResult
Views per day100M ร— 5500 million
Watch time per day500M views ร— 10 min5 billion minutes
Average concurrent viewers5B min รท 1,440 min per dayabout 3.5 million
Peak concurrent viewers3.5M ร— 3about 10 million
Peak egress10M ร— 3 Mbps30 Tbps (3.75 TB per second)
Egress per day5B min ร— 60 s ร— 3 Mbps รท 8about 112 PB
Segment requests at peak10M viewers รท 4 sabout 2.5 million per second
Raw upload per day500,000 ร— 100 MB50 TB (about 5 Gbps average, 14 Gbps at 3ร— peak)
Stored per day, all renditions50 TB ร— 4200 TB per day, about 73 PB per year (about 110 PB with 1.5ร— erasure coding)
Encoding work per day500,000 ร— 5 min ร— 10 CPU-min25 million CPU-minutes, about 417,000 CPU-hours
Encoding cores, average, then with 2ร— headroom417,000 รท 24 h, then ร— 2about 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 peak30 Tbps ร— 1%300 Gbps
Egress bill at the illustrative price112 PB = 112M GB ร— $0.005about $560,000 per day, so volume pricing and own caches matter
What the numbers tell us about the design
  • โ€ขPlayback egress is about 30 Tbps. No origin can serve that, so the CDN is the core of the design, not an add-on.
  • โ€ขThe CDN hit ratio is a money dial: every point is about 300 Gbps. Design for popular content at the edge and a tiered cache for the rest.
  • โ€ขUpload is small by comparison (about 5 Gbps), but encoding is heavy: about 35,000 cores with headroom. It must be a queue and a worker fleet.
  • โ€ขStorage grows about 200 TB a day, so cold videos need cheaper tiers, and we should ask which renditions are worth keeping.
  • โ€ขTwo and a half million segment requests a second is a CDN job. The API and metadata layer only sees about 6,000 views a second on average, which is small.
๐ŸŽค
Say it out loud
โ€œLet me do the maths. A hundred million users watching five ten-minute videos is five billion minutes a day, about 3.5 million watching on average and about 10 million at peak. At 3 megabits each that is 30 terabits a second. No origin serves that, so the CDN is the heart of the design, and every point of hit ratio is about 300 gigabits. Uploads are small by comparison, about 50 terabytes a day raw, but encoding all those renditions is around 35 thousand cores, so processing must be a queue and a worker fleet. Storage grows about 200 terabytes a day, so I will tier cold videos.โ€

Step 3Define the API and the data modelabout 4 min

๐Ÿค”
Pause. Try it yourself first
Write the calls for upload and for playback. Where do the video bytes travel? Which calls hit your servers, and which go straight to storage or the CDN?

Endpoints

MethodPathRequestResponseNotes
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}none200 { 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}none200 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 }204Fire and forget. Goes to a queue and is counted later, so it never slows playback.

Data model

Table or storeKey fieldsNotes
videosvideo_id, owner_id, title, description, status, duration, created_at, original_keySmall, read-heavy. SQL or a key-value store. Cached hard. About 1 KB per row.
renditionsvideo_id, quality, codec, bitrate, manifest_key, statusOne row per quality per video. Tells the packager and the manifest what exists.
transcode_jobsjob_id, video_id, chunk_no, quality, state, attempts, worker, updated_atOne row per task. State: queued, running, done, failed. Makes retries and progress visible.
object store: originalsvideos/{id}/originalThe source of truth, kept in a durable and cheap tier.
object store: segmentsvideos/{id}/{quality}/seg_00001.m4s, plus the manifestImmutable files, so they cache perfectly. This is what the CDN fetches.
view countsvideo_id, day, countA separate store fed by a stream. Sharded counters. Never on the playback path.
A small master playlist (HLS)
#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
๐Ÿ“Which store, and why
Three kinds of data, three stores. Video files are huge, written once and read many times, so they go in object storage (cheap, durable, and the CDN can fetch from it). Metadata and job state are small and relational, so a replicated SQL or key-value database is fine, with a cache in front. View counts are a high-rate stream of tiny increments, so they go through a queue into a counter store.
๐ŸŽค
Say it out loud
โ€œUploads are a three-call flow. The client asks for an upload and gets pre-signed URLs, sends the parts straight to object storage so our API never carries video bytes, then calls complete, which emits an event that starts processing. Playback is two reads: a small metadata call that returns a signed manifest URL, and then the manifest and the segments, which come from the CDN. Metadata is a small relational table, video files live in object storage as immutable segments, and views go through a queue so they never slow playback.โ€

Step 4Draw the high-level designabout 8 min

๐Ÿค”
Pause. Try it yourself first
Draw the boxes. Keep the upload and the playback paths apart. Where does each video byte travel, and which box would you scale first?
Video streaming: high-level design
๐Ÿ“ฑUploaderapp or browser
โ†’โ†“parts, pre-signed
๐Ÿ—„๏ธObject storageoriginals
โ†’โ†“uploaded event
๐Ÿ“จJob queuechunk tasks
โ†’โ†“
Transcoding workers
โœ‚๏ธSplitinto chunks
๐ŸŽž๏ธEncodeall qualities, in parallel
๐Ÿ“ฆPackagesegments + manifest
Playback
โ–ถ๏ธPlayerpicks quality per segment
โ†“HTTP
๐ŸŒCDN edgecached segments
โ†“miss
๐ŸขRegional + origin shieldtiered cache
โ†“miss
๐Ÿ—„๏ธObject storagesegments
Control plane
๐ŸงพMetadata serviceAPI + cache
๐Ÿ’พMetadata DBreplicated
๐Ÿ””Pipeline statusqueued, done, failed
Off the hot path
๐Ÿ“ŠView eventsqueue to counters
๐Ÿ›ก๏ธModerationasync checks
๐Ÿ–ผ๏ธThumbnailsafter encode
Upload goes straight to object storage. A pipeline turns it into segments. Playback comes from the CDN.
ComponentWhat it does
Object storageDurable home of the originals and of every segment. The CDN and the encoders read from it.
Upload serviceCreates the multipart upload and the pre-signed URLs, and completes it. Never touches the video bytes.
Job queueHolds one task per chunk and quality. Gives retries, priorities and back pressure when the workers are busy.
Transcoding workersSplit, encode and package. Stateless, so we can add thousands on demand (spot or preemptible machines work well).
Metadata service and DBTitle, status, manifest location and job records. Small data, cached, replicated across zones.
CDN with tiersEdge caches near viewers, regional caches behind them, and an origin shield in front of storage to collapse misses.
PlayerReads the manifest, downloads segments, measures speed and buffer, and picks the quality of the next segment.
View, moderation and thumbnail pipelinesAsynchronous consumers of events. A failure here never stops a video playing.
Write path (follow one request)
  1. The client calls POST /videos. The service creates a record with status uploading and a multipart upload, and returns pre-signed part URLs.
  2. The client uploads parts straight to object storage, in parallel, and retries only a failed part. It can resume after a break.
  3. The client calls complete. The service finishes the upload, sets status processing and emits an uploaded event.
  4. A planner reads the video, cuts it into chunks at keyframes (for example 4 minutes), and queues one task per chunk and quality, lowest quality first.
  5. Workers pull tasks, encode, and write segments to object storage. Each task is idempotent: the same output path, so a retry just overwrites.
  6. When a quality is complete, the packager writes its playlist and updates the master manifest. The first low quality makes the video watchable.
  7. Thumbnails and moderation run in parallel. When all required qualities are done and checks pass, status becomes ready.
Read path (follow one request)
  1. The player calls GET /videos/{id}. The metadata service answers from cache with title, status and a signed manifest URL.
  2. The player fetches the master manifest from the CDN, which lists the qualities.
  3. It starts at a low quality for a fast start, downloads the first segment from the nearest edge, and starts playing.
  4. The edge returns a cached segment if it has it. On a miss it asks the regional cache, then the origin shield, then object storage, and caches on the way back.
  5. After every segment the player measures the download speed and its buffer, and picks the quality of the next segment.
  6. Every few seconds it sends a small view event. This goes to a queue and never blocks playback.
๐ŸŽค
Say it out loud
โ€œHere is the picture. The upload path goes straight from the client to object storage using pre-signed multipart URLs, so our servers never carry video bytes. An uploaded event feeds a job queue, and a worker fleet splits the video into chunks, encodes every quality in parallel and packages segments and a manifest back into object storage. The playback path is separate. The player gets a signed manifest URL from a small metadata service, then pulls segments over HTTP from a tiered CDN, picking the quality of each next segment from its speed and buffer. Views, thumbnails and moderation are asynchronous and off the hot path.โ€

Step 5Deep dive into the hard partsabout 15 min

๐Ÿง The pattern for every deep dive
Problem โ†’ options โ†’ pick one โ†’ say why โ†’ say what it costs. Interviewers score the reasoning more than the choice.
5.1

The upload and transcoding pipeline

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.

OptionHow it worksGoodBad
One worker encodes the whole fileA 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 parallelCut 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 videoAlways 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 ladderAnalyse 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.
Pick
Chunk-parallel encoding from a task queue, with a fixed ladder first and per-title tuning later for popular videos

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.

CodecCompressionCost and reach
H.264 (AVC)Baseline. Plays almost everywhere.Cheapest to encode. The safe default for every device.
VP9 or HEVCRoughly 30% to 50% smaller at the same quality (varies by content).Slower to encode. Support differs by device and licence.
AV1Smaller 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.
๐Ÿ’กSpend encoding effort where the views are
A video watched ten million times saves real money if it is 30% smaller, so give hot videos the slow, efficient codecs later. A video watched twice does not deserve it. Encode cheap and fast first, and re-encode the winners.
๐ŸŽค
Say it out loud
โ€œI would cut the video at keyframes into chunks of a few minutes and queue one task per chunk and quality. A four-hour film becomes about 60 chunks and 300 tasks, so with a few hundred workers it finishes in minutes. Tasks are idempotent: they write to a fixed path, so a retry overwrites. I encode the lowest quality first so the video is watchable early, and I give the slow, efficient codecs only to videos that turn out to be popular.โ€
5.2

Adaptive bitrate streaming

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.

OptionHow it worksGoodBad
One file, one qualityServe 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.
Pick
Segmented HTTP streaming (HLS and DASH) with a quality ladder and a client-side adaptive algorithm

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.

RungResolutionBitrate (illustrative)
1240p0.4 Mbps
2360p0.8 Mbps
3480p1.5 Mbps
4720p3 Mbps
51080p5 Mbps
๐Ÿ“Try it: the visualizer below
Switch between always 1080p, a throughput rule and a buffer rule on a network with a long dip. Fixed 1080p freezes for a long time. The adaptive rules trade some sharpness for a smooth picture.
๐ŸŽค
Say it out loud
โ€œI would use HLS or DASH. Each quality is cut into a few seconds per segment, a manifest lists them, and the player chooses the quality of every next segment from its measured speed and its buffer. It is plain HTTP, so the CDN caches it, and the server keeps no state per viewer, so it scales. I would start at a low quality for a fast first picture, climb as the buffer fills, and step down quickly when the buffer drains.โ€
5.3

Delivering at scale: the CDN

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.

OptionHow it worksGoodBad
Serve everything from the originPlayers 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 tierEdge 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 shieldEdge, 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 ISPsPush 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.
Pick
A tiered pull CDN with request coalescing and an origin shield, plus pre-positioning for known-popular content

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.

TrafficWhere it comes fromWhy
Popular videos (a small share of titles, most of the watch time)Edge cache, nearly always a hitSmall set, watched constantly. Can be pre-positioned.
Mid-popularity videosRegional cacheNot hot enough for every edge, but hit often enough to stay cached.
The long tailOrigin, cached on the wayRarely watched. Each first view is a miss. Keep the origin cheap and fast.
โš ๏ธDo not forget cost
Egress is the largest bill. Better compression (newer codecs), a higher hit ratio, and cheaper delivery routes all save money. Ask what each saves, not only what it speeds up.
๐ŸŽค
Say it out loud
โ€œSegments never change, so the cache key is the URL and the TTL can be long. I would use a tiered CDN: edge, regional, and an origin shield in front of storage, with request coalescing at each tier so a viral video sends one request to the origin, not thousands. Popular titles can be pre-positioned to edge caches overnight, and the long tail simply comes from the origin and caches on the way back. One point of hit ratio is about 300 gigabits at peak, so it is worth watching.โ€
5.4

Views, metadata and access control

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.

OptionHow it worksGoodBad
Increment a database row on every viewUPDATE 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 storeSpread 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 batchesPlayers 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.
Pick
View events through a queue, aggregated in batches into sharded counters, with a short-lived cache for the displayed number

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.

๐ŸŽค
Say it out loud
โ€œI would not touch a database row per view. Players send view events to a queue, a stream job counts them per video per minute and writes sharded counters, and the page shows a cached total a few seconds old. It also lets me filter bots in one place. Metadata is small, so it is cached hard. Access is by signed, expiring URLs, and moderation and copyright checks run as asynchronous stages before a video is published.โ€
VisualizerAdaptive bitrate: pick the quality of every next segmentChoose a network with a dip or a flaky one. Compare always 1080p with the two adaptive rules. Watch freezes, average quality and start-up time. Then move the safety margin.
Network
How does the player choose the quality of the next segment?
Network speed (taller = faster)
Quality chosen (taller and greener = sharper)
Seconds of video in the buffer (red = froze here)
start60 s120 s of video
240p (0.4 Mbps)360p (0.8 Mbps)480p (1.5 Mbps)720p (3 Mbps)1080p (5 Mbps)
Start-up delay
3.3 s
until the first picture
Freezes
8
122.0 s frozen
Average quality
5.0 Mbps
about 1080p
Quality changes
0
switches between rungs
The picture froze 8 times, 122.0 s in total. Always asking for 1080p (5 Mbps) means a segment needs more speed than the network had, so a 4-second segment took longer than 4 seconds to arrive.

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.

Step 6Scale, bottlenecks and failuresabout 7 min

๐Ÿค”
Pause. Try it yourself first
If one video goes viral, what breaks first? If an encoding job fails halfway, what does the uploader see? If egress doubles, where does the bill go?

What breaks first, and the fix

BottleneckFix
Origin traffic on a new viral videoRequest coalescing and an origin shield. Pre-warm the first segments of a video that is spreading fast.
Encoding backlog after a burst of uploadsA queue with priorities, autoscaled spot workers, and low qualities first so videos become watchable early.
Egress costRaise 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 videoCache 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 segmentsUse 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 networksBegin at a low quality, short first segments, and a manifest that is small and cached.

What if a part fails?

FailureHow the design copes
A transcoding worker dies mid-taskThe 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 dropsThe 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 downDNS 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 zoneMulti-zone storage with replication. The shield retries and serves stale segments if it must.
The metadata database fails overA replica is promoted. Cached metadata keeps playback going for videos already known, and writes retry.
What to monitor
  • โ€ขStart-up time and freeze ratio at the player, by country, device and ISP (the true quality measure)
  • โ€ขCDN hit ratio and origin traffic, by tier
  • โ€ขTime from upload complete to the first playable quality
  • โ€ขQueue depth, task failure rate and dead-letter size for transcoding
  • โ€ขSegment error rate and the share of players stuck on the lowest quality
  • โ€ขEgress per day and cost per hour watched
Security and abuse
  • โ€ขSigned, expiring URLs for manifests and segments, so links cannot be shared forever or hotlinked
  • โ€ขValidate every upload: type, size and container, in a sandbox, since encoders parse untrusted files
  • โ€ขVirus and abuse scanning, and copyright matching, before publishing
  • โ€ขRate limit uploads and view events per user and IP (link to the rate limiter)
  • โ€ขPrivate and unlisted videos need an access check when issuing the signed URL

Step 7Wrap upabout 3 min

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.

Trade-offs you made

DecisionWhat we gainWhat it costs
Pre-signed direct upload to object storageOur API never carries video bytes. Uploads resume and scale on their own.More client logic, and a cleanup job for abandoned uploads.
Chunk-parallel encodingMinutes 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 shieldA tiny origin load, and a much better hit ratio.More layers to run, and a slightly slower cold miss.
Asynchronous view countsPlayback is never slowed by counting.Counts are a few seconds to minutes late.
Several renditions per videoSmooth playback on every device and network.About 4 times the storage and a large encoding bill.
If we had more time, we wouldโ€ฆ
  • โ€ขPer-title encoding and AV1 for the most-watched videos, to cut egress.
  • โ€ขPre-positioning popular videos to edge caches ahead of known demand.
  • โ€ขLive streaming, which needs a different low-delay pipeline.
  • โ€ขDRM and per-country licensing with a licence server.
  • โ€ขRecommendations and search, as separate services over view and metadata events.
๐ŸŽค
Say it out loud
โ€œTo recap: uploads go straight to object storage, a chunk-parallel pipeline turns them into immutable segments and a manifest, and playback is adaptive HTTP streaming from a tiered CDN. The numbers drive it: about 30 terabits a second at peak means the CDN carries nearly everything, so the hit ratio is the key dial, and encoding is a queue-and-workers job. Counts and moderation run off to the side. Next I would add per-title encoding and AV1 for popular videos to cut egress, then live and DRM.โ€

Q&ACross-questions (25)

๐Ÿ’กHow to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Playback and adaptive streaming

The core of the product. Know why segments exist and how the player decides.

Upload and processing

Where most of the compute goes. Show parallelism, idempotency and failure handling.

Delivery, scale and cost

Where the money is. Show you know the CDN is the design, and the hit ratio is the dial.

Metadata, views and curveballs

The smaller systems around the video, and the questions that change the problem.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Add live streamingA 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 contentEncrypt 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 regionsAdd 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 featurePackage a chosen quality as a bundle with a time-limited licence. Track downloads per user and expire them.
Videos can be edited after publishVersion 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 halfHigher hit ratio, efficient codecs for hot videos, fewer renditions, colder storage for the tail, and cheaper delivery routes.
Add personalised thumbnails and previewsGenerate 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 bordersRegional object storage and CDN configuration, regional metadata, and signed URLs scoped to the region. Ingest and encode in the same region.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts 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.
EstimationNo 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.
DesignOne 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 divesSays 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 costNo 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.
CommunicationA 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.

AvoidCommon mistakes on this question

MistakeDo this instead
Serving video from the application serversSay the origin cannot serve tens of Tbps, and make the CDN the core of the playback path.
Streaming the original file to everyoneTranscode to a ladder of qualities, cut into segments, and let the player adapt.
Encoding a whole video on one machineSplit into chunks at keyframes, encode in parallel, and make every task idempotent.
Uploading video bytes through the API serversUse pre-signed multipart uploads straight to object storage, resumable, with the API only creating and completing.
Counting views with a database update per playSend events to a queue and aggregate into sharded counters, off the playback path.
Ignoring the costDo the egress and storage maths, and name the levers: hit ratio, codecs, tiering and cheaper delivery routes.
Saying ready before every file existsWrite the manifest last, flip the status only after a check, and avoid caching 404s.
Permanent, guessable video URLsUse signed, expiring URLs, and check access when signing.

Revise60-second revision sheet

  • โœ”Scale: 100M users ร— 5 videos ร— 10 min = 5B minutes a day, about 10M viewers at peak, 30 Tbps. The CDN is the design.
  • โœ”Hit ratio: one point is about 300 Gbps at peak. At 95%, the origin sees about 1.5 Tbps (less with a regional tier).
  • โœ”Upload: pre-signed multipart straight to object storage, resumable. The API never carries video bytes.
  • โœ”Pipeline: event, queue, split into chunks at keyframes, encode all qualities in parallel, package segments plus manifest. Idempotent tasks, fixed output paths.
  • โœ”Publish progressively: lowest quality first, so the video is watchable in minutes. Write the manifest last.
  • โœ”Playback: HLS or DASH. 2 to 10 second segments, a quality ladder, and a client that picks per segment from throughput and buffer.
  • โœ”Start low, climb: a small first segment gives a fast first picture. Step down fast, up slowly.
  • โœ”CDN: segments are immutable. Tiered cache with an origin shield and request coalescing stops miss storms.
  • โœ”Cost: egress is the biggest bill. Levers: hit ratio, efficient codecs for hot videos, cold tiers, cheaper routes.
  • โœ”Views: events through a queue into sharded counters, a cached total on the page. Never a row update per view.

Read these topics next

CDNโ†’

The core of the playback path and the biggest cost lever.

CDN Push vs Pullโ†’

Pulling on demand versus pre-positioning popular content.

Object Storageโ†’

The home of originals and segments.

Task Queues, Workers and Scheduled Jobsโ†’

The shape of the transcoding fleet.

Storage Tiers (Hot, Warm, Cold)โ†’

How to keep petabytes affordable.

Latency vs Throughput vs Bandwidthโ†’

Why egress, not latency, is the problem.

Hot Keysโ†’

The viral video and its counter.

Cloud Basics: Regions, Zones and Edgeโ†’

Where the edge caches live.

โ† Previous
Design File Storage (Dropbox)
Next โ†’
Design a Distributed Cache