SkillSprout
Chapter 7 · Lesson 3
Advanced
31 min read

Design YouTube (Video Streaming)

Overview

A video platform has two jobs that barely resemble each other. Creators upload large files that must be accepted reliably and converted into many formats. Viewers press play and expect video to start in about a second, on any device and any network. The numbers are enormous: hundreds of terabytes of new video every day and tens of terabits per second of video flowing out. This lesson walks the full eight-step interview framework. The key ideas are a resumable upload, a transcoding pipeline that splits each video into pieces and processes them in parallel, adaptive bitrate streaming, and a CDN that serves nearly every byte so the origin does not have to.

Detailed Notes

How to use this lesson

Treat this as a 45-minute interview. The numbers are assumptions you state out loud, not facts about any real company. The interviewer checks that your estimates drive your design: a 400x gap between ingest and egress is the reason the CDN exists.

New terms are defined where they first appear. You already know caching, CDNs, queues, partitioning and retries from the earlier chapters, so they get a one-line reminder only.

Step 1: Clarify Requirements

Start by turning "design YouTube" into a scope you can finish in 45 minutes. A good opening: "Video is a huge product. I'd like to focus on upload, processing and playback, and agree on what to skip."

Functional requirements

  • A creator uploads a video file (up to several GB), and the upload survives network drops.
  • The system processes the video so it plays on phones, laptops and TVs, on fast and slow connections.
  • A viewer watches a video with fast start and no long buffering pauses.
  • A video shows a title, description, thumbnail and view count.
  • Viewers can search for videos and see recommendations.

Extended requirements

Mention these, then ask whether to include them.

  • Comments, likes and subscriptions.
  • Live streaming (a different pipeline with strict latency).
  • Captions, content moderation and copyright detection.
  • Monetization and ads.

Non-functional requirements

  • Fast start: the first frame appears in under 2 seconds at p99 (99 of 100 plays are faster).
  • Smooth playback: rebuffering (video pausing to load) under 1% of watch time.
  • High availability: 99.99% for playback, about 52 minutes of downtime a year. Upload can be slightly less available, at 99.9%.
  • Durability: an accepted upload must never be lost. Target 11 nines (99.999999999%) for stored video, which object storage provides.
  • Scalability: millions of simultaneous viewers and hundreds of thousands of uploads a day.
  • Processing latency: a 10-minute video should be watchable within a few minutes of upload, not hours.
  • Cost efficiency: storage and bandwidth are the largest bills, so cost is a first-class requirement.

Consistency decision. Playback and view counts tolerate staleness: showing 1.2M views when the real number is 1,203,411 hurts nobody. A video's published state must be consistent: once we say "ready", every segment must exist.

Out of scope

Live streaming, ads, comments, DRM (copy protection), creator payments, and the content moderation model itself. We note where moderation hooks in but do not design it.

Interview tip. Candidates often draw "upload to server, save to database, serve from server." Say early that video bytes never go through the app servers or the metadata database. That single sentence shows you understand the scale.

Step 2: Estimate Scale

Estimation tells you which parts are hard. Round every number so you can do the arithmetic aloud.

Assumptions to state

  • 500 million daily active users (DAU), each watching 5 videos a day.
  • 500,000 uploads per day.
  • An average video is 10 minutes long. The raw uploaded file is 500 MB (about 7 Mbps).
  • The average viewer watches 5 minutes of each video they open, at an average 2.5 Mbps (megabits per second).
  • A day has about 100,000 seconds.
  • We keep videos for 5 years.

A few definitions. Bitrate is the data used per second of video; a higher bitrate means better quality and more bytes. A resolution is the picture size (1080p is 1920x1080 pixels). Transcoding means converting a video into other formats, resolutions and bitrates. Each converted version is called a rendition.

Views and bandwidth

text
Views per day        = 500M users x 5 videos           = 2.5 billion
Views per second     = 2.5B / 100,000 s                = 25,000 per second
Peak views / second  = 25,000 x 3 peak factor          = 75,000 per second

Concurrent viewers   = 25,000 views/s x 300 s watched  = 7.5 million
Peak concurrent      = 7.5M x 3                        = about 22 million

Egress bandwidth     = 7.5M viewers x 2.5 Mbps         = 18.75 Tbps (about 19)
Peak egress          = 19 Tbps x 3                     = about 56 Tbps
Per day              = 19 Tbps x 100,000 s / 8         = about 235 PB per day

Egress is data leaving our system toward users. Nineteen terabits per second equals about 2.3 terabytes per second. No origin data center serves that. The CDN is not an optimization here; it is the architecture.

Uploads and storage

text
Uploads per second   = 500K / 100,000 s                = 5 per second
Upload bandwidth     = 500K x 500 MB / 100,000 s       = 2.5 GB/s = 20 Gbps
Peak upload          = 20 Gbps x 3                     = 60 Gbps

