The Problem#
Design a video platform like YouTube or Netflix. Creators upload videos, from a 20-second phone clip to a 4-hour 4K recording of tens of gigabytes. Viewers press play on any device (a phone on a train, a laptop on hotel Wi-Fi, a 4K TV on fibre) and expect the video to start in a second or two and never stall.
Those two verbs, upload and watch, look simple. They hide most of the hard problems in large-scale systems: moving huge files reliably over flaky networks, burning enormous amounts of CPU to convert each video into many versions, storing exabytes cheaply, and delivering terabits per second to viewers all over the world with low latency.
Analogy. Think of a publisher that receives a manuscript in the author's handwriting. Before anyone can read it, the publisher must typeset it into many editions: large print, pocket size, an audiobook, a translation. Each edition is cut into chapters, so a reader can start at chapter one while the rest is still on its way, and switch from the large print to the pocket edition halfway through if they need to travel light. The editions are stocked in local bookshops near the readers rather than shipped from the central warehouse every time. Video streaming does exactly this. Transcoding is the typesetting, renditions are the editions, segments are the chapters, adaptive bitrate is switching editions mid-book, and the CDN is the network of local bookshops.
YouTube and Netflix are two ends of one design space. YouTube is user-generated: millions of uploads per day, a very long tail of rarely watched videos, and processing speed matters (creators want their video live quickly). Netflix is a curated catalogue: a small number of titles, each watched by millions, so it can afford to spend enormous compute per title to squeeze out bandwidth, and it pre-positions content near viewers. We will design for the YouTube shape and point out where Netflix's choices differ.
Clarifying Questions#
| Question | Assumed answer | Why it matters |
|---|---|---|
| Which features are in scope? | Upload and watch are core; video metadata, search and view counts are in scope; comments, recommendations and channels are out of scope | Upload and watch drive the architecture; the rest are separate systems |
| How big can uploads be? | Up to tens of GB (long 4K recordings) | Rules out uploading through app servers; needs resumable chunked upload |
| Which devices? | Web, iOS, Android, smart TVs, consoles | Many codecs, containers and DRM systems must be supported |
| What scale? | About 1 million uploads and 100 million video views per day, growing | Sizes storage, transcoding and CDN egress |
| How fast must a new upload become watchable? | Within minutes for typical videos; longer for very long or 4K videos | Pushes towards parallel transcoding |
| Is live streaming in scope? | Discuss how it differs; video on demand (VOD) is the focus | Live changes ingest, processing and caching |
| Is content protection required? | Private and unlisted videos for user content; studio DRM for premium content | Signed URLs and DRM shape delivery |
| Consistency needs? | Availability over consistency; view counts may lag | Lets us cache aggressively and count asynchronously |
| Global audience? | Yes, viewers on every continent | CDN placement, multi-region metadata |
Requirements#
Functional Requirements#
- Upload videos. A creator uploads a video file with metadata (title, description, tags, visibility). Uploads are resumable.
- Watch videos. A viewer streams any public video on any device, starting quickly and adapting quality to their network.
- View video information. Title, description, channel, upload date, duration and view count.
- Search videos by title, description, tags and spoken words (transcripts).
- Count views, roughly in real time, robust to bots and retries.
Out of scope: comments (see the live comments case study for the realtime version), recommendations, channel management, subscriptions, monetisation and ads. Moderation and copyright matching are mentioned where they touch the pipeline.
Non-Functional Requirements#
- High availability, prioritising availability over consistency. A video being briefly invisible after upload, or a view count lagging by a minute, is fine; being unable to play is not.
- Large uploads: files of tens of GB, over unreliable mobile and home networks, resumable after interruption.
- Low-latency, smooth playback even on poor networks: time to first frame under about 2 seconds at p90, rebuffering under 1% of watch time.
- Scale: about 1 million uploads per day and 100 million views per day to start, designed to grow 10x.
- Durability: an uploaded original must never be lost (eleven nines of object durability, the level S3 is designed for).
- Reasonable processing time: a 10-minute 1080p video playable within a few minutes of upload finishing.
- Cost efficiency: bandwidth and storage dominate cost, so the design must minimise bytes stored and bytes delivered.
For a problem with so few functional requirements, the non-functional requirements carry the interview. They turn "upload" and "watch" into large files, flaky networks, global audiences and low latency, and each deep dive below exists to satisfy one of them.
Capacity Estimation#
We work with round numbers and say our assumptions out loud. See Back-of-the-Envelope Estimation.
Uploads.
uploads: 1,000,000 / day ~ 12 / s average, ~50 / s at peak
average length: ~10 minutes; average original size ~ 500 MB
(1080p at ~6-8 Mbps x 600 s ~ 450-600 MB)
ingest: 1M x 500 MB = 500 TB / day of originals ~ 46 Gbps average inboundFor scale, YouTube has said that more than 500 hours of video are uploaded every minute (a figure it published in 2019). That is 720,000 hours per day, about 4 million 10-minute videos, so our "1 million per day" is a realistic interview baseline, a few times smaller than the real thing.
Transcoded storage. Each video is converted into an encoding ladder: several resolutions and bitrates, possibly in more than one codec.
example H.264 ladder (video bitrate):
240p 0.3 Mbps, 360p 0.7, 480p 1.2, 720p 2.5, 1080p 4.5 => ~9.2 Mbps total
+ audio tracks ~0.2 Mbps
a second, more efficient codec (VP9 or AV1) at ~60% of the bitrate: ~5.5 Mbps
total renditions ~ 15 Mbps vs ~7 Mbps original => ~2x the original size
per day: 500 TB originals + ~1 PB renditions ~ 1.5 PB / day
per year: ~550 PB, before replication or erasure coding overheadIn practice the second codec is produced only for videos that get enough views to pay for it (Deep Dive 2), which cuts this considerably. Even so, storage grows by hundreds of petabytes per year, which is why tiering and erasure coding matter (Deep Dive 11).
Transcoding compute. This is the most expensive part of ingest.
video per day: 1M x 10 min = 10M minutes ~ 167,000 hours of video
H.264 ladder in software: ~5-10 CPU-core-hours per hour of 1080p video
=> ~0.8-1.7 million core-hours / day ~ 35,000-70,000 cores busy around the clock
AV1 software encoding is many times slower than H.264
=> only for popular videos, or with hardware encodersThese are rough, because encoding speed depends heavily on presets and content, but the order of magnitude (tens of thousands of cores) is the point. It is why Google built custom video-transcoding chips for YouTube (described in Deep Dive 1).
Views and egress.
views: 100M / day ~ 1,160 / s average, ~5,000 / s peak
average watch time per view: ~5 minutes; average delivered bitrate ~3 Mbps
bytes per view: 300 s x 3 Mbps / 8 ~ 112 MB
egress: 100M x 112 MB ~ 11 PB / day
= 11 x 10^15 x 8 bits / 86,400 s ~ 1 Tbps average, ~3 Tbps at peak
concurrent viewers: 100M x 5 min / 1,440 min ~ 350,000 average, ~1M peakEgress is the dominant cost. At list CDN prices of a few cents per GB, 11 PB per day would cost hundreds of thousands of dollars per day, which is why the largest platforms build their own CDNs and place caches inside internet service providers (Deep Dive 5).
Request rates.
metadata reads: each view + browsing and search pages ~10 reads per view
=> ~12,000 / s average, ~50,000 / s peak (mostly cache hits)
segment requests: 1M concurrent viewers / 4-second segments
=> ~250,000 segment requests / s at peak (served by the CDN)
view and heartbeat events: one heartbeat per viewer every ~30 s
=> ~33,000 events / s at peak
search queries: ~5,000-20,000 / sThe shape is clear: writes are rare and huge (uploads), reads are frequent and also huge (segments), and the read-to-write ratio for any given video is extreme. A viral video is uploaded once and watched millions of times. See Pattern: Scaling Reads.
Core Entities#
- User: a creator or viewer.
- Video: the logical video, identified by
videoId. Holds its processing status (uploading,processing,ready,failed), visibility and owner. - VideoMetadata: title, description, tags, duration, thumbnails, language, caption tracks, and pointers to the manifest files.
- Upload session: an in-progress resumable upload. It tracks the multipart upload id and the status of each chunk.
- Rendition: one version of the video (codec, resolution, bitrate, container). It is made of many segments, each a few seconds long.
- Manifest: a text file listing renditions (the primary or "master" manifest) or the segments of one rendition (a media manifest). Players read manifests to know what to fetch.
- View event: a record that someone watched part of a video, used for view counts and analytics.
- Watch progress: where a user stopped in a video, so they can resume.
API Design#
The first-draft API usually looks like POST /upload with the video in the body and GET /videos/{id} returning the bytes. Both change once we accept that video bytes should never flow through our application servers. Say so in the interview: "I'll sketch simple endpoints and refine them as the design evolves." See API Design Best Practices.
POST /v1/videos
Authorization: Bearer <token>
{ "title": "...", "description": "...", "tags": [...], "visibility": "public",
"fileSize": 5368709120, "contentType": "video/mp4", "sha256": "..." }
-> 201 { "videoId": "v_9f2c", "uploadId": "u_77a1", "partSize": 16777216,
"partUrls": [ { "part": 1, "url": "https://bucket.s3...&X-Amz-Signature=..." }, ... ] }
PUT <presigned part URL> -- client uploads bytes directly to blob storage
POST /v1/videos/{videoId}/parts -- { "part": 7, "etag": "..." } records progress
GET /v1/videos/{videoId}/upload -- which parts are done (for resume)
POST /v1/videos/{videoId}/upload:complete -- finishes the multipart upload, starts processing
GET /v1/videos/{videoId}
-> 200 { "title": "...", "status": "ready", "durationSec": 612, "views": 18234,
"manifests": { "hls": "https://cdn.example.com/v_9f2c/master.m3u8",
"dash": "https://cdn.example.com/v_9f2c/manifest.mpd" },
"thumbnails": [...], "captions": [...] }
GET /v1/search?q=...&cursor=... -- paginated results
POST /v1/videos/{videoId}/views -- { "sessionId": "...", "positionSec": 30 } heartbeat
PUT /v1/users/me/progress/{videoId} -- { "positionSec": 245 } resume pointNotes:
POST /v1/videosreplacesPOST /upload. The request carries only metadata; the response carries presigned URLs, time-limited signed URLs that let the client write directly to blob storage without our credentials. See Pattern: Handling Large Files and Blobs.GET /v1/videos/{id}returns metadata and manifest URLs, not video bytes. The player fetches manifests and segments from the CDN.- Viewing endpoints for private or unlisted videos return signed CDN URLs or set signed cookies so the CDN can check access (Deep Dive 10).
- Writes use idempotency keys (the
sha256of the file, or a client-generated key) so a retriedPOST /v1/videosdoes not create two videos. See Idempotency and Safe Retries.
High-Level Design#
Background: five terms you need#
You do not need to be a video engineer to pass this interview, but you do need these five ideas.
- Codec (coder-decoder): the algorithm that compresses and decompresses video. Codecs trade off encoding time, device support, compression efficiency and quality. Common ones: H.264/AVC (2003, plays everywhere), H.265/HEVC (2013, about 30-50% smaller files at the same quality, patent licensing is complex), VP9 (Google, 2013, royalty-free, widely used by YouTube), and AV1 (Alliance for Open Media, 2018, royalty-free, roughly 30% better than VP9 but much slower to encode). Older ones such as MPEG-2 survive in broadcast. Almost all are lossy: they discard detail the eye is unlikely to notice.
- Container: the file format that wraps encoded video, audio, subtitles and metadata together, such as MP4 (and its fragmented form fMP4), MPEG-TS, WebM and MKV. The codec decides how pictures are compressed; the container decides how the compressed streams are laid out in a file. Device support varies for both.
- Bitrate: bits per second of video, in kbps or Mbps. Higher resolution and frame rate need more bits; a better codec needs fewer for the same quality. Bitrate determines file size (
size = bitrate × duration) and the network speed needed to play without stalling. - Segment: a small, independently playable piece of a rendition, typically 2 to 6 seconds long. Each segment starts with a keyframe (a complete picture, also called an I-frame), so a player can start or switch quality at any segment boundary.
- Manifest: a text index. A primary (or master) manifest lists the available renditions and their bitrates and resolutions. Each media manifest lists the URLs of one rendition's segments in order. The player reads the primary manifest, picks a rendition, then fetches segments listed in its media manifest.
We will call a codec plus container combination a format, and a format at a particular resolution and bitrate a rendition.
1. Users can upload videos#
Two questions come first: where do the metadata and the bytes live?
Metadata. At 1 million uploads per day, we add about 365 million video records per year, and reads are point lookups by videoId far more often than anything else. A horizontally partitioned store keyed by videoId fits: Cassandra (high availability, tunable consistency, easy horizontal scaling) or DynamoDB. Because every read is "get this video", we do not need careful partitioning to co-locate related rows; a uniform hash of videoId spreads load evenly. YouTube itself famously scaled on MySQL by building Vitess, a sharding layer it later open-sourced, which shows a sharded relational database also works. See Apache Cassandra in Practice and Partitioning and Sharding.
Bytes. Video files go to object storage (Amazon S3, Google Cloud Storage, Azure Blob Storage) and never through our application servers. The client asks the video service for presigned URLs and uploads directly, in parts, using multipart upload. Our servers handle only small metadata requests. See Object Storage and Blob Storage.
What do we store for the video? This choice shapes everything downstream.
Bad: store only the raw upload
Keep exactly the file the creator sent and serve it. This fails immediately: the upload may be a 4K ProRes file from a camera, an HEVC file from an iPhone, or an old AVI. Many devices cannot decode it, and almost no viewer has the bandwidth for a 50 Mbps original.
Good: transcode into several formats
When the upload completes, object storage emits an event (S3 event notifications) to a processing service, which converts the original into several formats (for example H.264 MP4 at 360p, 720p and 1080p), stores each as a file, and records their locations in the metadata. Now every device can play something. The flaw: each rendition is one big file, so a player cannot easily fetch "the next few seconds" or switch quality midway, which is exactly what smooth streaming needs.
Great: transcode into formats, cut into segments
Split each rendition into segments of a few seconds, each independently playable, and generate manifests that index them. This is strictly better: players can start after one segment, fetch ahead incrementally, and switch rendition at any segment boundary. It makes the processing service a pipeline (split, transcode, package, write manifests), and we must store and reference millions of segment files sensibly. That pipeline is Deep Dive 1.
2. Users can watch videos#
GET /v1/videos/{id} now returns metadata, including manifest URLs, rather than the video itself. How does the client play the video?
Bad: download the whole file, then play
The client downloads the complete file and starts playing when it finishes. A 10 GB file takes over 13 minutes on a 100 Mbps connection before the first frame. And if the single long HTTP request breaks halfway, the progress may be lost and the download restarts. This is download-and-play, not streaming.
Good: download segments incrementally
The client picks a rendition based on the device, the connection and the user's setting (for example "1080p"), fetches the first segment and starts playing within a second or two, then keeps fetching segments a little ahead of the playhead. A dropped connection costs one segment, not the whole download.
The flaw is that the choice is fixed. If the network degrades mid-video, 1080p segments arrive more slowly than they are played and the video rebuffers (stalls with a spinner).
Note that this is different from a byte-range "chunked download" of one file. Some MP4 files can be played progressively, but not all formats can, and arbitrary byte chunks are not independently playable. Segments that each begin with a keyframe make incremental playback, and later switching, explicit.
Great: adaptive bitrate streaming (ABR)
Store each video as segments in several renditions, plus a manifest that lists them all. The player:
- Fetches the video metadata, which contains the primary manifest URL.
- Downloads the primary manifest and sees the available renditions.
- Chooses a starting rendition from its network estimate and user settings, and fetches that rendition's media manifest and first segment.
- Plays the segment while fetching the next ones into a buffer.
- Measures throughput and buffer level continuously and, at each segment boundary, switches down to a lower bitrate if the network slows or up if it improves.
This is how YouTube, Netflix, Twitch and essentially every large video service work, using the HLS or DASH protocols (Deep Dive 3). The client becomes an active, intelligent part of the system, and it depends on the upstream decisions to store segments in many renditions and to generate manifests.
3. Search, view counts and information#
These are side systems that read from or feed the core:
- Search: the metadata DB publishes changes (change data capture) into a search index such as Elasticsearch, which also indexes auto-generated transcripts (Deep Dive 7).
- View counts: players send view events and heartbeats to an event endpoint; events flow through Kafka into a stream aggregator that updates counters (Deep Dive 8).
- Video information: served from the metadata DB through a cache, with the view count merged in from the counter store.
The full high-level design#
The upload and processing side:
The viewing side:
Components:
- API gateway: authentication, rate limiting, routing. See API Gateway and Backend-for-Frontend.
- Video service: stateless. Creates video records, issues presigned URLs, tracks upload parts, serves metadata. Scales horizontally behind a load balancer.
- Video metadata DB: Cassandra (or DynamoDB, or sharded MySQL via Vitess), partitioned by
videoId, replicated three ways. - Metadata cache: Redis or Memcached with LRU eviction, partitioned by
videoId, absorbing reads for popular videos. - Object storage: one bucket (or bucket family) for originals, another for renditions, segments, manifests, thumbnails and captions. Originals are kept so we can re-encode later with better codecs.
- Workflow orchestrator: builds and runs the processing DAG for each upload (Deep Dive 1). Temporal, AWS Step Functions, or an in-house system. See Temporal and Workflow Engines.
- Transcode workers: a large autoscaled fleet running ffmpeg or a custom encoder on CPUs, GPUs, or dedicated video chips; they read inputs from and write outputs to object storage, passing only URLs between steps.
- CDN: edge caches near viewers (including caches inside ISPs), a mid-tier shield, and object storage as the origin (Deep Dive 5).
- Search service and index: Elasticsearch fed by change data capture from the metadata DB.
- Event collector, Kafka and stream aggregator: view counting and analytics (Deep Dive 8).
Key Flows#
Flow 1: Resumable upload#
The client sends several parts in parallel (for example 4 at a time) to use its bandwidth fully. Presigned URLs expire (for example after a few hours), so a long upload asks for fresh URLs for the remaining parts. Deep Dive 4 covers the details.
Flow 2: Processing a new video#
Flow 3: Playing a video#
Once the player has the manifests, it talks only to the CDN. If every manifest and segment is cached at the edge, our backend is not involved at all in continuing playback, which is what lets the system serve terabits per second.
Data Model#
The upload side of the model:
The media and counting side:
| Table / store | Partition key | Notes |
|---|---|---|
| VIDEO (Cassandra) | video_id | Point lookups; replication factor 3; cached in Redis |
| UPLOAD_PART | video_id, clustered by part_number | Deleted or expired after upload completes |
| RENDITION | video_id, clustered by rendition_id | Small; often embedded in the video record as a list |
| SEGMENT | not usually stored in the DB | The media manifest in object storage is the segment index; storing millions of segment rows per day adds nothing |
| VIEW_COUNT_SHARD | video_id, shard | Sharded counters for hot videos (Deep Dive 8) |
| WATCH_PROGRESS | user_id, clustered by video_id | High write rate, last write wins; Cassandra or DynamoDB |
| Objects | /{videoId}/{rendition}/{seq}.m4s | Immutable segment keys allow long CDN cache lifetimes |
The segment table is drawn for clarity, but in practice the manifest files are the index of segments. The database stores pointers to manifests, and the player discovers segments from them. See Choosing a Database: A Decision Guide and Data Modeling.
Deep Dives#
1. The processing pipeline: a parallel transcoding DAG#
To support adaptive bitrate streaming, every upload must be turned into segments in several renditions plus manifests. The pipeline's outputs are:
- Segment files for every rendition (codec, container, resolution, bitrate), in object storage.
- Manifests: one primary manifest per protocol and one media manifest per rendition, pointing at the segment files.
- Side outputs: audio tracks, thumbnails and preview sprites, automatic captions, content-safety and copyright signals.
Basic: one worker transcodes the whole file
A worker downloads the original and runs ffmpeg once per rendition, sequentially. A 1-hour 1080p video with a five-rendition ladder takes hours on one machine. A long 4K video can take most of a day. A crash near the end loses all the work. And upload bursts (say, a big event when thousands of creators upload at once) form a long queue because each job holds a machine for hours.
Better: one task per rendition
Fan out one task per rendition onto a queue so five machines each produce one rendition in parallel. This is faster, but each task still processes the whole video serially, the slowest rendition (1080p or 4K) sets the completion time, and a failure still repeats an hour of work.
Best: split into chunks, transcode chunks in parallel, assemble
Treat processing as a directed acyclic graph (DAG) of small tasks:
- Probe and validate. Read the container and stream info (
ffprobe): duration, codecs, resolution, frame rate, rotation, audio channels. Reject corrupt or unsupported files early, and decide the ladder (do not create a 1080p rendition from a 480p source). - Split the original into chunks at keyframes. Each chunk must be independently decodable, so splits happen on closed GOP boundaries (a GOP, group of pictures, is a keyframe plus the frames that depend on it; "closed" means no frame refers to a frame outside the group). If the source has sparse keyframes, the splitter either decodes and re-encodes around split points or chooses split points at scene cuts.
- Transcode each chunk to each rendition in parallel. A 1-hour video split into 120 chunks of 30 seconds, times 5 renditions, is 600 independent tasks. With enough workers, the wall-clock time is roughly the time to encode one chunk plus overhead: minutes rather than hours.
- Audio, captions, thumbnails and safety checks run in parallel with video transcoding, because they depend only on the original.
- Package: cut the encoded streams into 2- to 6-second segments aligned across renditions (so the player can switch at any boundary), mux into fMP4 (CMAF) or MPEG-TS, and apply encryption for DRM content.
- Manifests: write the primary and media manifests for HLS and DASH.
- Publish: update the metadata record to
readywith manifest locations, and notify the creator (and subscribers, if configured).
The graph has one-way dependencies with fan-out (split into chunks, chunks into renditions) and fan-in (packaging waits for all chunks), which is exactly what a DAG is. Each node is idempotent: it reads inputs from object storage and writes outputs to deterministic keys, so a retried task simply overwrites its own output.
Orchestration. Something must build the graph for each video, dispatch ready tasks, track completion, retry failures with backoff, and time out stuck workers. A durable workflow engine such as Temporal fits well: the workflow code expresses the DAG ("for each chunk, start these activities; wait for all; then package"), and Temporal persists the state, so an orchestrator crash does not lose progress. Alternatives are AWS Step Functions, Apache Airflow-style schedulers (better for batch than per-upload work), or a custom DAG executor over a task queue. See Pattern: Multi-Step Processes and Workflows and Pattern: Managing Long-Running Tasks.
Pass references, not bytes. Workers exchange URLs of intermediate files in object storage, never the files themselves through the orchestrator or a queue. Temporary chunks get a lifecycle rule that deletes them after a day or two.
Chunking has costs. Every chunk boundary forces a keyframe and resets the encoder's rate control, so many short chunks slightly worsen compression and quality. Short chunks also multiply task overhead. Chunks of tens of seconds are a common compromise, and some systems use two-pass approaches: a fast analysis pass over the whole video to set per-chunk bitrate targets, then parallel encoding.
Hardware. Software encoding on CPUs is flexible but expensive at YouTube scale. Google described its custom video coding unit (VCU), code-named Argos, in "Warehouse-Scale Video Acceleration: Co-design and Deployment in the Wild" (Ranganathan et al., ASPLOS 2021): dedicated chips that encode H.264 and VP9 far more efficiently per watt than CPUs, deployed across its data centres. GPUs (NVIDIA NVENC) are another option for fast encoding, typically with somewhat lower compression efficiency than the best software encoders at slow presets.
Priorities and fairness. Separate queues for short videos, long videos and re-encodes, so a creator's 30-second clip is not stuck behind a backlog of 4-hour livestream archives. A cheap, fast rendition (for example 360p and 720p H.264) is produced first so the video becomes watchable quickly; the full ladder and expensive codecs follow.
Pipelining with upload. The design above waits until the upload is complete. A faster variant has the client split the video, or the server split as parts arrive, so transcoding starts while the rest is still uploading. This speeds up time-to-publish noticeably for long videos, at the cost of complexity and wasted work for uploads that are abandoned (their partial segments must be garbage-collected).
Scaling the fleet. Autoscale workers on queue depth and oldest task age. Transcoding is stateless, retryable and tolerant of delay, so it is ideal for spot or preemptible instances at a large discount; a reclaimed worker's task is retried elsewhere.
2. Encoding ladders, codecs and per-title optimisation#
The encoding ladder is the list of renditions we produce. A typical fixed ladder for H.264:
| Rendition | Resolution | Video bitrate | Who uses it |
|---|---|---|---|
| 240p | 426 × 240 | 0.3 Mbps | Very poor mobile networks |
| 360p | 640 × 360 | 0.7 Mbps | Mobile on 3G or congested 4G |
| 480p | 854 × 480 | 1.2 Mbps | Small phones, weak Wi-Fi |
| 720p | 1280 × 720 | 2.5 Mbps | Phones, tablets, laptops |
| 1080p | 1920 × 1080 | 4.5 Mbps | Laptops, TVs |
| 2160p (4K) | 3840 × 2160 | 15+ Mbps | 4K TVs on fast connections |
Basic: one fixed ladder for every video
Simple and predictable. But content varies enormously. A static slide presentation looks perfect at 1080p and 1 Mbps; a confetti-filled sports scene needs 8 Mbps or more for the same perceived quality. A fixed ladder wastes bandwidth on easy content and looks blocky on hard content.
Better: per-title encoding
Netflix described per-title encode optimisation in 2015: for each title, encode test versions at many resolution and bitrate combinations, measure quality, and pick the ladder that gives the best quality for each bitrate. Plotted as quality against bitrate, each resolution produces a curve; the convex hull of those curves shows, at every bitrate, which resolution looks best. An animated film might get 1080p at 1.5 Mbps; an action film might need much more. The ladder is chosen from points on the hull.
Measuring quality needs a metric that correlates with human perception. Netflix's VMAF (Video Multimethod Assessment Fusion, published in 2016) combines several elementary metrics with a machine-learned model trained on human ratings; it is now widely used across the industry. Simpler metrics such as PSNR and SSIM are cheaper but match perception less well.
Best: per-shot optimisation and popularity-aware codecs
- Per-shot or per-scene encoding. Netflix later described a "dynamic optimizer" (2018) that splits a title into shots and chooses encoding parameters per shot, which pairs naturally with chunked parallel encoding (Deep Dive 1).
- Codec by popularity. Encoding cost is paid once; bandwidth savings are paid on every view. So spend more compute on videos that will be watched a lot. A common policy: every upload gets a fast H.264 ladder; videos crossing a view threshold get VP9 or AV1 renditions; the most popular get slow, high-effort encodes. At 100 views, AV1's 30% bandwidth saving is worth nothing compared with its encoding cost; at 10 million views it is worth a lot.
break-even for an expensive codec, one 10-minute video:
extra encode cost: e.g. 20 extra core-hours x $0.02 = $0.40
saving per view: 30% of ~112 MB = ~34 MB; at $0.005 per GB => ~$0.00017
break-even ~ 0.40 / 0.00017 ~ 2,400 viewsThe numbers are illustrative (real CDN costs per GB and encoder speeds vary widely), but the shape of the argument is what interviewers want: encode effort should scale with expected views.
Device support decides what to encode. H.264 decodes in hardware on essentially every device. VP9 and AV1 hardware decoders are common on newer phones, TVs and browsers but not universal; HEVC is common on Apple devices and TVs. Software decoding of AV1 on an old phone drains the battery. So the player tells the server (or the manifest offers) what the device supports, and the player picks only renditions it can decode in hardware.
Audio. Audio is encoded separately (AAC at 64-192 kbps is near universal; Opus for WebM; Dolby Digital Plus or Atmos for premium TV content) and delivered as its own track, so players can pick the language and quality independently from video. Separate audio tracks also avoid duplicating audio inside every video rendition.
3. Adaptive bitrate streaming in depth: HLS, DASH and the player#
Adaptive streaming runs over plain HTTP, which is why it scales: segments are ordinary static files that any HTTP cache or CDN can serve. See HTTP, HTTP/2, HTTP/3 and HTTPS.
The two protocols.
- HLS (HTTP Live Streaming), created by Apple, documented as RFC 8216 (Pantos and May, 2017). Manifests are
.m3u8text playlists. Required for native playback on Apple devices. - MPEG-DASH (Dynamic Adaptive Streaming over HTTP), an international standard, ISO/IEC 23009-1 (first edition 2012). Manifests are XML MPD (Media Presentation Description) files. Codec-agnostic and widely used on Android, smart TVs and the web (via Media Source Extensions in browsers).
- CMAF (Common Media Application Format, ISO/IEC 23000-19, 2018) defines a common fragmented-MP4 segment format usable by both. With CMAF, we store one set of segments and write both HLS and DASH manifests pointing to them, instead of storing everything twice (once as MPEG-TS for HLS and once as fMP4 for DASH).
A minimal HLS primary playlist and one media playlist:
#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360,CODECS="avc1.4d401e,mp4a.40.2"
360p/playlist.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=2800000,RESOLUTION=1280x720,CODECS="avc1.4d401f,mp4a.40.2"
720p/playlist.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080,CODECS="avc1.640028,mp4a.40.2"
1080p/playlist.m3u8
--- 720p/playlist.m3u8 ---
#EXTM3U
#EXT-X-VERSION:7
#EXT-X-TARGETDURATION:4
#EXT-X-MAP:URI="init.mp4"
#EXTINF:4.000,
seg_00001.m4s
#EXTINF:4.000,
seg_00002.m4s
#EXT-X-ENDLISTThe #EXT-X-ENDLIST tag marks a finished VOD playlist; live playlists omit it and keep growing (Deep Dive 9). The init.mp4 initialisation segment holds codec configuration shared by all media segments.
Segment duration trade-offs.
- Short segments (2 s): faster startup and quicker reaction to bandwidth changes, lower live latency. But more requests, more manifest entries, more keyframes (each keyframe costs bits, so compression is slightly worse), and more per-request overhead at the CDN.
- Long segments (6-10 s): better compression and fewer requests, but slower adaptation and startup. Apple's HLS authoring guidance moved to recommending 6-second segments; many services use 2 to 6 seconds.
How the player chooses a bitrate. This is a control problem: choose the highest quality that will not stall, while avoiding frequent switches (which viewers notice). The research literature is rich:
- Throughput-based: estimate bandwidth from recent segment downloads (for example a harmonic mean of the last few, which is robust to spikes) and choose the highest rendition below, say, 80% of the estimate. Simple, but throughput estimates are noisy, especially on mobile.
- Buffer-based: Huang, Johari, McKeown, Trunnell and Watson, "A Buffer-Based Approach to Rate Adaptation: Evidence from a Large Video Streaming Service" (SIGCOMM 2014), tested at Netflix, showed that choosing bitrate mainly from buffer occupancy reduces rebuffering. With a nearly empty buffer, pick the lowest rate; as the buffer fills, step up; with a full buffer, use the highest the network sustains. Estimating throughput matters mostly at startup, when the buffer is empty.
- Control-theoretic: model predictive control (Yin, Jindal, Sekar and Sinopoli, SIGCOMM 2015) optimises a quality-of-experience objective over the next few segments using a throughput forecast.
- Lyapunov optimisation: BOLA (Spiteri, Urgaonkar and Sitaraman, INFOCOM 2016) gives a buffer-based algorithm with provable near-optimality; it is implemented in the open-source dash.js reference player.
- Learned: Pensieve (Mao, Netravali and Alizadeh, SIGCOMM 2017) trained a neural network policy with reinforcement learning.
The objective these algorithms optimise is roughly: maximise average bitrate (quality), minus a heavy penalty for rebuffering time, minus a smaller penalty for quality switches, with startup delay as a separate cost. Rebuffering is by far the most hated event, so good players are conservative.
Startup. To start fast, players often begin at a moderate rendition (or the last bitrate this device sustained), fetch the first segment immediately, and need only a few seconds of buffer to start. The service can help by including the first segment's URL or a bandwidth hint in the metadata response, and by making sure the first segments of popular videos are hot in the CDN.
Open-source players such as hls.js, dash.js, Shaka Player (Google) and ExoPlayer/Media3 (Android) implement these algorithms; large services typically run their own tuned versions.
4. Resumable uploads for multi-gigabyte files#
A 20 GB upload over a home connection at 20 Mbps upstream takes over 2 hours. Laptops sleep, Wi-Fi drops, phones switch networks. Without resumability, any interruption restarts from zero, and some uploads would never finish.
The approach:
- Chunk on the client. Split the file into parts of 5 to 16 MB (S3 multipart requires each part except the last to be at least 5 MB, and allows at most 10,000 parts, so a 100 GB file needs parts of at least 10 MB). Compute a fingerprint (for example SHA-256) per part.
- Register the upload.
POST /v1/videoscreates the video record and a multipart upload in object storage, and returns theuploadId, part size and presigned URLs. The metadata holds apartslist, each with fingerprint and statusNotUploaded. - Upload parts directly to object storage, several in parallel. For each part, object storage returns an ETag (an identifier derived from the part's content).
- Record progress. The client reports each finished part with its ETag (
POST /v1/videos/{id}/parts). The server can verify the part exists and matches (S3'sListPartsreturns the parts it has with their ETags and sizes), then marks itUploaded. Do not trust the client blindly: the server-sideListPartsis the source of truth. - Resume. After an interruption, the client calls
GET /v1/videos/{id}/upload(or the server callsListParts), sees which parts are done, and uploads only the missing ones. Expired presigned URLs are refreshed on request. - Complete. The client calls
upload:complete; the server callsCompleteMultipartUploadwith the ordered list of part numbers and ETags. Object storage assembles the final object and emits a single object-created notification, which starts the processing workflow.
Chunk-level progress tracking is driven by the client and server together; object storage only reports the final object event, not per-part events. That is why step 4 exists.
Why not the server's own byte-range protocol? Some services implement resumable upload themselves: Google's resumable upload protocol (used by the YouTube Data API) lets a client query the last byte received and continue from there, and the open tus protocol standardises the same idea over HTTP for any server. These are good choices when uploads go to your own ingest servers rather than straight to a cloud object store. With S3 or GCS, multipart upload with presigned URLs is the simplest option.
Cleanup. Abandoned multipart uploads keep their parts (and their storage cost) until aborted. Add a bucket lifecycle rule to abort incomplete multipart uploads after, say, 7 days, and a sweeper that deletes video records stuck in uploading for longer.
Integrity. Check per-part checksums (S3 supports CRC32C or SHA-256 checksums per part) and the whole-file hash after completion. A corrupted original poisons every rendition.
Deduplication of uploads. If many users upload the identical file (a viral clip re-uploaded thousands of times), a whole-file hash lets us detect it, reference the existing original and skip transcoding. Near-identical re-uploads (re-encoded, cropped) need perceptual fingerprints, which is also how copyright matching systems such as YouTube's Content ID (launched in 2007) find reused material.
Upload acceleration. For creators far from the storage region, routing uploads through nearby edge points of presence (S3 Transfer Acceleration, or a CDN's upload path) uses the provider's backbone for the long haul, which can be much faster than the public internet for intercontinental uploads.
The Pattern: Handling Large Files and Blobs page covers presigned URLs, multipart uploads and their security in general; the file sync case study goes deeper on chunk-level dedupe.
5. Delivering video: CDN caching at terabits per second#
With roughly 1 Tbps average and 3 Tbps peak egress, serving video from one region's object storage is impossible on cost and latency grounds. A viewer in Mumbai fetching 4-second segments from Virginia pays a 200 ms round trip on every request, and the cross-ocean bandwidth bill would be enormous. Video delivery is a CDN problem. See Content Delivery Networks (CDN).
Segments are perfect cache objects. They are immutable (a given URL always has the same bytes), mid-sized (hundreds of KB to a few MB) and requested by many viewers of the same video. Serve them with Cache-Control: public, max-age=31536000, immutable. Media manifests for finished VOD are also immutable; the primary manifest may change (a new codec added later) and gets a shorter TTL, or a versioned URL.
A cache hierarchy.
- Edge: hundreds of locations close to viewers; small per-site storage, so it holds what is popular locally right now.
- Mid-tier (origin shield): a few large regional caches. Edge misses go here rather than to the origin, which collapses many edge misses into one origin fetch and protects object storage.
- Origin: object storage. Ideally it sees only a small fraction of requests.
- Request collapsing: when many viewers request the same uncached segment at the same moment (a video just went viral), the cache sends one request upstream and serves all waiting clients from that response. Without this, a new viral video stampedes the origin. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
The long tail. Video popularity is heavily skewed: a small fraction of videos gets most views, and a huge number of videos are watched rarely. Edge caches hold the popular head with very high hit rates; the tail misses at the edge and is served from mid-tier caches or the origin. Overall byte hit rates above 90% are typical for large video CDNs, and every percentage point matters: at 3 Tbps, a 1% hit-rate drop sends 30 Gbps more to the origin.
Caches inside ISPs. The largest services place their own cache servers inside internet service providers' networks, free to the ISP, because it cuts the ISP's transit traffic and gives viewers the shortest path:
- Netflix Open Connect (launched in 2012) places Open Connect Appliances, storage-dense servers, in ISPs and internet exchange points. Netflix's catalogue is relatively small and predictable, so it proactively fills these appliances during off-peak hours with the content it predicts each region will watch the next day. Most Netflix traffic is served from these appliances.
- Google Global Cache places Google cache nodes in ISPs to serve YouTube and other Google content.
Proactive fill works for Netflix because its catalogue is curated and demand is predictable. YouTube's catalogue is vast and new uploads go viral without warning, so it relies more on reactive caching with a deep hierarchy, plus pre-warming for predictable events (a big premiere, a major creator's scheduled release).
Routing viewers to a cache. DNS-based steering (the CDN's DNS returns the IP of a nearby, healthy edge, see DNS: The Domain Name System), anycast IP addresses (the network routes to the nearest site announcing the address), or, as Netflix does, the playback API returns explicit URLs for the best cache servers for this client, chosen from the client's network location and cache health.
Multi-CDN. Many services use several commercial CDNs (and their own) and steer traffic by real-time measurements of performance and cost per region. If one CDN has an outage or performs badly in a country, the player or the steering service shifts traffic to another. Players can also fail over: if a segment request fails, retry it from an alternate CDN listed in the manifest or metadata.
Cache keys. The key should be the path (/v_9f2c/720p/seg_00042.m4s), not including per-user query parameters, or each viewer gets a separate cache entry. When access control needs per-user tokens (Deep Dive 10), the CDN validates the token and strips it from the cache key.
Thumbnails and metadata. Thumbnails are small, extremely popular images, also served from the CDN. Even metadata API responses for very popular public videos can be cached at the edge for a few seconds, which absorbs spikes when a link is shared widely.
Transport at the edge. Most viewers are on mobile or Wi-Fi networks with loss and variable latency. HTTP/2 lets a player multiplex manifest, segment and caption requests over one connection; HTTP/3 over QUIC goes further by avoiding head-of-line blocking at the transport layer and resuming connections quickly after a network change, such as walking from Wi-Fi onto cellular. Large video services have reported fewer rebuffers after adopting QUIC, which is why players and CDNs enable it where supported. TLS is terminated at the edge, so the cost of encrypting terabits per second is spread across thousands of edge servers, often with kernel or hardware TLS offload to keep CPU usage manageable. Edge servers also use TCP congestion control tuned for video (for example BBR, which Google deployed for YouTube traffic) to sustain throughput on lossy paths.
6. Scaling metadata and hot videos#
With the CDN serving the bytes, our own backend sees mostly metadata traffic: about 12,000 reads per second on average and 50,000 at peak. That is moderate, but the distribution is extremely skewed. When a video goes viral, millions of people open its page within minutes.
Component by component:
- Video service: stateless, behind a load balancer, autoscaled on CPU and request rate. See Load Balancing.
- Metadata DB (Cassandra): scales horizontally through its consistent-hashing ring and leaderless replication;
videoIdspreads data uniformly. The weakness is a hot partition: every read of a viral video hits the same three replicas. See Consistent Hashing. - Processing service: internal task queues absorb upload bursts; worker count scales on queue depth.
- Object storage: scales to enormous request rates, but a bucket lives in one region (replicated across availability zones). Viewers far away need the CDN, and disaster recovery needs cross-region replication of originals.
Basic: read the database every time
Every page view reads Cassandra. A viral video at 50,000 reads per second lands on a single partition; even with three replicas and reads at consistency level ONE, each replica handles about 17,000 reads per second for one key, which is near the practical limit of a node and harms every other key on those nodes.
Better: a metadata cache
Put a distributed cache (Redis or Memcached) in front, partitioned by videoId, with LRU eviction and a TTL (say 5 minutes). Popular videos are almost always cache hits. Invalidate or update the cache entry when the metadata changes (title edit, status change), or accept up to one TTL of staleness for non-critical fields. See Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.
The cache itself can develop a hot key: one Redis shard serving 50,000 reads per second for one key is fine (Redis handles around 100,000 simple operations per second), but at higher rates or with large values it saturates the shard's network.
Best: layered caching with hot-key protection
- In-process caches on each video service instance for the hottest few thousand videos, with a short TTL (a few seconds). This spreads a hot key across every instance.
- Hot-key replication in the distributed cache: store
video:v_9f2c#1through#8copies and read a random one when a key is detected as hot. - Edge caching of public metadata for a few seconds, so a spike is absorbed before it reaches our data centres.
- Request coalescing in the service: concurrent misses for the same key wait on one backend fetch (a "single flight").
- Increase replication for hot partitions in the DB, or serve reads from more replicas, though with good caching the DB rarely sees hot-key load.
Separate fast-changing fields. The view count changes constantly, the title rarely. Store and cache them separately: the metadata object is cached for minutes, the view count is fetched from the counter store (Deep Dive 8) or embedded at a coarser granularity. Otherwise every view-count update would invalidate the metadata cache.
Multi-region metadata. For a global service, replicate metadata to several regions (Cassandra's multi-datacentre replication, or DynamoDB global tables) so reads are local. Writes (uploads, edits) are rare and can go to the creator's home region, with asynchronous replication, which fits our availability-over-consistency requirement. See Multi-Region and Global Data.
7. Metadata and search#
Users find videos by searching titles, descriptions, tags, channel names, and increasingly the words spoken in the video.
What goes into the index. For each video: title, description, tags, channel name, language, duration, upload date, category, and the transcript from automatic speech recognition (ASR), produced in the processing DAG. Popularity signals (views, recent view velocity, likes, watch time) and quality signals are added as fields for ranking.
Keeping the index in sync.
- Basic: dual writes. The video service writes the DB and the index. If one write fails, they diverge, and nothing repairs it.
- Better: change data capture (CDC). The metadata DB's change stream (Cassandra CDC, DynamoDB Streams, or the MySQL binlog via Debezium) feeds Kafka; an indexer consumes it and updates Elasticsearch. The index is eventually consistent, typically within seconds, and can be rebuilt by replaying from the DB. See Change Data Capture and the Outbox Pattern.
- Best: CDC plus periodic signal updates. Text fields change rarely and flow through CDC. Popularity signals change constantly; updating every document on every view would overwhelm the index. Instead, a batch or streaming job pushes popularity scores every few minutes or hours, using partial updates, or keeps them in a separate fast lookup used at ranking time.
The search service. Elasticsearch (or OpenSearch, or a custom inverted index at very large scale) sharded by videoId, with replicas to scale reads. A query runs in two phases: retrieve candidates by text relevance (BM25 over title, description and transcript, with title boosted), then rank by a combination of relevance, popularity, freshness, and personalisation, often with a learned ranking model over the top few hundred candidates. See Elasticsearch and Search Systems.
Multilingual and fuzzy search. Use language-specific analysers (stemming, stop words, tokenisation for languages without spaces), and fuzzy matching or spelling correction for typos. Autocomplete suggestions come from a separate prefix index of popular queries; the search autocomplete case study covers it.
Visibility filters. Private, unlisted, region-blocked, age-restricted and removed videos must never appear in results for users who cannot see them. Store visibility fields in the index and filter on every query; when a video is taken down, the CDC update must reach the index within seconds, and the video service checks visibility again before returning a playable manifest URL.
Caching search. Popular queries ("music", a trending event) repeat heavily. Cache result pages for a minute or two keyed by normalised query, language and region. Personalised ranking reduces the cacheability of the final page, so cache the candidate set and personalise on top.
Search at scale is its own system. The post search case study goes much deeper into inverted-index sharding, ingestion and freshness; here, the key interview point is that search is fed asynchronously from the metadata DB, not written in the upload path.
8. Counting views#
View counts look trivial ("increment a counter") but combine four hard problems: high write rates, extreme hot keys (one viral video), fraud (bots inflating counts for money), and definitional questions (what is a view?).
What counts as a view? Platforms define a minimum amount of watching before a play counts, and exclude repeated plays and automated traffic; exact rules are not public and change over time. YouTube was long known for freezing public counts at around 300 while it verified a fast-growing video's views, a behaviour it later replaced with faster verification. The design lesson: the displayed count is the output of a validation pipeline, not a raw increment.
The event stream. The player sends:
- a start event when playback begins,
- heartbeats every 30 seconds or so with the current position (also used for watch time and resume),
- an end event when the viewer leaves.
Events go to a lightweight event collector (stateless, horizontally scaled), which validates the signature and session, then writes to Kafka partitioned by videoId. At about 33,000 events per second at peak, this is modest for Kafka. See Apache Kafka in Practice.
Basic: increment a database row per view
UPDATE videos SET views = views + 1 (or a Cassandra counter) on every view. A viral video at thousands of views per second creates a single hot row, causing lock contention in a relational DB or a hot partition in Cassandra. Cassandra counters are also not idempotent: a retried increment counts twice.
Better: Redis counters
INCR views:{videoId} in Redis, flushed to the database periodically. Redis handles around 100,000 increments per second per shard, so even one hot key is fine at our scale. Retries still double-count, and losing a Redis node loses recent increments unless persistence is configured.
Best: stream aggregation with deduplication
A stream processor (Apache Flink or Kafka Streams) consumes view events:
- Deduplicate by session id: a session counts at most once per video within a window, regardless of how many heartbeats or retries arrive. Flink keeps per-session state with a TTL.
- Apply view rules: minimum watch duration, known bot user agents and IPs, rate-of-views-per-account limits, anomaly scores.
- Aggregate per video in short windows (say 5 seconds) and emit one delta per video per window:
+1,342. Windowed aggregation turns 33,000 events per second into a few thousand writes, and a viral video becomes one write every 5 seconds instead of thousands per second. - Write deltas to the counter store with an idempotent key (
videoId, window id), so replays after a failure do not double-count.
Flink's checkpoints plus idempotent or transactional sinks give effectively exactly-once counts. See Apache Flink and Stream Processing and Delivery Guarantees: At-Most, At-Least and Exactly-Once.
Sharded counters for extremely hot videos. If a single counter key is still too hot (a huge live premiere), split it into N shards (views:{videoId}:{0..N-1}), write to a random shard, and sum the shards on read (cached for a second or two). See Pattern: Scaling Writes.
Exact or approximate? Total views are summed exactly from deduplicated deltas; that is cheap. Unique viewers per video per day is a distinct-count problem; exact sets of user ids per video would be huge, so use HyperLogLog (about 12 KB per counter for roughly 0.8% standard error in Redis's implementation). See Probabilistic Data Structures for Big Data.
Corrections. All raw events also land in a data lake. Nightly batch jobs recompute counts with better fraud models and emit corrections, so the public count can go down when fake views are removed. This is the classic lambda shape: fast approximate path plus slow accurate path. See Batch vs Stream Processing.
Watch time and creator analytics. The same heartbeat stream powers metrics that matter more than raw views: total watch time, average view duration, audience retention curves (what fraction of viewers is still watching at each second), traffic sources and geography. Retention curves come from aggregating heartbeat positions into per-second or per-percent buckets per video, a batch or streaming job writing into an analytics store (a columnar OLAP database such as ClickHouse, Apache Druid or BigQuery) that creator dashboards query. These analytics can lag by minutes or hours without harm, so they belong on the asynchronous path, never in the playback path.
Trending and top-K lists (most-viewed videos in the last hour or day) are computed from the same stream; the top-K case study covers windowed heavy-hitter counting with count-min sketches.
9. How live streaming differs#
Video on demand gives us time: we can transcode for minutes, use slow high-quality encoders, and cache immutable files forever. Live removes that time. Every step must keep up with real time, and viewers want low glass-to-glass latency (from camera to screen).
What changes, step by step:
- Ingest. Broadcasters push a continuous stream, typically over RTMP (old but universal in streaming software), SRT (Secure Reliable Transport, UDP-based, better over lossy networks), or WebRTC (via the WHIP ingest protocol standardised by the IETF) for low latency. Ingest servers sit in many regions near broadcasters, and a stream is pinned to one ingest server for its lifetime (with a backup ingest for important streams).
- Transcoding. No chunk-parallel DAG: the transcoder must encode in real time, producing the whole ladder for one stream as it arrives, usually on one machine (or GPU) per stream. Fast encoder presets trade compression efficiency for speed. Some platforms only transcode popular streams and pass small streams through at the source quality.
- Packaging and manifests. Segments are produced every few seconds and the media playlist keeps growing: no
ENDLIST, a sliding window of recent segments, and the player re-fetches the playlist every segment duration to learn about new segments. - Caching. Segments are still immutable and cacheable, but playlists change every few seconds and must have TTLs of about one segment duration or less. Every viewer polls the playlist, so a stream with a million viewers creates a burst of playlist requests every few seconds: request collapsing at the CDN shield is essential, or the live origin melts.
- Latency budget. Standard HLS with 6-second segments and a 3-segment buffer gives 20 to 30 seconds of latency. Low-Latency HLS (introduced by Apple in 2019) publishes partial segments of a few hundred milliseconds and lets players request upcoming parts in advance (blocking playlist reload), reaching 2 to 5 seconds. Low-latency DASH uses CMAF chunks delivered with HTTP chunked transfer encoding for similar results. Sub-second latency needs WebRTC delivery, which does not use HTTP caching and needs a different, more expensive fan-out architecture of media servers (see the video conferencing case study).
- Failure handling. A VOD failure means a retry; a live failure means viewers see a frozen stream. Use redundant ingest, hot-standby transcoders, and players that tolerate a missing segment by skipping ahead.
- Live to VOD. The stream is recorded during the broadcast. When it ends, the recording goes through the normal VOD pipeline to produce high-quality renditions; meanwhile, a DVR window lets viewers rewind within the live stream.
- Interaction. Live chat and reactions need realtime fan-out to every viewer of a stream, synchronised roughly with the video delay. That is the live comments case study's problem: pub/sub partitioned by stream, SSE or WebSockets to viewers, and special handling for streams with millions of viewers. See Pattern: Pushing Realtime Updates.
Facebook described similar issues when scaling Facebook Live in 2015-2016: a popular live stream creates a thundering herd of requests for the newest segment the moment it appears, which they addressed with request coalescing in the edge and origin cache layers. The general lesson is that live turns a storage and caching problem into a real-time fan-out problem.
10. Access control, signed URLs and DRM#
Public YouTube videos are open to anyone, but private and unlisted videos, paid content, region-restricted content and studio films need protection. There are three levels.
Basic: obscure URLs
Unlisted videos use unguessable ids (v_9f2c is short for the example; real ids carry enough randomness that guessing is infeasible). This prevents discovery, not sharing: anyone with the link can watch, which is exactly what "unlisted" means. It is not access control.
Better: signed URLs or signed cookies at the CDN
When an authorised user opens a private video, the video service returns manifest URLs signed with a short expiry (for example 1-6 hours) and optionally bound to the user or IP. The CDN verifies the signature at the edge (CloudFront signed URLs and signed cookies, Akamai and Fastly token authentication) without calling our backend. Since a manifest references hundreds of segments, signed cookies or a token in the path prefix avoid signing every segment URL individually. The CDN strips the token from the cache key so all authorised viewers share cached segments. See Authentication and Authorization.
Signed URLs stop casual sharing and hotlinking, but an authorised viewer can still download the segments and reassemble the video.
Best for premium content: DRM
Digital rights management encrypts the content so that only licensed, trusted players can decrypt and display it.
- During packaging, segments are encrypted with AES-128 using content keys, following Common Encryption (CENC, ISO/IEC 23001-7), so one set of encrypted CMAF segments works with several DRM systems.
- The three dominant DRM systems are Widevine (Google: Chrome, Android, many TVs), FairPlay (Apple: Safari, iOS, tvOS) and PlayReady (Microsoft: Edge, Windows, many TVs and set-top boxes).
- The player gets a licence from a licence server, after the service checks the user's entitlement. The licence carries the content key, wrapped so only the device's trusted DRM module (often in hardware, a trusted execution environment) can use it, with policies such as expiry, allowed output resolution and offline playback permission.
- Security levels matter: studios typically require hardware-backed DRM (for example Widevine L1) for HD and 4K; software-only clients may be limited to SD.
DRM adds a licence-server dependency to the start of playback (an extra round trip and a critical service that must be highly available) and complexity in packaging, but it is mandatory for studio content. User-generated platforms usually skip DRM for ordinary videos.
Geo-restrictions and policy. Licensing often varies by country. The video service checks the viewer's region (from IP geolocation, account country) before returning playable URLs, and the CDN can enforce geo-blocking too. Takedowns (copyright claims, policy violations) flip the video's status and must propagate to caches: delete or purge the manifests from the CDN and refuse new signed URLs; segments already cached become unreachable without a manifest.
Protecting uploads. Presigned upload URLs are scoped to one object key and a short expiry, with a maximum size and content type where the storage supports policy conditions. Uploaded files are treated as untrusted input: parsing a malicious video file in ffmpeg is a known attack surface, so transcode workers run sandboxed, with no access to anything but their inputs and outputs. See Security Fundamentals for System Design.
11. Storage: tiering, durability and cost#
Storage grows by hundreds of petabytes per year, and most of it is the long tail: videos rarely watched after their first week.
Durability first. Originals are irreplaceable. Object storage gives very high durability within a region (S3 is designed for 99.999999999%, eleven nines, through replication or erasure coding across availability zones). For disaster recovery, replicate originals to a second region, or at least to a cold archive. Renditions can always be regenerated from originals, so they need less protection. See Disaster Recovery and Backups.
Tiering by popularity.
- Hot: new and popular videos' renditions in standard storage, also cached in the CDN.
- Warm: older videos in infrequent-access tiers (cheaper per GB, more expensive per read).
- Cold: originals of old videos, and renditions of almost-never-watched videos, in archival tiers (Glacier-class storage costs a small fraction of standard storage, with retrieval delays from milliseconds to hours depending on the class).
Lifecycle rules move objects automatically based on age; better, a job uses actual view statistics to decide. See Data Lifecycle, Tiering and Retention.
Store fewer renditions for the long tail. For a video watched 10 times a year, storing six renditions in two codecs is wasteful. Options:
- Prune: keep the original plus two or three renditions; regenerate others if the video becomes popular again.
- Just-in-time packaging: store one mezzanine format (for example CMAF fMP4 segments) and generate HLS or DASH manifests and containers on request at the edge or origin, caching the result. This avoids storing the same media twice in two packaging formats.
- Just-in-time transcoding for very rare renditions: transcode on first request and cache. Startup latency for that first viewer is worse, so use it only for renditions nobody depends on.
Erasure coding instead of replication. Three-way replication costs 3x the raw size. Erasure coding (for example a 10+4 Reed-Solomon scheme) stores data in 14 fragments, any 10 of which reconstruct it, at 1.4x overhead while tolerating 4 lost fragments. Cloud object stores do this internally; if you build your own storage (as the largest platforms do), it is a key lever. The object storage case study covers the maths.
Cost model for one year at our scale.
new storage: ~550 PB raw renditions + originals per year (before pruning)
pruning long-tail renditions and second codecs: maybe ~40-60% less
storage at a blended ~$5 / TB-month (mix of tiers) for ~300 PB average
=> ~$1.5M per month
egress: ~11 PB / day ~ 330 PB / month
at even $0.005 / GB => ~$1.65M per month, more at list pricesThe numbers are illustrative, but egress and storage are both in the millions per month, which is why codec efficiency (fewer bytes per view), cache hit rate (fewer origin bytes) and tiering (cheaper bytes at rest) drive the economics of a video platform far more than compute does.
Deleting videos. A deleted video must disappear from metadata, search and CDN quickly, and its objects must eventually be deleted from every tier and replica (privacy laws may set deadlines). Use a tombstone in metadata, a CDN purge for its manifests, and an asynchronous deletion workflow over its object prefix.
12. The playback experience: resume, startup and quality of experience#
The best backend still feels bad if the player starts slowly, stalls or forgets where you were. Several small systems sit around playback.
Resume where you left off. The player sends its position with heartbeats (every 10-30 seconds) and on pause or exit. Store (userId, videoId) → positionSec, updatedAt in a wide-column or key-value store (Cassandra, DynamoDB), partitioned by userId so "continue watching" for a user is one partition read. Writes are frequent (one per heartbeat per active viewer, tens of thousands per second) and last write wins is acceptable. To reduce load, buffer positions in the client and write only every 30 seconds or on meaningful events, and keep a short-lived copy in Redis for cross-device handoff (start on the phone, continue on the TV). Netflix and YouTube both offer this; it is a natural extension question.
Faster startup. Time to first frame is the most visible metric. Techniques:
- Return manifest URLs (and even the first segment URL) in the metadata response to save a round trip.
- Start at a conservative bitrate and switch up quickly once the buffer allows.
- Use short initial segments or partial segments, and keep the first few seconds of popular videos warm in edge caches.
- Prefetch: when a user hovers on a thumbnail or is likely to play the next video in a feed, fetch its manifest and first segment in advance. Short-video apps do this aggressively (see the TikTok case study).
- Reuse connections (HTTP/2 or HTTP/3 over QUIC), which avoids repeated handshakes on lossy mobile networks. See TCP vs UDP (and QUIC).
Seeking and scrubbing. Seeking means jumping to the segment containing the target time and starting at its keyframe; shorter segments mean finer, faster seeks. Trick-play thumbnails (the preview frames shown while scrubbing the progress bar) come from sprite sheets or I-frame-only playlists generated in the processing DAG.
Captions and audio tracks. Captions are separate WebVTT or TTML files referenced from the manifest, so players can switch language without changing video; the same goes for alternative audio tracks (dubs, audio description).
Offline downloads. Mobile apps let users download videos for offline viewing. The app downloads segments of one rendition and stores them encrypted; with DRM, the licence must allow offline playback and expires after a set period. The backend tracks download counts per account where licensing limits them.
Measuring quality of experience (QoE). Players report telemetry: startup time, rebuffering ratio (stall time ÷ watch time), average bitrate, bitrate switches, errors, and the CDN and server used. Aggregated by region, ISP, device and CDN, this shows where to fix things: a CDN performing badly in one country, a device model with a decoder bug, a rendition ladder missing a rung for a common bandwidth. Studies of large video services have found that viewers abandon slow-starting videos and watch less after rebuffering, which is why QoE is a business metric, not just an engineering one. See Observability: Logs, Metrics and Traces.
Mobile and TV clients. TVs have weak CPUs but good decoders; phones change networks constantly; browsers depend on Media Source Extensions. Client teams tune ABR per platform. See Client, Mobile and Frontend Considerations.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Upload interrupted | Lost progress, frustrated creators | Multipart upload with per-part status; resume via ListParts; refresh expired presigned URLs |
| Upload burst (major event) | Long processing queues, slow publish | Autoscale workers on queue depth; separate queues by size; fast low-ladder first, full ladder later |
| Transcode worker crash or spot reclaim | Lost task progress | Small idempotent chunk tasks; orchestrator retries with backoff; outputs to deterministic keys |
| Corrupt or malicious upload | Pipeline failures, possible exploit | Probe and validate first; sandboxed workers; fail fast with a clear status to the creator |
| Viral video metadata hot key | Hot Cassandra partition and cache shard | In-process caches; hot-key replication; edge caching of public metadata; request coalescing |
| Viral video segments not yet cached | Origin stampede | CDN shield tier with request collapsing; pre-warm for scheduled premieres |
| CDN outage or poor performance in a region | Rebuffering, failed playback | Multi-CDN steering; player failover to alternate CDN URLs; health-based routing |
| Origin region outage | Cache misses fail for long-tail videos | Cross-region replication of renditions or originals; regenerate renditions in another region |
| View-count hot key | Contention, lost or double counts | Windowed stream aggregation; dedupe by session; sharded counters; idempotent deltas |
| Fake views and bots | Inflated counts, fraud | View rules in the stream; anomaly detection; nightly batch recount with corrections |
| Live playlist request storm | Live origin overload, stalls | Short-TTL playlists with request collapsing; LL-HLS blocking reloads; shield tier |
| DRM licence server down | Premium content cannot start | Multi-region licence servers; licence caching per session; graceful error and retry |
What Interviewers Expect#
Mid-level#
- Clear API endpoints and data model, and a working high-level design for upload and playback.
- Understanding that video bytes go directly to object storage (presigned URLs) and are served via a CDN, not through app servers.
- Converging, perhaps with hints, on multipart upload and segment-based streaming.
- Some idea that videos must be transcoded into formats different devices can play.
- Driving at least one deep dive with clarity, even if not exhaustively.
Senior#
- A quick high-level design, then most of the time on upload details and post-processing.
- Resumable uploads with multipart upload: chunk tracking, ETags, completion, resume, and cleanup.
- An efficient processing pipeline: split, parallel transcode, package, manifests; orchestration and retries; a ladder of renditions.
- Adaptive bitrate streaming explained properly: primary and media manifests, segment switching, why HLS and DASH run over HTTP and cache well.
- Scaling: metadata cache, hot videos, CDN for segments, and a sensible view-count design.
Staff+#
- Depth on every topic above, plus the freedom to steer toward what matters most, treating the interviewer as a peer.
- Economics: egress and storage dominate; codec choice by popularity; cache hit rate; tiering and pruning of the long tail; ISP-embedded caches.
- Quality science: per-title or per-shot encoding, VMAF, convex-hull ladders, ABR algorithm trade-offs (throughput versus buffer-based).
- Live versus VOD: what breaks (real-time transcoding, playlist storms, latency budgets, LL-HLS, WebRTC).
- Correctness of counts and safety: deduplicated stream aggregation, fraud corrections, takedown propagation, DRM.
- Clear articulation of trade-offs and of what to build first versus later.
Deep Dive: the numbers behind streaming, worked throughShow
1. Bitrate, size and download time. size = bitrate × duration. A 10-minute 1080p rendition at 4.5 Mbps is 4.5 × 600 / 8 ≈ 340 MB. A 2-hour 4K film at 15 Mbps is 15 × 7,200 / 8 = 13.5 GB. Downloading the 10 GB file from the "bad" playback option over 100 Mbps takes 10 × 8,000 / 100 = 800 s, over 13 minutes, versus playback starting after one 4-second segment of 720p (2.5 × 4 / 8 ≈ 1.25 MB), which arrives in about 0.1 s plus round trips.
2. Buffer dynamics. Let b(t) be seconds of video in the buffer. While downloading rendition r at bitrate R_r over a link of throughput C, each second of wall time adds C / R_r seconds of video and playback drains 1 second:
db/dt = C / R_r - 1
C = 3 Mbps, R = 4.5 Mbps (1080p): db/dt = -0.33 -> a 30 s buffer empties in 90 s
C = 3 Mbps, R = 2.5 Mbps (720p): db/dt = +0.2 -> buffer grows, can try 1080p laterThis is why buffer-based ABR works: the buffer level integrates the mismatch between throughput and bitrate, so it is a smoothed, direct signal of whether the current choice is sustainable. A typical buffer-based map: below 10 s choose the lowest rendition; between 10 s and 60 s map linearly onto the ladder; above 60 s choose the top rendition the device supports.
3. Startup time budget.
DNS + TCP + TLS (or QUIC) ~50-150 ms (less with connection reuse)
metadata API call ~50-100 ms
primary + media manifest ~2 x 20-50 ms from a nearby edge
init segment + first segment ~100-400 ms depending on bitrate and throughput
decoder start, first frame ~50-100 ms
total ~0.4-1 s on a good network; 2-3 s on poor mobileEach removed round trip matters: embedding the manifest URL in the metadata response, preconnecting to the CDN, and starting at a modest bitrate are worth hundreds of milliseconds.
4. Cache hit rate and popularity. If video popularity follows a Zipf-like distribution (the i-th most popular video gets a share proportional to 1 / i^α with α near 1), the fraction of requests to the top k of N videos is about ln k / ln N for α = 1. With N = 1 billion videos:
k = 1 million videos cached: ln(10^6) / ln(10^9) = 6 / 9 ~ 67% of requests
k = 10 million: 7 / 9 ~ 78%
k = 100 million: 8 / 9 ~ 89%Each 10x increase in cache size adds a roughly constant slice of hit rate, which is why multi-tier caches (small, fast edges plus large mid-tiers) are efficient. Real popularity is also strongly time-varying (new uploads spike and decay), so caches with recency-aware eviction do better than this static model suggests. Byte hit rates differ from request hit rates because popular videos are watched longer and at higher bitrates.
5. Parallel transcoding speed-up. A 60-minute video encoded at 0.5x real time per rendition (each minute of video takes 2 minutes of encode time on one machine) for 5 renditions takes 60 × 2 × 5 = 600 machine-minutes. On one machine that is 10 hours. Split into 120 chunks of 30 seconds, each chunk-rendition task takes about 1 minute, so with 600 workers the wall-clock time is about 1 minute plus splitting, packaging and scheduling overhead, perhaps 3 to 5 minutes total. Amdahl's law applies: the serial parts (probe, split, final packaging, manifest writing) bound the speed-up, so they must be fast too.
6. Erasure coding durability, intuitively. With 3x replication, data is lost if all 3 copies fail before repair. With 10+4 erasure coding, data is lost only if 5 of 14 fragments fail before repair. If each fragment independently fails with probability p during one repair window, loss probability is about C(14,5) × p^5 = 2,002 p^5, versus p^3 for replication. With p = 10^-3, replication gives 10^-9 and erasure coding about 2 × 10^-12, at less than half the storage overhead (1.4x versus 3x). Fast repair (small windows) is what makes either scheme reach eleven nines in practice.
7. Live latency budget for standard HLS.
encoder and packager: produce a 6 s segment ~6 s
publish to origin and CDN ~0.5-1 s
player waits for 3 segments in buffer before playing ~18 s
total glass-to-glass ~25 s
LL-HLS with 0.33 s parts and 1 s target buffer ~2-4 sDeep Dive: what a codec actually doesShow
A raw 1080p video at 30 frames per second with 8-bit 4:2:0 colour is 1920 × 1080 × 1.5 bytes × 30 ≈ 93 MB/s, about 750 Mbps. A good H.264 encode of the same video is 4-6 Mbps: a compression ratio of more than 100x. Here is where it comes from.
Spatial redundancy (within a frame). Neighbouring pixels are similar. The encoder splits the frame into blocks (macroblocks of 16 × 16 in H.264; flexible coding tree units up to 64 × 64 in HEVC, 128 × 128 in AV1), predicts each block from already-encoded neighbouring pixels (intra prediction), and encodes only the residual (the difference). The residual is transformed with a DCT-like integer transform, which concentrates energy into a few low-frequency coefficients.
Quantisation, where the loss happens. Transform coefficients are divided by a quantisation step and rounded. High-frequency detail, which the eye notices least, mostly becomes zero. The quantisation parameter (QP) is the main quality knob: a larger QP means coarser steps, fewer bits and lower quality.
Temporal redundancy (between frames). Consecutive frames are mostly the same scene, shifted. Motion estimation searches the previous (or future) frames for the best-matching block and encodes a motion vector plus a small residual instead of the block itself. This is the most expensive part of encoding, and slower presets search harder and find better matches.
Frame types.
- I-frames (intra, keyframes): self-contained, large. Players can start decoding only at an I-frame.
- P-frames: predicted from earlier frames; much smaller.
- B-frames: predicted from earlier and later frames; smallest, but they require reordering so the decoder sees reference frames first.
A GOP (group of pictures) runs from one I-frame to the next. Long GOPs compress better; short GOPs allow faster seeking and switching. For ABR, GOPs must be aligned across renditions and every segment must start with an I-frame, so the player can switch rendition at a segment boundary and decode immediately. That is why the encoder is configured with a fixed keyframe interval (for example every 2 seconds) and scene-cut keyframes are constrained.
Entropy coding. The final step losslessly packs symbols (coefficients, motion vectors, modes) using context-adaptive arithmetic coding (CABAC in H.264 and HEVC) or similar, squeezing out statistical redundancy.
Rate control. The encoder must decide how many bits each frame gets.
- CBR (constant bitrate): steady bitrate, predictable for networks, but wastes bits on easy scenes and starves hard ones.
- VBR (variable bitrate): bits follow content complexity within a cap; often two-pass (analyse the whole video, then encode) for best distribution.
- CRF (constant rate factor, in x264 and x265): targets constant perceived quality; file size varies with content. Common for archival.
- Capped CRF / constrained VBR is the usual choice for streaming: quality-targeted, but with a maximum bitrate and a buffer constraint (VBV) so each segment can be downloaded at the advertised bandwidth.
Why newer codecs are better and slower. HEVC, VP9 and AV1 add bigger and more flexible block partitions, more prediction modes, better motion vector coding and loop filters. Each new tool gives the encoder more choices to evaluate, so encoding time rises sharply even as bitrate falls. Decoding cost rises too, which is why hardware decoder support decides when a codec becomes practical on devices.
Content-adaptive decisions (per-title, per-shot) exploit the fact that the best QP, resolution and bitrate vary by scene. Animation, talking heads and screen recordings compress dramatically better than film grain, water, foliage or confetti.
Deep Dive: how YouTube, Netflix and live platforms actually do itShow
Public engineering talks, papers and blog posts reveal a lot about the real systems. These are the parts that are well documented.
YouTube.
- Scale: YouTube has reported more than 500 hours of video uploaded per minute (2019) and, earlier, over a billion hours watched per day (2017).
- Metadata on MySQL with Vitess. Rather than moving to a NoSQL store, YouTube built Vitess to shard MySQL transparently: a proxy layer routes queries to shards, handles resharding and connection pooling, and protects the databases from bad queries. Vitess was open-sourced and is now a Cloud Native Computing Foundation project used by other large companies. It is a good example of choosing a familiar database and adding a scaling layer.
- Custom transcoding hardware. The Argos video coding unit (Ranganathan et al., ASPLOS 2021) moved much of YouTube's transcoding from CPUs to dedicated accelerators, which the paper reports as many times more efficient. It also enabled encoding more videos in VP9 and higher resolutions, since encoding cost fell.
- Caching at the edge of the internet. Google Global Cache nodes inside ISPs serve popular YouTube content close to viewers.
- Codecs. YouTube was an early, large-scale adopter of VP9 and later AV1, using more efficient codecs for popular content and devices that decode them in hardware.
Netflix.
- Open Connect: Netflix's own CDN, with appliances placed in ISPs and at internet exchange points, filled proactively during off-peak hours based on predicted demand. The control plane (deciding which file goes where, steering clients to appliances) runs in AWS; the data plane (video bytes) runs on Open Connect.
- Encoding research: per-title encoding (2015), VMAF (2016), shot-based dynamic optimisation (2018), and adoption of AV1 for supported devices. Netflix's small catalogue relative to YouTube means it can spend heavily on encoding each title.
- Playback: clients request playback info from a control-plane API in AWS, which returns a manifest with URLs for the best Open Connect servers for that client, plus licence information for DRM.
- Resilience culture: Netflix popularised chaos engineering (Chaos Monkey, which randomly terminates production instances, was described publicly in 2011 and open-sourced in 2012) to make sure the control plane tolerates failures.
- ABR research: the buffer-based rate adaptation paper (SIGCOMM 2014) was evaluated on Netflix traffic.
Facebook Live and other live platforms. Facebook's engineering posts on Facebook Live (2015-2016) described the thundering-herd problem of popular live streams and request coalescing in the edge and origin caches. Twitch and YouTube Live use RTMP-style ingest from broadcaster software such as OBS, real-time transcoding (often only for partners or popular streams), and HLS delivery, with low-latency modes. Interactive live formats (live shopping, auctions, video calls with audiences) increasingly use WebRTC for sub-second latency.
Open-source building blocks. ffmpeg (decoding, filtering, encoding with x264, x265, libvpx, SVT-AV1 and others), Shaka Packager and Bento4 (packaging and encryption), hls.js, dash.js, Shaka Player and ExoPlayer (players), and Video.js (web player UI). A competent interview answer names some of these when talking about how the pipeline is built.
What they share. Direct uploads to object storage; offline, highly parallel transcoding into an encoding ladder; segmented delivery with HLS or DASH; a large CDN with caches as close to viewers as possible; and a thin, highly available control plane that tells clients where to fetch from. The differences come from catalogue shape (long-tail user-generated versus curated), latency needs (VOD versus live) and business model (ads versus subscriptions versus studio licensing).
Deep Dive: failure walkthroughsShow
Every video moves through a status state machine, stored on the video record. Making it explicit is what lets each failure be handled cleanly.
Parts upload and resume within Uploading, failed tasks retry within Processing, and extra codecs are added later without leaving Ready.
A creator uploads a 40 GB, 3-hour 4K video and their laptop sleeps at 70%. The 2,500 parts of 16 MB each are tracked individually. On wake, the client asks for the upload status; the server calls ListParts, sees 1,750 parts present, and returns fresh presigned URLs for the other 750. The upload completes without re-sending 28 GB. If the creator never returns, the lifecycle rule aborts the multipart upload after 7 days and the record moves to Abandoned.
A transcode worker dies mid-chunk. It held one chunk-rendition task (30 seconds of 1080p). The orchestrator's activity timeout or missing heartbeat triggers a retry on another worker; the output key is deterministic, so a partial file from the dead worker is overwritten. The video's completion is delayed by about a minute. If a chunk fails repeatedly (a corrupt region of the source), the orchestrator can retry with a more tolerant decoder setting, then fail the video with a clear error to the creator rather than looping forever.
A video goes viral within minutes of publishing. A link is shared by a celebrity; requests jump from zero to 100,000 per second.
- Metadata: the first requests miss the cache; request coalescing makes the video service fetch from Cassandra once per instance. In-process caches then absorb most reads; hot-key detection replicates the Redis entry.
- Segments: every edge misses at first. The shield tier collapses the misses into one origin request per segment per shield. Within seconds, edges hold the first segments, and the hit rate climbs.
- View counts: Kafka absorbs the event spike; Flink's windowed aggregation turns it into one counter update per few seconds. The public count lags a few seconds behind reality, which nobody notices.
A CDN has a regional outage. Players see segment errors. Their retry logic falls back to an alternate CDN host from the manifest or the playback API, and the steering service shifts new sessions away from the failing CDN for that region. Viewers see a brief stall at worst. Without multi-CDN, the region would be down until the CDN recovers.
The primary object storage region becomes unavailable. CDN caches keep serving popular content, since segments are immutable and long-lived. Long-tail videos miss and fail, unless renditions (or at least originals) are replicated to a second region and the CDN's origin failover points there. Uploads switch to the secondary region's bucket. This is a disaster recovery decision: replicating hundreds of petabytes of renditions is expensive, so many designs replicate originals plus popular renditions and accept degraded long-tail playback during a regional disaster.
A takedown is ordered for a video with 50 million views. The status changes to Removed; the video service stops returning manifest URLs; a CDN purge removes the cached manifests; the search index update from CDC hides it within seconds. Cached segments without a manifest are unreachable for normal players and age out. If the order requires deleting the data, the deletion workflow removes every object under the video's prefix in every tier and region.
Deep Dive: moderation and copyright in the pipelineShow
A user-generated platform cannot publish every upload blindly. Moderation and rights management plug into the processing DAG as parallel branches.
- Perceptual fingerprints for copyright. A rights holder registers reference files. For every upload, the pipeline computes audio and video fingerprints (features robust to re-encoding, cropping, speed changes and overlays) and matches them against the reference database, an approximate nearest-neighbour search at enormous scale. YouTube's Content ID (launched in 2007) does this; rights holders choose to block, track or monetise matches. Fingerprints are distinct from cryptographic hashes: changing one pixel completely changes a SHA-256 but barely moves a perceptual fingerprint. See Vector Databases and Similarity Search.
- Known-bad content hashing. Industry hash-sharing databases for the most serious illegal content let platforms block re-uploads of known material immediately.
- ML classifiers for nudity, violence, spam and other policy categories run on sampled frames, audio and transcripts. They produce scores, not verdicts: high-confidence violations are blocked, borderline cases go to human review, and low scores publish normally.
- Human review queues prioritised by predicted severity and reach (a video already getting thousands of views is reviewed first).
- Appeals and audit trails: every automated decision is logged with the model version and scores so it can be reviewed and reversed.
The design trade-off is latency versus safety. Blocking publication until every check finishes slows creators; publishing first and checking in parallel risks a harmful video reaching viewers. A common compromise is to run fast checks (hash matches, quick classifiers) before publishing and slower ones (full fingerprinting of long videos, human review) after, with the ability to take the video down quickly. Live streams need real-time sampling of the stream, since there is no "before publication".
Deep Dive: the origin, object layout and packaging choicesShow
The CDN hides the origin most of the time, but the origin decides what happens on every miss, how much we store, and how easily we can change formats later.
Object key layout. A clean, predictable layout makes CDN rules, lifecycle policies and deletion simple:
originals/{videoId}/source.mp4
media/{videoId}/v3/master.m3u8 primary HLS manifest
media/{videoId}/v3/manifest.mpd DASH manifest
media/{videoId}/v3/h264_720p/init.mp4
media/{videoId}/v3/h264_720p/playlist.m3u8
media/{videoId}/v3/h264_720p/seg_00042.m4s
media/{videoId}/v3/av1_1080p/...
media/{videoId}/v3/audio_en_128k/...
media/{videoId}/v3/captions/en.vtt
thumbs/{videoId}/default_720.jpg- A version segment (
v3) in the path means a re-encode writes to a new prefix and flips the metadata pointer atomically. Old and new never mix in caches, and rollback is a pointer change. The old prefix is deleted later. - Keys start with a high-cardinality id, so request load spreads across the object store's internal partitions. S3, for example, scales request rates per prefix (thousands of reads per second per prefix), so millions of distinct
videoIdprefixes give effectively unlimited aggregate throughput. - Everything for one video sits under one prefix, so deletion, tiering and replication rules can target a video as a unit.
Static packaging versus just-in-time packaging.
| Approach | How it works | Pros | Cons |
|---|---|---|---|
| Static packaging | The pipeline writes final segments and manifests for every protocol | Origin is plain object storage; simplest and most cacheable | Storage multiplied by protocols and formats; adding a format means reprocessing |
| CMAF single set | One set of fMP4 segments, separate HLS and DASH manifests | About half the storage of TS plus fMP4; both protocols supported | Older devices that need MPEG-TS need a fallback |
| Just-in-time packaging | Origin servers repackage a mezzanine format into the requested protocol on a miss, then the CDN caches the result | Minimal stored variants; new formats without reprocessing; per-request manifest customisation (ads, DRM) | Origin needs compute; first-request latency; more moving parts |
Large platforms often mix them: static CMAF for the common path, and a just-in-time packager for rare device formats, DRM variants, and server-side ad insertion (stitching ads into the manifest per viewer).
Manifest personalisation. Because the manifest is a small text file, the origin can tailor it per request without touching segments: remove renditions the device cannot decode, cap resolution for the viewer's plan, choose the best CDN hostnames for this client, or insert ad segments. Personalised manifests are not shared-cacheable, but they are tiny; the segments they point to remain shared.
Origin shield sizing. The shield tier exists to protect the origin. If edges see 250,000 segment requests per second at a 90% hit rate, 25,000 per second reach the shields. If the shields hit 80% of those, only 5,000 per second (about 2% of the total) reach object storage. Each shield node handling tens of Gbps of throughput, a handful per region suffices. The real risk is a cold start (new region, cache flush) or a burst of new content, which is why request collapsing and gradual traffic shifting matter.
Thumbnails and images. Thumbnails are requested far more often than any single video segment (every page view shows dozens of them). Generate a few sizes in the pipeline, serve modern formats such as WebP or AVIF where supported, and cache them at the edge for a long time with versioned URLs so a creator's custom thumbnail update is a new URL, not a purge.
Deep Dive: captions, thumbnails and other side outputsShow
The processing DAG produces more than video renditions, and each side output has its own trade-offs.
Automatic captions. Speech recognition runs on the extracted audio track. Modern ASR models are accurate for widely spoken languages and weaker for rare languages, accents, overlapping speech and music. The pipeline:
- Detect the spoken language (or use the creator's declared language).
- Transcribe in chunks in parallel (the same fan-out idea as video transcoding), with overlaps between chunks to avoid cutting words.
- Align words to timestamps, then build caption cues of readable length (a couple of lines, a few seconds each).
- Write WebVTT for HLS and web players, TTML or IMSC for DASH and TVs, and the plain transcript for the search index.
Creators can upload their own caption files or correct automatic ones; uploaded captions take precedence. Machine translation can produce captions in other languages, flagged as automatic. Captions are an accessibility requirement in many jurisdictions for some content types, and they also improve search: the transcript turns spoken words into searchable text.
Thumbnail selection. The pipeline extracts candidate frames (for example one per second, or at scene changes), filters out blurry, dark or transitional frames, and scores the rest for quality and representativeness, often with a learned model. Creators choose from the candidates or upload a custom image, which then goes through the same safety checks as the video.
Preview sprites and animated previews. For the scrubbing preview, the pipeline renders small frames every few seconds into sprite sheets (one image holding a grid of frames) with a WebVTT index mapping time ranges to sprite coordinates, so the player fetches a few images instead of hundreds. Animated hover previews are short, low-bitrate clips generated from a few highlight moments.
Chapters and structure. Chapters may come from the creator's timestamps in the description or from automatic segmentation of the transcript and scenes. They are small metadata stored with the video record.
Audio normalisation. Loudness varies widely between uploads. Measuring integrated loudness (in LUFS, per the ITU-R BS.1770 standard) and storing a normalisation value lets players even out the volume between videos without re-encoding.
All side outputs are independent DAG branches from the original, so they never delay the core video renditions, and a failed caption job does not block publishing. It just retries, or the video publishes without automatic captions and gets them later.
Deep Dive: observability for a video platformShow
Two very different systems need monitoring: the ingest pipeline, where problems show up as delays, and the delivery path, where problems show up as bad playback for millions of people. See Observability: Logs, Metrics and Traces.
Ingest pipeline.
- Upload success rate and resumptions per upload; time from upload start to upload complete by file size and country.
- Processing latency (upload complete to
ready) at p50, p95 and p99, split by video length and resolution, with an SLO such as "95% of videos under 10 minutes are ready within 5 minutes of upload completion". - Queue depth and oldest task age per priority queue; worker utilisation; task retry and failure rates by error class (corrupt input, out of memory, timeout).
- Quality checks on output: sampled VMAF scores per rendition, detection of black frames, audio-video sync drift and missing audio.
Delivery path.
- QoE from player telemetry: startup time, rebuffering ratio, average bitrate, bitrate switch frequency, playback failure rate, exit-before-start rate. Slice by country, ISP, device, player version, CDN and rendition ladder.
- CDN: request and byte hit rates per tier, origin offload, error rates and latency per CDN per region, egress by CDN for cost tracking.
- Origin and metadata: request rate and latency for the video service and metadata cache, cache hit rate, hot-key detections, Cassandra latency by partition.
- Live: ingest health per stream (bitrate, dropped frames from the broadcaster), segment publish latency, playlist request rate and collapse ratio, and end-to-end latency measured by embedding timestamps in the stream.
Alerting on users, not only on servers. A CDN can report healthy servers while viewers in one ISP see rebuffering because of a congested peering link. Player-side QoE metrics, aggregated in near real time (seconds to a minute), catch these problems first, and automated steering can respond by shifting that ISP's traffic to another CDN or cache cluster.
Experimentation. Encoder settings, ladders and ABR algorithms are changed through A/B tests measured on QoE and engagement (watch time), because offline quality metrics do not always predict viewer behaviour. That feedback loop is how large video platforms keep improving.
Deep Dive: multi-region architectureShow
A global video platform runs in several regions, but not every component needs the same treatment. Separate the control plane (APIs, metadata, search, upload orchestration) from the data plane (video bytes through the CDN).
- Data plane. Already global by construction: CDN edges everywhere, shields per region, and object storage origins in a few regions. Popular renditions are replicated to every origin region; long-tail renditions live in one or two, with the CDN fetching cross-region on a miss. Originals are replicated to at least two regions for disaster recovery.
- Metadata. Read-mostly and tolerant of slight staleness, so replicate asynchronously to every serving region (Cassandra multi-datacentre replication with
LOCAL_QUORUMreads and writes, or DynamoDB global tables). A creator's edits are written in their nearest region and propagate within a second or so. Conflicts are rare (one owner edits one video) and last-writer-wins on each field is acceptable. See Database Replication. - Uploads. Creators upload to the nearest region's bucket. The processing DAG runs in that region, close to the data, and the outputs replicate outward. If a region is overloaded, the orchestrator can send work to another region, at the cost of moving the original across regions first.
- Search. Each region has its own index replica fed from the replicated metadata stream, so queries are served locally.
- View counts. Each region aggregates its own views, and a global roll-up sums regional deltas every few seconds. A video's count is the sum, so no cross-region coordination happens on the write path.
- Failover. If a region fails, DNS or anycast steers API traffic to the next region, which has the metadata replica and can serve playback (segments come from the CDN and the surviving origins). Uploads in progress to the failed region must restart elsewhere, or resume when it recovers, since their parts live in that region's bucket. See Multi-Region and Global Data.
The principle: replicate what is small and read everywhere (metadata, popular renditions); keep in place what is large and rarely read (long-tail renditions, in-progress uploads), and design the failure behaviour of each explicitly.
Deep Dive: spending 45 minutes on this problem in an interviewShow
The topic is huge, so time management is part of the answer.
- Minutes 0-5: requirements. Pin down upload and watch as the core; mention metadata, search and view counts; confirm scale (1 million uploads and 100 million views per day), file sizes (tens of GB), and the priorities (availability, low-latency playback on poor networks, resumable uploads). Say explicitly that the non-functional requirements carry this problem.
- Minutes 5-10: estimates, entities, API. Do only the numbers that change decisions: storage per day, egress in Tbps (which forces a CDN), and transcoding cores (which forces a parallel pipeline). Sketch the presigned-URL upload API and the metadata-plus-manifest watch API.
- Minutes 10-20: high-level design. Upload direct to object storage; store segments in several renditions (bad, good, great); stream with adaptive bitrate (bad, good, great); metadata in a partitioned store with a cache; CDN in front of the segments.
- Minutes 20-40: deep dives. At senior level, the processing DAG and resumable uploads are expected. At staff level, add one or two of: CDN hierarchy and economics, ABR algorithms, view counting, or live versus VOD, steered by the interviewer's interest. Use numbers: parallel speed-up, hit rates, cost per view.
- Minutes 40-45: failures and evolution. Walk through one or two failure modes (viral video, worker crash, CDN outage) and say what you would build first and what later (popularity-based codecs, ISP caches, live).
Common mistakes: sending video bytes through application servers; forgetting that devices need different formats; describing "chunked download" of one file instead of segments and manifests; claiming a single database row per view count; ignoring egress cost; and spending ten minutes on comments or recommendations, which were out of scope.
Deep Dive: variants and how the design shiftsShow
Netflix-style subscription catalogue. Tens of thousands of titles instead of billions of videos. Upload is a studio delivery of a high-quality mezzanine file, not a phone upload, so resumable consumer uploads matter less. Encoding gets enormous effort per title (per-shot optimisation, multiple codecs, HDR formats such as Dolby Vision and HDR10, multiple audio formats and dozens of subtitle languages). Content is pre-positioned in ISP caches overnight. DRM is mandatory. Personalisation (artwork, rows) is a large separate system.
YouTube-style user-generated platform. Billions of videos with a long tail. Processing speed and cost per upload matter most, so: fast first renditions, popularity-driven re-encoding, pruning of tail renditions, reactive deep caching. Moderation and copyright matching are core. Search and recommendations drive discovery.
Short-video feed (TikTok, Reels, Shorts). Videos are short (seconds to a few minutes), vertical, and consumed in a continuous feed, so prefetching the next videos is the dominant playback optimisation: the client downloads the first segments of the next few feed items while the current one plays. Startup must feel instant. Many short videos are delivered as small progressive files or a few segments rather than long ABR ladders. The recommendation feed is the heart of the system; see the TikTok case study.
Live streaming platform (Twitch, YouTube Live). Real-time ingest and transcoding per stream, short-TTL playlists, LL-HLS or WebRTC, chat at massive fan-out, and recording to VOD. Cost per viewer-hour is higher because transcoding cannot be amortised over a long tail of future views.
Enterprise and education video. Smaller scale, heavier access control (single sign-on, per-course permissions), captions and accessibility as legal requirements, and often a managed service (AWS Elemental MediaConvert, Mux, Cloudflare Stream, or similar) rather than a custom pipeline. Knowing when to buy instead of build is part of the answer.
Music streaming shares much of the delivery design (encoded renditions, CDN, DRM, offline downloads), but files are small and transcoding is cheap, so catalogue metadata, playlists, recommendations and royalties dominate; see the music streaming case study.
Key Takeaways#
- Upload directly to object storage with presigned multipart URLs; track parts with ETags and
ListPartsfor resumable uploads; abort stale uploads with lifecycle rules. See Pattern: Handling Large Files and Blobs and Object Storage and Blob Storage. - Store segments in an encoding ladder, not single files. Segments that start with aligned keyframes, in several renditions, plus primary and media manifests, are what make adaptive bitrate streaming possible.
- Processing is a DAG: probe, split at keyframes, transcode chunks in parallel, handle audio, captions, thumbnails and safety checks in parallel, package, write manifests, publish. Orchestrate it with a durable workflow engine and pass object references, not bytes. See Pattern: Multi-Step Processes and Workflows and Temporal and Workflow Engines.
- Adaptive bitrate runs on plain HTTP: HLS and DASH (with shared CMAF segments) let the player switch rendition at every segment boundary using throughput and buffer signals. Buffer-based logic minimises rebuffering, the event viewers hate most.
- Video delivery is a CDN problem. Immutable segments with long TTLs, an edge and shield hierarchy with request collapsing, ISP-embedded caches and multi-CDN steering carry terabits per second. See Content Delivery Networks (CDN) and Cache Failure Modes: Stampedes, Hot Keys and Penetration.
- Metadata is a read-heavy, hot-key problem: partition by
videoId, cache in layers, separate fast-changing fields such as view counts. See Pattern: Scaling Reads and Apache Cassandra in Practice. - Search is fed asynchronously from the metadata DB through change data capture, including transcripts and periodic popularity signals. See Change Data Capture and the Outbox Pattern and Elasticsearch and Search Systems.
- Count views through a stream, deduplicating by session, applying view rules, aggregating in windows and writing idempotent deltas; correct with batch recounts. See Apache Flink and Stream Processing and Probabilistic Data Structures for Big Data.
- Live is different: real-time ingest and transcoding, growing playlists with short TTLs, latency budgets from 25 seconds down to 2 seconds with LL-HLS, and WebRTC for sub-second. See Pattern: Pushing Realtime Updates.
- Economics drive the design: egress and storage dwarf compute, so spend encoding effort in proportion to expected views, maximise cache hit rate, and tier or prune the long tail. See Data Lifecycle, Tiering and Retention.