YouTube and Netflix let millions of people press play and watch smoothly on a phone, a laptop or a TV, on fast Wi-Fi or a weak mobile network. A video is large, the audience is huge, and the networks differ. The design has two halves. The first is the upload pipeline: take one file and turn it into many versions that any device can play. The second is delivery: move enormous amounts of data to viewers without the origin servers ever seeing most of it. Storing files in object storage and the basics of a CDN are in earlier lessons, so here we focus on what is specific to video.
1. Requirements and Scope
Functional requirements:
- Upload a video (large files, on unreliable connections).
- Watch a video: playback starts fast and rarely pauses, on any device and network.
- See a title, description, thumbnail and view count.
Non-functional requirements:
- Fast start: playback begins in under 2 seconds.
- No buffering: the quality adapts to the viewer's network instead of stalling.
- Durable: an uploaded video is never lost.
- Highly available playback. Uploads can be a little slower to process, but playing must work.
- Cost-aware: video bandwidth is the biggest cost, so every design choice is also a cost choice.
Out of scope: search, recommendations, comments, live streaming and ads. We mention recommendations only where they touch the design.
2. Estimation
- Watching: 500 million daily viewers watch about 1 hour each: 500 million hours a day. Average delivered quality is about 3 Mbps, which is 1.35 GB per hour (3 Mbps = 0.375 MB/s × 3,600 s). So 500,000,000 × 1.35 GB ≈ 675 PB a day. Per second: 675 PB ÷ 86,400 ≈ 7.8 TB/s, about 62 Tbps on average, and roughly 125 Tbps at the evening peak (about 2 times).
- Viewers at once: 500 million hours ÷ 24 ≈ 21 million watching at any moment on average. With 4-second segments, that is about 5 million segment requests per second.
- Video starts: 5 per viewer: 2.5 billion a day ≈ 28,900 per second, and 116,000 at peak (4 times). These are metadata reads, not video data.
- Uploads: 500 hours of video uploaded every minute = 720,000 hours a day. At 8 Mbps (3.6 GB per hour), that is about 2.6 PB a day, or 240 Gbps of upload traffic.
- Storage: each upload becomes 6 renditions, which together take about 1.5 times the original size: about 4 PB a day, 1.4 EB a year. Storage grows forever, so older, rarely watched renditions move to cheaper tiers.
- Transcoding compute: 720,000 hours × 6 renditions = 4.3 million hours of encoding a day. If one core encodes at about 5 times real time (using parallel chunks), that is 4.3M ÷ 5 ÷ 24 ≈ 36,000 cores running all day.
The takeaway: 62 Tbps cannot come from any set of origin servers. The CDN must serve nearly all of it, and the origin sees only the misses. Delivery, not the database, is the heart of this design.
3. API
POST /v1/videoswith title and size returns avideoIdand pre-signed upload URLs for the parts (multipart upload, see the storage lesson).POST /v1/videos/{id}/completetells us all parts are uploaded and processing can start.GET /v1/videos/{id}returns metadata, the status and the manifest URL.- The manifest and the video segments are plain files fetched from the CDN, so they are not part of our API servers.
4. Data Model
- Video metadata
(video_id, owner_id, title, description, duration, status, created_at, manifest_path)in a sharded database byvideo_id.statusisUPLOADING,PROCESSING,READYorFAILED. It is read-heavy, so a cache sits in front. - Renditions
(video_id, resolution, codec, bitrate, path): which versions exist. - Files (raw upload, segments, thumbnails) in object storage, with paths such as
videos/{id}/720p/seg-0001.ts. The database holds paths, never the bytes. - View counts in a separate counter store (section 9).
4.1 How a File and Its Database Row Find Each Other
The object store and the database do not know about each other. Object storage has no link to the database, and the database has no foreign key to a file. The link is a naming rule that the application controls:
- The video ID is in every file path. The API creates the
video_idfirst, and every file for that video lives undervideos/{video_id}/:raw/original.mp4,720p/seg-0001.ts,master.m3u8,thumb.jpg. From the ID, anyone can build the path. - The row stores the paths that matter. The metadata row holds
manifest_path, and the renditions table holds apathper rendition. The player never needs to search the bucket: the row says where to look. - A path is not a URL. The row stores the storage path. The URL given to the player is built from it:
https://cdn.example.com/plus the path. If the CDN hostname changes, no rows change.
videos table: video_id = v-8841, status = READY, manifest_path = videos/v-8841/master.m3u8
object store: videos/v-8841/raw/original.mp4
videos/v-8841/720p/seg-0001.ts ... seg-0150.ts
videos/v-8841/master.m3u8
player URL: https://cdn.example.com/videos/v-8841/master.m3u8
The two can disagree, so the order of writes matters. The row is created before the file, so a file never exists without a row. The row says READY only after the files are durable, so a row never points to a missing file. Two cleanup jobs handle the leftovers: rows stuck in UPLOADING for more than a day are deleted, and a lifecycle rule aborts unfinished multipart uploads.
5. High-Level Design
flowchart LR
U["Uploader app"] -->|"multipart upload"| RAW[("Object storage: raw uploads")]
U --> API["Video API"]
API --> DB[("Metadata DB")]
RAW --> K[["Kafka: video-uploaded"]]
K --> TP["Transcoding pipeline: workers"]
TP --> OUT[("Object storage: segments + manifest")]
TP --> DB
P["Player app"] --> API
P -->|"manifest, segments"| CDN["CDN edge caches"]
CDN --> OUT
- Create the row first. The Video API creates the metadata row (
UPLOADING) and avideo_id, and returns pre-signed URLs for the keyvideos/{id}/raw/original.mp4. - Upload to storage. The uploader sends the parts straight to object storage. Our servers and the database are not involved in this step, so they never carry the video.
- Detect completion. When the last part is in, the uploader calls
complete. The API checks that the object really exists and has the right size, sets the status toPROCESSING, and publishes avideo-uploadedevent to Kafka. (Storage event notifications can publish the same event.) - Transcode, files first. The pipeline reads the raw file by its path, and writes segments, manifest and thumbnails under
videos/{id}/. Only then does it insert the renditions rows and set the video toREADY. - Play. The player asks the API for metadata. The API builds the manifest URL from
manifest_path. After that, the player talks only to the CDN, which fetches from object storage on a miss.
6. The Upload and Processing Pipeline
A raw upload is one big file in one format. Playback needs many small files in several qualities. That conversion is transcoding.
| Rendition | Typical bitrate | Size per minute | For |
|---|---|---|---|
| 240p | 0.4 Mbps | 3 MB | Very weak connections |
| 360p | 0.8 Mbps | 6 MB | Mobile data |
| 480p | 1.5 Mbps | 11 MB | Small screens |
| 720p | 3 Mbps | 23 MB | Most laptops and phones |
| 1080p | 5 Mbps | 38 MB | TVs, good connections |
| 4K | 25 Mbps | 190 MB | Large TVs, fast fibre |
- Split, encode in parallel, join. The video is cut into chunks (at keyframe boundaries) of a minute or less. Each chunk is encoded into every rendition by a different worker. A 2-hour film then takes minutes, not hours, because hundreds of workers run at once.
- A pipeline of small tasks. Validate the file, extract audio, encode chunks, create thumbnails, run checks such as copyright and safety, write the manifest. Each task takes input from storage and writes output to a fixed path, so a retry just overwrites the same file. Failed tasks are retried, and repeated failures go to a dead-letter queue (see the queues lesson).
- Publish early. Encode the lowest renditions first. As soon as 360p is ready, mark the video watchable and add higher qualities to the manifest as they finish. The creator sees the video in minutes.
- Spend compute to save bandwidth. A newer codec such as VP9 or AV1 gives the same quality in 30% to 50% fewer bits than H.264, but needs much more compute to encode. An encode happens once, while a popular video is delivered millions of times, so for popular videos the extra compute pays back. Rarely watched videos get the cheaper encode.
7. Playback: Adaptive Bitrate Streaming
The player cannot know the viewer's network in advance, and the network changes during a video. So each rendition is cut into short segments of 2 to 10 seconds, and a manifest file lists them (HLS and DASH are the common formats). A simplified HLS master playlist:
#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360
360p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=3000000,RESOLUTION=1280x720
720p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080
1080p/index.m3u8
The player downloads the manifest and then fetches segments one by one with ordinary HTTP GET. Before each segment it picks a rendition. The logic runs in the player, not on our servers:
Rendition choose(double measuredMbps, double bufferSeconds, List<Rendition> ladder) {
if (bufferSeconds < 5) return ladder.get(0); // about to stall: drop to the lowest
double safe = measuredMbps * 0.8; // keep a margin for network changes
Rendition best = ladder.get(0);
for (Rendition r : ladder) if (r.mbps() <= safe) best = r; // highest quality that fits
return best;
}
- Switching is cheap because every rendition has segments at the same time boundaries, so the player can change quality between any two segments.
- Fast start: begin with a modest rendition and a small buffer, then move up as measurements arrive.
- Because segments are plain files, a CDN caches them like images. This is the main reason the design scales.
8. Delivery: Where the Bandwidth Goes
Video popularity is very uneven. A small share of videos get most of the views, and a very long tail is rarely watched. That shapes the cache design:
- Edge caches close to viewers (in data centres and inside internet providers' networks) hold the hot segments. They serve most requests.
- Regional caches above them hold warm content and absorb edge misses.
- Origin (object storage) serves only the rare misses. Origin shield, signed URLs and cache keys are covered in the CDN lesson.
| Question | YouTube-style (user uploads) | Netflix-style (licensed catalog) |
|---|---|---|
| Catalog | Huge, grows by the minute | Small and known: thousands of titles |
| Popularity | Unpredictable: a video can go viral | Predictable from past viewing and new releases |
| Cache fill | On demand: the first miss fills the cache | Pushed ahead: popular titles are copied to servers inside ISPs overnight, when traffic is low |
| Processing | Fast and cheap for everyone, better encodes for popular videos | Heavy encoding per title, with extra renditions tuned for each title |
| What matters most | Handling the long tail and viral spikes | Pre-positioning content and a personalized home page |
The idea behind Netflix's approach is simple. If you know tomorrow's likely favourites today, you can fill the caches during the night with cheap bandwidth, and the evening peak never touches the origin. For user uploads you cannot predict, so you cache on first request, and use a shield so a viral video causes one origin fetch, not thousands.
9. Metadata, Views and Recommendations
- Metadata: 116,000 starts per second at peak are served from a cache in front of the metadata database. Titles and thumbnails rarely change.
- View counts: do not update one row per view. The player sends a view event, the events flow through Kafka, and counters are updated in batches. The number shown can be a little behind. A view counts only after the player has watched for some seconds, which also filters fake views.
- Recommendations and search are separate systems. The home page is a list of video IDs produced by them, and our service fills in the metadata (see the news feed lesson for the same pattern).
10. Worked Example: Priya Uploads a Tutorial
Priya records a 10-minute 1080p tutorial. At 8 Mbps the file is about 600 MB.
- Her app calls
POST /v1/videosand gets six pre-signed URLs for 100 MB parts. It uploads them in parallel. The connection drops after part 4. When it returns, the app uploads parts 5 and 6 only. - The app calls
complete. The event goes to Kafka. The video isPROCESSING. - A worker splits the file into ten 1-minute chunks. Workers encode each chunk into 6 renditions in parallel. The 360p set finishes first, within a couple of minutes. The video becomes watchable and shows
READYwith a manifest listing 360p. - Higher renditions finish over the next minutes, and the manifest is updated.
- A viewer, Dev, opens the video. The API returns metadata and the manifest URL (from cache). His player fetches the manifest, measures 6 Mbps, and picks 1080p. Its first segments are cache misses at his local edge. They come from a regional cache or origin and are stored on the way.
- The next 10,000 viewers in the same city get all segments from the edge. Midway through, Dev's train enters a tunnel. The buffer drops below 5 seconds, so the player switches to 360p and keeps playing, then climbs back up.
11. Scaling and Failures
- Uploads are resumable and go straight to storage, so large files and weak connections do not hurt our servers.
- Transcoding scales by adding workers, based on queue depth. Tasks are idempotent. A priority lane keeps new uploads from popular channels ahead of a backlog of old re-encodes.
- CDN failure: traffic shifts to other edges or to another CDN provider. Large services use several CDNs and steer traffic between them.
- Viral video: the origin shield merges simultaneous misses into one origin fetch. Pre-warming the edges for videos that are starting to trend also helps.
- Durability: the raw upload and all renditions are replicated across zones in object storage. The raw file is kept, so videos can be re-encoded later with better codecs.
- Monitoring: time to first frame, rebuffering rate, share of playback at each quality, CDN hit rate, and transcoding lag from upload to
READY.
12. Common Pitfalls
- Uploading through app servers. They become the bottleneck. Use pre-signed multipart uploads.
- Serving a single file at one quality. The viewer on a weak network stalls, and the viewer on a fast one gets poor quality.
- Encoding a whole video in one piece, which takes hours and loses everything on a failure. Split into chunks.
- Publishing only when every rendition is done. Make the video watchable after the first one.
- Letting origin servers face viewers. Put a CDN with a shield in front of storage.
- Updating a counter row for every view. Batch the events.
- Ignoring cost. Bandwidth and encoding compute dominate the bill, so codec and caching choices are cost choices.
13. Interview Questions
- How does adaptive bitrate streaming work? Each video is cut into short segments in several qualities, listed in a manifest. The player measures its throughput and buffer, and picks the quality for each next segment. Segments are plain files, so a CDN serves them.
- How do you upload a large video reliably? Multipart upload with pre-signed URLs straight to object storage. The client retries only failed parts and can resume.
- How do you speed up transcoding? Split the video into chunks, encode the chunks in parallel, and join the results. Run the lowest quality first so the video can be published early.
- How do you serve 60 Tbps? Through a CDN. Popularity is skewed, so edge caches hold the hot segments, regional caches and a shield absorb misses, and the origin sees very little.
- How does Netflix differ from YouTube? Netflix has a small, predictable catalog, so it can copy popular titles into servers inside ISPs overnight. YouTube has a huge, unpredictable catalog, so it caches on demand and handles the long tail.
- Why use newer codecs if they cost more to encode? Encoding happens once and delivery happens millions of times. For popular videos, saving 30% to 50% of the bits saves far more than the extra compute costs.
- How do you count views at scale? Send view events through Kafka and update counters in batches. Accept a slightly stale number, and count a view only after some watch time.