Rendition bitrates   = 0.3 + 0.7 + 1.2 + 2.5 + 5       = about 10 Mbps total
                       (240p, 360p, 480p, 720p, 1080p)
One video, renditions= 10 Mbps x 600 s / 8             = 750 MB
Plus the raw original                                  = 500 MB
Storage per video                                      = about 1.25 GB

New storage per day  = 500K x 1.25 GB                  = 625 TB per day
Per year             = 625 TB x 365                    = about 230 PB
Five years                                             = about 1.1 EB

Notice the renditions (750 MB) are larger than the original (500 MB) because we store five versions. We keep the original so we can re-encode later with better codecs. A codec is the algorithm that compresses video; H.264 plays everywhere, newer codecs like VP9 and AV1 shrink files 30 to 50% at the same quality but are costlier to encode.

YouTube: Estimate the Scale
Estimation

Request load

500Mdaily users
given
2.5Bviews per day
× 5 videos
25K/sviews per second
÷ 100,000 s
7.5Mconcurrent viewers
× 300 s watched
19 Tbpsegress
× 2.5 Mbps
56 Tbpsegress at peak
× 3 peak factor

Uploads and storage

625 TB/day

500K uploads/day (5 per second) × 1.25 GB (750 MB renditions + 500 MB original); about 230 PB a year

Object storage with lifecycle tiering

Egress

19 Tbps

7.5M viewers × 2.5 Mbps, about 235 PB per day and 750K segment requests/s

A CDN must serve the bytes

CDN and origin

~200 Gbps

19 Tbps × 5% edge miss × 20% regional miss

Origin sees about 1% of traffic
Key point. We store about 0.6 PB a day but send about 235 PB a day, so the CDN carries nearly all the load.

Egress comes from viewers x watch time x bitrate. Storage comes from uploads x renditions.

Processing load

text
Video minutes per day   = 500K x 10 min                = 5 million minutes
Encoding cost (assumed) = 10 CPU-minutes per video minute (all 5 renditions)
CPU work per day        = 5M x 10 = 50M CPU-minutes    = 3 billion CPU-seconds
Average cores busy      = 3B / 100,000 s               = 30,000 cores
With 2x headroom for peaks                             = about 60,000 cores

Segments: 10-second pieces -> 60 per video
Tasks = 60 segments x 5 renditions                     = 300 tasks per video
Tasks per day           = 500K x 300                   = 150 million
Tasks per second        = 150M / 100,000               = about 1,500 per second

Thirty thousand cores is a lot, but it is batch work that can wait seconds, so it runs on cheap, interruptible machines and scales with queue depth. Processing one video as a single job would take about an hour; splitting it into 300 independent tasks cuts that to about a minute.

Metadata, thumbnails and the request mix

text
Videos in 5 years    = 500K x 365 x 5                  = about 900 million (round to 1 billion)
Metadata per video   = about 2 KB (title, description, tags, state)
Metadata total       = 1B x 2 KB                       = about 2 TB
Thumbnails           = 500K x 5 images x 100 KB        = about 250 GB per day

Segment requests     = 7.5M viewers / 10 s per segment = 750,000 per second
Check: 750K x 3 MB (25 Mb segment)                     = 2.3 TB/s = 18.75 Tbps

Metadata is tiny (2 TB) while video is exabytes. That is why the metadata database and the video storage are completely different systems. The 750,000 segment requests per second are all static files, so a CDN can answer them.

So what?

  • Egress of 19 Tbps (56 peak) means a CDN serves the bytes. The origin sees only misses.
  • 625 TB of new video per day means object storage, with lifecycle rules to cheaper tiers.
  • 1,500 tasks per second means a parallel, queue-driven transcoding pipeline.
  • 2 TB of metadata means a normal sharded database, plus a cache, and no special tricks.

Interview tip. State the 400x gap aloud: we store about 0.6 PB a day but send about 235 PB a day. Reads dominate writes by far, so every optimization belongs on the playback path.

Step 3: Define the APIs

Video bytes and control messages travel on different paths. The control APIs (create, status, metadata) are small JSON requests to our servers. The bytes go straight to object storage (upload) and the CDN (playback).

Start an upload

http
POST /v1/videos
Authorization: Bearer <token>
Content-Type: application/json
Idempotency-Key: 7f3c9a10-5b2e-4d0a-9c11-2f6f1e0a8b77

{
  "title": "Learn System Design in 10 Minutes",
  "description": "A quick intro.",
  "file_size_bytes": 524288000,
  "content_type": "video/mp4",
  "sha256": "9b74c9897bac770ffc029102a200c5de..."
}
json
{
  "video_id": "v_8Xk29aQ",
  "upload_id": "up_41c0e7",
  "chunk_size_bytes": 8388608,
  "total_chunks": 63,
  "expires_at": "2026-12-05T10:00:00Z"
}

The 8 MB chunk is a fixed-size piece of the file. Splitting the file into chunks lets the client upload several in parallel and retry only the piece that failed.

Upload a chunk, check progress, finish

http
PUT /v1/uploads/up_41c0e7/chunks/17
Content-Length: 8388608
Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==

<binary data>
http
GET  /v1/uploads/up_41c0e7              # which chunks do you already have?
POST /v1/uploads/up_41c0e7/complete     # all chunks sent, start processing

Status codes that matter:

  • 201 Created on start, 200 OK for an accepted chunk, 202 Accepted on complete (processing continues in the background).
  • 400 Bad Request if the checksum of a chunk does not match (the client resends only that chunk).
  • 409 Conflict if complete is called while chunks are missing.
  • 413 Content Too Large if the file exceeds the limit (for example 256 GB).
  • 429 Too Many Requests if the creator exceeds the upload quota.
  • 410 Gone if the upload session expired.

Idempotency. A retry of POST /v1/videos with the same Idempotency-Key returns the same video_id instead of creating a duplicate. Chunk uploads are naturally idempotent: writing chunk 17 twice leaves the same data.

In production the chunk is often sent straight to the object store through a pre-signed URL (a temporary, signed link that allows one specific upload). The result is the same: the bytes bypass our app servers.

Watch a video

http
GET /v1/videos/v_8Xk29aQ
json
{
  "video_id": "v_8Xk29aQ",
  "title": "Learn System Design in 10 Minutes",
  "channel_id": "c_77aa10",
  "status": "READY",
  "duration_s": 600,
  "thumbnail_url": "https://cdn.vid.example/t/v_8Xk29aQ/0.jpg",
  "manifest_url": "https://cdn.vid.example/v/v_8Xk29aQ/master.m3u8",
  "view_count_approx": 1203000
}

The player then talks only to the CDN, requesting the manifest and segments. Errors: 404 if unknown, 403 if private, 409 if status is not READY (still processing).

Other APIs

http
POST /v1/videos/{id}/views               # player beacon, returns 204 No Content
GET  /v1/search?q=system+design&cursor=  # search, paginated
GET  /v1/feed?cursor=...                 # recommendations for the home page

How the API shapes the architecture

Upload is a long, multi-request session with state. Playback is a handful of metadata calls followed by hundreds of static file downloads. These need two different paths, and the second one must be served by a CDN.

Step 4: Define the Data Model

Start from access patterns:

  1. Resume an upload: which chunks of up_41c0e7 have arrived?
  2. Load a video page: given video_id, return metadata and the manifest location (about 100,000 reads per second with browsing).
  3. List a channel's videos: all videos for channel_id, newest first.
  4. Track processing: which tasks of a video are pending, running or failed?
  5. Count views: increment a counter for video_id at 25,000 events per second.

Fields and why each exists

  • videos.status: UPLOADING, PROCESSING, READY, FAILED, BLOCKED. It gates playback.
  • videos.raw_object_key: where the original sits in object storage, so we can re-encode later.
  • video_renditions: one row per rendition (for example 720p_h264) with the location of its playlist. A video is playable when the renditions we require exist.
  • upload_sessions.received_chunks: a bitmap of chunks received, which powers resume.
  • transcode_tasks: one row per (segment, rendition) with a state and an attempt counter. It lets the orchestrator resume after a crash and detect poison videos.
  • view_counts: kept apart from videos, for the same reason click counts were kept out of the URL row: a popular video would make one hot row.
The Data Model
Data model
videosSharded relational DB
  • PKvideo_idvarchar(12)

    partition key

  • FKchannel_idvarchar(12)

    owner

  • titlevarchar(200)
  • descriptiontext
  • statusUPLOADING | PROCESSING | READY | FAILED | BLOCKED

    gates playback

  • duration_sint
  • raw_object_keyvarchar

    original, kept for re-encoding

  • IDXcreated_attimestamp

    with channel_id: newest first

About 2 KB per row and 1B rows. Cached heavily because it is read on every play.

video_renditionsSame DB
  • PKvideo_idvarchar(12)
  • SKrenditionvarchar

    for example 720p_h264

  • bitrate_kbpsint
  • playlist_keyvarchar

    points to the rendition playlist in object storage

  • size_bytesbigint

    for cost and tiering decisions

One row per rendition. Playable when the required rows exist.

channelsSame DB
  • PKchannel_idvarchar(12)
  • namevarchar(100)
  • UQowner_user_iduuid

Small table.

upload_sessionsKey-value store (TTL)
  • PKupload_idvarchar
  • FKvideo_idvarchar(12)
  • total_chunksint
  • received_chunksbitmap

    powers resume

  • expires_attimestamp

    TTL, 7 days

Short-lived and write-heavy during uploads.

transcode_tasksWide-column store
  • PKvideo_idvarchar(12)
  • SKtask_idsegment#rendition

    for example 0017#720p

  • statePENDING | RUNNING | DONE | FAILED
  • attemptsint

    3 attempts, then dead-letter queue

  • lease_untiltimestamp

    expires if worker stops heartbeating

About 300 rows per video. Lets the orchestrator resume after a crash.

view_countsCounter store
  • PKvideo_idvarchar(12)
  • SKshardint

    0-15 sub-counters for hot videos

  • viewsbigint

    written once per aggregation window

Kept apart from videos so a viral video cannot create a hot row.

  • videos.channel_idchannels.channel_id· many to one
  • video_renditions.video_idvideos.video_id· many to one
  • upload_sessions.video_idvideos.video_id· one to one
Key point. Metadata is about 2 TB while video is exabytes: they live in different systems.

Small metadata in databases, huge video files in object storage referenced by key.

Which databases?

  • Video metadata (videos, channels): about 2 TB, read-heavy, looked up by video_id, listed by channel_id. A sharded relational database (partitioned by video_id, with a secondary index on channel_id) or a wide-column store both work. 2 TB is small, so the real concern is read volume, which a cache and read replicas absorb.
  • Upload sessions and transcode tasks: short-lived, high-write state keyed by id. A key-value or wide-column store with TTL (automatic expiry) fits.
  • View counts: a write-heavy counter store, a wide-column or key-value store, fed by an aggregator (Step 6.6).
  • Video and thumbnail files: object storage, never a database. Files are immutable, huge and read by key.

Trade-off thinking. One relational database for everything is simple and gives joins and transactions, but view counters and task state would overwhelm it. Using four specialized stores adds operations work. We choose by access pattern: relational for rich metadata, key-value for ephemeral state and counters, object storage for bytes.

Step 5: High-Level Design

Separate three paths: upload, metadata, and streaming. They scale independently and fail independently.

Upload, Metadata and Streaming Paths
Architecture
UploadMetadataStreamingClientapp / browserAPI gatewayauth, limits, LBUpload servicesessions, chunksRaw storeoriginals, objectTranscodingDAG + workersMetadataservicecached readsMetadata DBsharded, replicasCDNedge + regionalOrigin storesegments, manifests1uploadmetadatavideo bytessegmentscache fill
Key point. The CDN serves every byte of playback. App servers handle only small control requests.

Three paths that scale and fail independently. Video bytes never touch the metadata path.

Components and why each exists

  • API gateway and load balancer: authentication, rate limits, TLS, and routing.
  • Upload service: creates the upload session, verifies chunks, and starts processing on complete. It handles control only. If bytes pass through it, it can use pre-signed URLs so they do not.
  • Raw object store: durable storage for originals and the staging place for chunks.
  • Transcoding pipeline: an orchestrator and a fleet of workers that convert the original into renditions and thumbnails (Step 6.2).
  • Origin object store: holds the finished segments and manifests. It is the source of truth the CDN fills from.
  • CDN: caches segments close to viewers and serves almost all traffic.
  • Metadata service and database: video info, channel listings, status.
Resumable Upload
Request flow
ClientUpload serviceObject storeMetadata DB1POST /videostitle, size, checksum2create video + sessionstatus = UPLOADING3upload_id, chunk size4PUT chunks 1..Nparallel, each with checksum5ack per chunk6POST /complete7verify + assemble8PROCESSING, enqueue job9202 Accepted

Chunks go straight to object storage. If the network drops, the client asks which chunks exist and sends only the rest.

Request flow

Upload path.

  1. Client calls POST /v1/videos; the service stores a videos row (UPLOADING) and an upload session.
  2. Client sends chunks (in parallel) and the store acknowledges each.
  3. Client calls complete; the service verifies the chunks, sets PROCESSING and puts a job on the transcoding queue.
  4. Transcoding writes segments to the origin store and marks the video READY.

Playback path.

  1. Client calls GET /v1/videos/{id} (served from cache most of the time).
  2. Player downloads the manifest from the CDN, then segments, choosing quality as it goes.
  3. The player sends a view beacon to the API, which is queued for counting.

Step 6: Deep Dive

Interviewers usually push on processing and delivery. Cover the upload, the transcoding DAG, adaptive streaming and the CDN thoroughly; then be brief but correct on counting, search, thumbnails and cost.

6.1 Resumable chunked upload

A 500 MB upload on a phone over mobile data will be interrupted. A plain POST of the whole file would restart from byte 0 each time.

  • The client splits the file into 8 MB chunks and uploads each with its index and checksum (a short fingerprint, such as MD5, that proves the bytes arrived intact).
  • The server records each accepted chunk in upload_sessions.received_chunks. After a crash the client calls GET /v1/uploads/{id}, learns which chunks are missing and sends only those.
  • Chunks can go in parallel (for example 4 at a time) to fill the user's bandwidth.
  • On complete, the service checks every chunk exists, optionally compares the whole-file SHA-256, and tells the object store to assemble the chunks into one object.
  • Sessions expire after 7 days. A cleanup job deletes orphaned chunks, since abandoned uploads would otherwise waste storage forever.
  • Why 8 MB? Smaller chunks mean more requests and more bookkeeping; larger chunks waste more on a retry. A few MB up to 16 MB is the common range.

Because chunks go to object storage directly, the upload service handles only about 5 sessions per second of control traffic. The 20 Gbps of upload bandwidth lands on the object store, which is built for that.

6.2 The transcoding pipeline

Transcoding turns one raw upload into a family of playable files. The problem: it is slow and CPU-hungry. A single long job is slow, fails as a whole and cannot use more than one machine.

The solution: split the video, encode the pieces in parallel. Cut the video into segments of about 10 seconds. Each cut must land on a keyframe (a frame that is a complete picture rather than a difference from earlier frames) so every segment decodes on its own. Each (segment, rendition) pair is then an independent task.

The whole job is a DAG (directed acyclic graph): a set of tasks with arrows meaning "B needs A first", with no loops. Tasks without dependencies run at the same time.

Transcoding as a DAG of Parallel Tasks
Architecture
ParallelRaw uploadvalidate + probeSplit10 s at keyframesAudio + thumbsside tasksEncode 240-480pper segmentEncode720-1080pper segmentPackageplaylists + manifestPublishstatus = READY
Key point. About 300 independent tasks per video turn an hour of encoding into about a minute.

Split into 10-second segments, run all (segment, rendition) tasks at once, then package and publish.

The stages:

  1. Probe and validate. Check the container and codec, reject files that are not video, extract the duration. Fail early here, because it is cheap.
  2. Split into 10-second segments, stored next to the original.
  3. Parallel tasks: encode each segment at each rendition; extract and encode the audio; generate thumbnails. With 60 segments and 5 renditions there are about 300 tasks, each taking tens of seconds.
  4. Package. Write each rendition's list of segments (a playlist), plus the master manifest listing all renditions (Step 6.3).
  5. Publish. Verify every segment exists, then update videos.status = READY.

Design details that matter:

  • Orchestrator. A workflow engine owns the DAG. It keeps the state of each task in the transcode_tasks table, so a crash does not lose progress.
  • Work queue. Ready tasks go on a queue. Workers pull a task, process it and report back. Scale the worker fleet by queue depth.
  • Which renditions? A ladder like 240p, 360p, 480p, 720p and 1080p, plus 4K for videos uploaded in 4K. A 10-minute 1080p source never needs a 4K rendition.
  • Smart ordering. Encode 360p first and publish it as soon as it is ready; the video is watchable in about a minute while 1080p finishes. Higher renditions appear in the manifest later.
  • Right-size codecs. Encode everything in H.264 (plays on every device). Only re-encode in AV1 or VP9 when a video becomes popular, because the extra CPU pays off only when many views each save 30% bandwidth.
  • Hardware. Use cheap interruptible machines (spot instances) and GPU or dedicated encoder hardware where useful. A killed worker just means a retry.
  • Idempotent tasks. A task writes to a deterministic path such as v_8Xk29aQ/720p/seg_0017.ts. Running it twice overwrites the same file with the same bytes, so retries are safe.

Trade-off thinking. Shorter segments (2 s) give faster quality switches and quicker publishing but multiply the task count and the CDN request rate by 5x. Longer segments (10 s) reduce overhead but react more slowly to bandwidth changes. 4 to 10 seconds is the usual compromise.

6.3 Adaptive bitrate streaming (HLS and DASH)

Network speed changes constantly. If we served one big 1080p file, a viewer whose bandwidth dips would stall.

Adaptive bitrate (ABR) streaming makes the player choose quality continuously. The video is already cut into short segments at several bitrates. The player downloads one segment at a time and, before each, picks the rendition its recent download speed and buffer can sustain.

Two standard protocols do this: HLS (HTTP Live Streaming, created by Apple, uses .m3u8 playlists) and MPEG-DASH (an open standard using .mpd files). Both are plain HTTP, so ordinary web servers and CDNs can serve them.

A manifest is a small text file that describes the available renditions and where their segments are. The master manifest points to one playlist per rendition:

text
#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360
360p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=2800000,RESOLUTION=1280x720
720p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=5300000,RESOLUTION=1920x1080
1080p/index.m3u8

And each rendition playlist lists its segments:

text
#EXTM3U
#EXT-X-TARGETDURATION:10
#EXTINF:10.0,
seg_0000.ts
#EXTINF:10.0,
seg_0001.ts
...
#EXT-X-ENDLIST
One Big File vs Adaptive Bitrate Streaming
Comparison

Single progressive file

one MP4 at one quality

  1. 1

    Server picks one quality

    for example 1080p

  2. 2

    Browser downloads the file

    streams from the start

  3. 3

    Bandwidth drops

    buffer drains

  4. 4

    Video stalls

    no way to switch quality

  • One file, simple to store and serve
  • Stalls on slow or changing networks
  • Seeking needs range requests, poor caching
  • Wastes bytes on small screens

Fine for small clips, poor for a global platform

ABR with HLS / DASH

many renditions in segments

  1. 1

    Player fetches the manifest

    lists all renditions

  2. 2

    Starts at a medium rendition

    fast first frame

  3. 3

    Downloads one segment at a time

    measures speed and buffer

  4. 4

    Switches up or down

    before each next segment

  • Smooth on any network
  • Segments are immutable, so CDNs cache them perfectly
  • Seeking jumps to a segment
  • 5x the storage and encoding work
  • Many small requests (750K/s)

The standard choice; cost is managed in the long tail

Key point. The player, not the server, decides quality, one 10-second segment at a time.

ABR trades more storage and processing for smooth playback and perfectly cacheable files.

How the player behaves:

  • It starts at a low or medium rendition so the first frame appears fast, then climbs.
  • It keeps a buffer of a few segments (for example 30 seconds). If the buffer drains it switches down; if bandwidth is plentiful it switches up.
  • Because every request is a normal HTTP GET of an immutable file, segments cache perfectly. Once seg_0017.ts is stored it never changes.
  • Seeking is trivial: jump to the segment covering the target time.
  • Manifests of finished videos can be cached for a long time. Manifests of live videos change and need short TTLs (out of scope here).

6.4 CDN tiers and cache fill

Peak egress is about 56 Tbps. We use a multi-tier CDN: copies of segments in servers near viewers.

CDN Tiers and Cache Fill
Architecture
CDNViewers, regionAplayersViewers, regionBplayersEdge PoP A95% hitEdge PoP B95% hitRegional cache80% of misses hitOrigin storesource of truthsegmentssegmentsmiss 5%miss 5%miss 20%
Key point. Each tier cuts the traffic: 19 Tbps at the edge becomes about 200 Gbps at the origin.

Misses travel upward one tier at a time and the response fills each cache on its way back.

  • Edge PoP (point of presence): servers in or near an ISP, within a few milliseconds of the viewer. They answer most requests. Assume a 95% hit rate.
  • Regional cache (mid tier): a larger cache that serves many edges. Edge misses go here first. Assume 80% of those hit.
  • Origin shield and origin store: the regional tier is the only layer allowed to go to the origin, so the origin sees one request per segment per region instead of one per edge.

The numbers:

text
Viewer egress          = 19 Tbps average
Edge misses (5%)       = 0.95 Tbps = about 1 Tbps to regional tier
Regional misses (20%)  = 0.2 Tbps = about 200 Gbps to the origin

The origin sees about 1% of the traffic, a manageable 25 GB/s at average load.

Cache fill is how a cache gets a file it does not have. On a miss the edge asks the next tier and stores the answer. Important details:

  • Request coalescing. If 5,000 viewers ask for the same new segment at once, the edge sends one request upstream and holds the rest until it answers. Without it a viral video would flatten the origin (a thundering herd).
  • Eviction. Use LRU (drop the least recently used). A small set of popular videos stays hot; the long tail falls out of cache.
  • Pre-warming. For a known big release, push the first few segments of the video to edges before it goes public. The first segments matter most for fast start.
  • Cache keys. Segment URLs are versioned and immutable, so there is never an invalidation problem. If a video is deleted or blocked, issue an explicit purge and also refuse to hand out the manifest.
  • Placement near ISPs. Large platforms place servers inside ISP networks, so video traffic never crosses the open internet.
  • Several CDNs. A multi-CDN setup lets us fail over or shift traffic when one provider has problems or is expensive in a region.

Playback security is handled with signed URLs or tokens with short expiry, so private videos cannot be fetched by guessing a URL.

6.5 Metadata service and caching

  • The metadata service is stateless, so we scale it by adding instances.
  • A cache (cache-aside, as in the caching lesson) holds recent video records. With 25,000 page loads a second plus browsing and a 95% hit rate, only a few thousand reads per second reach the database.
  • Partition videos by hash of video_id so rows spread evenly (consistent hashing, from the partitioning lesson). A channel page needs a secondary index on channel_id; keep it in a separate index table or global index so listing does not scatter-gather across every shard.
  • Replication. Each shard has a leader and replicas in other zones. Reads go to replicas; a creator who just published reads from the leader briefly (read-your-writes).
  • The metadata DB is not on the playback hot path: after the page loads, the player talks to the CDN.

6.6 View counting at scale

A naive UPDATE videos SET views = views + 1 at 25,000 per second (75,000 at peak) would hammer one row for a popular video and make every play wait on a database write.

View Counting Off the Playback Path
Architecture
AsyncPlayerbeacon after 30 sEvent streamkeyed by video_idAggregators10 s windowsNightly batchdedupe, botsCounter storesub-counters204 returnedconsumeraw logexact totals
Key point. Fast approximate counts from the stream, authoritative counts from a nightly batch job.

Aggregate in windows so a video with 10,000 views per second causes one write every 10 seconds.

The design: count asynchronously.

  1. The player sends a beacon (a tiny HTTP call) after about 30 seconds of real watching, to avoid counting accidental starts.
  2. The API validates it and publishes an event to a stream (a partitioned log, like the queue lesson) keyed by video_id. The call returns 204 immediately.
  3. Aggregators read the stream and add up counts in memory for a window (for example 10 seconds). They then write one increment per video per window, not one write per view.
  4. The aggregator writes to the counter store, and a periodic job copies approximate totals into the cached video record.

Why this works and what it costs:

  • A video with 10,000 views per second becomes one write every 10 seconds, a 100,000x reduction.
  • Hot counters. For extremely hot videos split the counter into N sub-counters (for example 16) and add them when reading; this is the hot-partition fix from the partitioning lesson.
  • Eventual consistency. The displayed count can lag by seconds or minutes. That is acceptable for display.
  • Accuracy and fraud. Real money (ad revenue, creator payouts) needs exact, deduplicated counts. A nightly batch job over the raw event log filters bots and repeat views and writes authoritative numbers. The stream gives a fast approximate number, and the batch gives the final one.
  • Losing events. The stream is durable and consumers track offsets, so a crashed aggregator re-reads and recounts; deduplicate by an event id to avoid double counting.
  • Display rounded numbers ("1.2M views"). Nobody needs exactness above a thousand.

6.7 Thumbnails

  • During the transcoding DAG a task extracts frames at several times (for example 3 to 5 candidates at keyframes) and resizes them to a few sizes such as 120, 320 and 640 pixels wide.
  • A creator may pick one or upload a custom image; otherwise a simple model scores frames for sharpness and faces and picks the best.
  • Images are stored in object storage and served from the CDN. They are small (about 100 KB) and are by far the most requested files on a home page showing 30 videos at once, so they have a very high hit rate.
  • For scrubbing the progress bar, a sprite sheet (one image containing many small frames) loads in one request instead of dozens.

6.8 Search and recommendations (high level)

Search. Metadata (title, description, tags, captions) is copied into a search index. An inverted index maps each word to the list of videos containing it, so a query for "system design" intersects two lists instead of scanning a billion rows. Ranking blends text match with popularity and freshness. The index updates asynchronously from a stream of metadata changes, so a new video appears in search a few seconds to minutes after publish. The index is the derived copy and the database stays the source of truth.

Recommendations. A common two-stage approach:

  1. Candidate generation: from billions of videos, quickly pick a few hundred that could fit, using the viewer's watch history, similar viewers and similar videos (often via embeddings, lists of numbers that place similar items near each other).
  2. Ranking: a machine-learning model scores those few hundred by predicted watch time and picks the top 30.

Models train offline in batch on logged watch events. Results for each user are precomputed and cached, so the home page is a quick lookup. Say this in a minute and move on unless asked, because it is a machine-learning topic more than a systems one.

6.9 Cost optimization

Storage and bandwidth dominate. Levers:

  • Tiered storage for the long tail. Video popularity is heavily skewed: a small share of videos gets most views, and most videos are rarely watched after the first weeks. Use lifecycle rules to move old, unpopular renditions to cheaper cold storage (cheaper per GB but slower and costlier to read). Keep the 360p and 720p renditions warm and move the rest of the ladder to cold; if someone requests it, re-encode from the original on demand or restore.
  • Delete what nobody watches. For very unpopular videos, drop the high renditions entirely and keep the original plus a low rendition. Re-create on demand.
  • Better codecs only for popular videos (Step 6.2).
  • Erasure coding in object storage stores about 1.5x the data instead of 3x for replication, with similar durability.
  • Cheap compute for transcoding: spot machines, run at off-peak hours for low-priority backlogs.
  • CDN efficiency: a higher hit rate, ISP-embedded caches and multi-CDN price negotiation reduce the largest cost, which is bandwidth.
  • Deduplicate identical uploads by comparing a content hash, so one copy is kept.

Trade-off thinking. Every cost reduction costs something: cold storage adds first-play delay, deleting renditions adds re-encode work, aggressive codecs add CPU. Apply each only to the long tail, where the savings are real and few users notice.

Step 7: Bottlenecks and Failure Handling

Bottlenecks

  • Origin overload. Cause: a viral new video missing in every cache. Mitigation: request coalescing, origin shield, pre-warming, and rate limiting origin fetches.
  • Transcoding backlog. Cause: a spike in uploads or a slow encode stage. Mitigation: autoscale workers by queue depth, prioritize (short videos and verified creators first), publish the low renditions first.
  • Hot metadata. Cause: a trending video's record. Mitigation: cache it, plus a short in-process cache on each server.
  • Hot counters. Mitigation: windowed aggregation and counter splitting (Step 6.6).
  • Storage growth. Mitigation: lifecycle tiering and alerts on projected capacity, because 230 PB a year does not wait.
  • Upload spikes. Mitigation: object storage absorbs the bytes; throttle per-creator limits at the gateway.

Failures

  • Failed segment task. Retry it with exponential backoff and jitter (retries lesson). Tasks are idempotent, so retrying is safe. After 3 attempts, mark the task failed and send it to a dead-letter queue (DLQ).
  • Worker dies mid-task. Workers hold a lease (a time-limited claim) on a task and send heartbeats. If heartbeats stop, the lease expires and the task is handed to another worker.
  • Orchestrator crash. Task state lives in the database, so a new orchestrator instance reloads the DAG and continues; completed tasks are not repeated.
  • Poison video. A file that crashes the encoder every time (corrupt data, strange container, or a deliberately malicious file) must not block the queue or loop forever. Cap attempts; if different workers fail the same video, mark it FAILED with a reason, notify the creator, keep the original for debugging and alert engineers if the failure rate rises. Run decoders in a sandbox (an isolated environment with no access to the rest of the system), because video parsers have a history of security bugs.
  • Partial success. If 1080p fails but 360p to 720p work, publish with what we have and retry the missing rendition in the background. Players adapt to the renditions the manifest lists.
  • Upload service or chunk failure. The client resumes; nothing is lost because accepted chunks are durable.
  • Edge or CDN failure. DNS and the player fall back to another PoP or CDN. ABR players also retry a segment at a lower rendition.
  • Metadata DB node failure. Promote a replica; cached reads keep working meanwhile.
  • Zone failure. All tiers run in at least two zones; object storage replicates across zones.
  • Graceful degradation. Under overload, cap the top rendition, serve cached recommendations, or pause new transcodes for low-priority uploads, before touching playback.

Monitor: time to first frame (p50, p99), rebuffer ratio, CDN hit rate by tier, origin egress, transcoding queue depth and time from complete to READY, task failure and DLQ rates, upload success rate, view-stream lag.

Interview tip. Pick two failures and walk them through: "a transcode task fails" and "a viral video hits every cache cold". Say what the viewer or creator sees, what the system does automatically, and which metric would alert you.

Step 8: Final Design Walkthrough

Final Design
Architecture
BackgroundClientUpload servicechunked sessionsAPI + metadatagateway, cacheCDNedge + regionalRaw storeoriginalsMetadata DBshardedOrigin storesegmentsTranscode DAGparallel workersView streamplayer beaconsAggregatorscounts, searchCold storagelong-tail videovideofillage out

Solid arrows are synchronous requests. Dashed arrows are asynchronous or fallback paths.

Request flow

Upload: client, API (create session), chunks to the raw store, complete, transcoding job. Watch: client, metadata API (cached), manifest and segments from the CDN, with CDN misses filling from the origin store. View: beacon, stream, aggregators, counter store.

Data flow

Originals live in the raw object store and finished segments in the origin store (replicated, tiered to cold storage when unpopular). Metadata and task state live in the databases, partitioned by id. Segments flow origin, regional cache, edge, viewer. View events flow beacon, stream, aggregators, counters.

Background processing

Transcoding workers run the DAG. Aggregators count views, and a batch job produces authoritative counts. Lifecycle jobs move cold videos to cheaper storage. A cleanup job removes expired upload sessions. Indexers update search from metadata changes. Recommendation models train offline.

Critical design decisions

  1. Video bytes bypass our servers. Chunks go to object storage and playback comes from the CDN, because 20 Gbps in and 19 Tbps out cannot go through app servers.
  2. Resumable chunked upload, so flaky networks never restart a 500 MB transfer.
  3. A DAG of idempotent segment tasks, turning an hour of encoding into about a minute and making retries safe.
  4. Adaptive bitrate over HLS/DASH, so players choose quality and every request is a cacheable static file.
  5. Tiered CDN with request coalescing, so the origin sees about 1% of traffic.
  6. Asynchronous windowed view counting, because exact real-time counters would create hot rows.
  7. Lifecycle tiering and selective codecs, because storage and bandwidth are the main cost.

If time remains, discuss live streaming (segments produced continuously with 2-6 second latency, short manifest TTLs), DRM, multi-region metadata replication, and per-viewer quality prediction.

Common Interview Questions

Finished this lesson?

0 of 44 lessons done · 0% of the course