system designs

YouTube

4 deep dives · 2 follow-ups · updated Oct 15, 2026

1. Functional requirements

  1. Upload a video with a title and description.
  2. Watch a video.
  3. Search videos by title.

Below the line: comments, likes, recommendations, subscriptions, view counts, live streaming.

Scale: 1M uploads a day, 100M daily viewers, about 500M views a day, so 500 views per upload. The design is driven by streaming bytes out, about 5 Tbps, not by ingesting uploads.

2. Non-functional requirements

  1. Availability over consistency: a new video may appear seconds late
  2. Resumable uploads of files in the tens of GB
  3. Playback starts in under 2 s anywhere, with adaptive bitrate
  4. Reads scale to 500 views per upload

3. Core entities

  • Users
  • Videos: uploading → processing → ready | failed
  • Video files: the original, then segments and manifests per resolution

4. API routes

Auth is a header on upload; watch and search are public. Simple enough to start; the upload route turns into presigned chunks in the first deep dive and the watch route returns a manifest in the third.

Upload
POST /videos
body: title, description, file
returns: videoId

Watch
GET /videos/:videoId
returns: title, description, status, fileUrl for the player

Search
GET /videos/search
params: q, cursor, limit
returns: Video[]

5. High-level design

The simplest system that satisfies the three routes. One client, one gateway, one service per route, Postgres for metadata, S3 for the files. The deep dives change this picture.

Boxes, drawing order: client · gateway · upload service, video service, search service · Postgres · S3 beside upload, with the player reading from it.

High-level design

Data model:

Video   id, uploaderId, title, description, status, fileUrl

Postgres holds metadata only, one primary to start; the bytes live in S3 and never pass through the database. The deep dives shard the metadata and add a search index, both allowed to lag by seconds.

6. Deep dives

Order in the room: 6.1 must · 6.3 if time · 6.2 and 6.4 one line each, only if asked. Each deep dive opens with three spoken sentences: Problem, Pick, Cost. Everything under them is what you say when the interviewer digs.

6.1 Processing: presigned uploads, transcoding DAG

Problem. A tens-of-GB upload streams through the upload service and is then served raw: one resolution, one codec, one huge file that stalls on a phone, and transcoding a 2-hour video inside the request would take hours. Pick. Presigned 16 MB chunk uploads straight to S3, then an async DAG of transcoding tasks run by an orchestrator, one task per 10-second piece per resolution, pulled from a queue by an autoscaled worker pool, with the video flipping to ready when the packager writes the manifest. Cost. The video goes live minutes after upload, which availability over consistency allows, and an orchestrator plus a queue to operate. Rejected: transcoding in the request, because a 2-hour video outlives any request and the pieces are parallel work.

Draw: S3 takes the upload directly; an orchestrator, a task queue and a worker pool sit between S3 raw and S3 published.

Routes (replace POST /videos from section 4):

POST /videos { title, description, sizeBytes } → { videoId, chunkUrls[] }   presigned S3 PUTs, 16 MB each, expire in 1 h
POST /videos/:videoId/complete                 → 202, status: processing

6.1 changed fragment

Flow

  1. Upload: POST /videos inserts the row (status: uploading) and returns presigned URLs; the client PUTs 16 MB chunks in parallel to raw/{videoId}/{n}, then calls complete. Status → processing, and the orchestrator starts the DAG for that videoId.
  2. Split and fan out: ffmpeg cuts the original at keyframes into ~10 s pieces, then the orchestrator enqueues one transcode task per piece per resolution (240p to 4K), plus audio and thumbnails. A 2-hour video becomes ~4,000 tasks that run in parallel.
  3. Workers: an autoscaled pool pulls tasks from the queue (SQS), reads each input from S3, writes the output to a deterministic key (work/{videoId}/{res}/{piece}) and acks. The orchestrator records each task as done in the database and starts a step only when all its inputs exist.
  4. Package and publish: per resolution, the packager cuts 4 s segments and writes a playlist, then the master manifest and thumbnails, all under videos/{videoId}/. One update sets status = ready and manifestUrl; the video is now watchable.

Follow up: a transcoding job fails halfway through a 2-hour video. What happens?

Answer: Only the failed task reruns: a worker that dies stops heartbeating, so the queue redelivers its task to another worker after the visibility timeout. Tasks are idempotent, with deterministic output keys, so a rerun just overwrites the same file. Finished tasks stay recorded as done, so the DAG resumes from the failure, not from the start. After 3 retries with backoff the task goes to a dead-letter queue, the video moves to failed and the uploader is notified; the raw upload stays in S3 for a reprocess.

6.2 Resumable uploads: fingerprint and chunk table

Problem. A 50 GB upload takes hours; after a dropped connection the client has no record of which chunks landed and starts over. Pick. Fingerprint the file so a restart finds the same videoId, and keep a chunk table that S3 event notifications fill in, so the client resumes from the first chunk S3 itself has not confirmed. Cost. One row per chunk and a lifecycle rule to delete abandoned uploads after 7 days; the completion update is conditional so the DAG starts exactly once.

6.2 changed fragment

6.3 Playback: HLS segments behind a CDN

Problem. The player downloads one file at one bitrate from one S3 region: it rebuffers on slow networks, underplays on fast ones, and the first frame takes seconds far from the region. Pick. HLS adaptive bitrate: every rendition cut into 4-second immutable segments with playlists and a master manifest on S3 behind a CDN, the player starting low and climbing as it measures throughput, switching at segment boundaries with no server session. Cost. About six renditions stored per video, and a watch that is now dozens of small requests instead of one. Rejected: progressive download, because the player cannot change bitrate mid-file and only one region serves it.

Draw: a CDN between the player and S3 published; the watch route returns a manifest URL.

Routes (change GET /videos/:videoId; the player then reads plain files from the CDN):

GET /videos/:videoId → Video { title, description, status, manifestUrl, thumbnailUrl }
GET cdn/videos/{videoId}/master.m3u8        → one line per rendition: bandwidth, resolution, playlist URL
GET cdn/videos/{videoId}/720p/index.m3u8    → that rendition's segment URLs, 4 s each
GET cdn/videos/{videoId}/720p/seg_00042.m4s → 4 s of 720p video

6.3 changed fragment

Flow

  1. GET /videos/:videoId returns manifestUrl, and the player fetches the master manifest from the CDN: one entry per rendition, from 240p at 0.4 Mbps to 4K at 20 Mbps.
  2. Start: the player picks a low rendition and fetches its playlist and first segment, so the first frame shows in under 2 s, then climbs as it measures throughput.
  3. Adapt: after every segment it takes the highest rendition whose bitrate fits in ~80% of measured throughput, and drops a level when the buffer falls under 10 s. Every rendition is cut on the same keyframes, so a switch at a segment boundary is seamless.
  4. Seek: the player jumps straight to segment ⌊t / 4 s⌋ in its current playlist, no range requests into a 10 GB file. Manifests and segments are immutable files under videos/{videoId}/, so the CDN caches them at the edge.

6.4 Reads at 500 to 1: cache every layer

Problem. 500M views a day read metadata from one database, every search scans the title column, and every edge miss pulls bytes from one region. Pick. The CDN for bytes with an origin shield, Redis for video metadata, Postgres sharded by videoId with replicas, and Elasticsearch fed by change data capture for title search. Cost. Replicas and the index lag by seconds, which the first requirement allows; view counts go through a Redis counter flushed every minute, never a row write per view.

6.4 changed fragment

Final design

Final design

Trade-offs, the two to say:

  • Async transcoding DAG over transcoding in the upload request: a 2-hour video takes far longer than any request and the pieces run in parallel; the cost is a video that goes live minutes later.
  • HLS segments on a CDN over progressive download: the player switches bitrate every 4 s and any edge serves an immutable file; the cost is storing about six renditions of every video.

Study only, not for the room: full flows for 6.2 and 6.4, and the 6.4 follow-up.

6.2 flow

Routes (replace POST /videos and /complete from 6.1):

POST /videos { title, description, sizeBytes, fingerprint } → { videoId, chunkUrls[] }   same videoId if this user already started this file
GET  /videos/:videoId/chunks                               → { missing: chunkIndex[], chunkUrls[] }
  1. Start: the client fingerprints the file (SHA-256 of its size plus first and last MB) and splits it into 16 MB chunks. POST /videos checks the unique (uploaderId, fingerprint): an unfinished upload returns its videoId, otherwise it creates the video and one Chunk row per index, pending.
  2. Upload: each chunk is a PUT to raw/{videoId}/{n} with its Content-MD5, so S3 rejects a corrupted chunk. S3 emits an ObjectCreated event per chunk to SQS; the upload service marks Chunk(videoId, n) uploaded only if still pending, then increments uploadedCount.
  3. Resume: after a drop or a restart, the client fingerprints again, gets the same videoId, calls GET /videos/:videoId/chunks and uploads from the first missing chunk with fresh presigned URLs.
  4. Finish: the update that brings uploadedCount to totalChunks also moves the video uploading → processing (conditional on status = uploading), so the 6.1 DAG starts exactly once. An S3 lifecycle rule deletes the chunks of uploads abandoned for 7 days.

6.4 flow and follow-up

  1. Bytes: the CDN serves segments, manifests and thumbnails from edges near the viewer, with S3 as origin behind an origin shield. Files are immutable (Cache-Control: max-age=31536000), so popular videos are almost all edge hits.
  2. Metadata: the video service reads video:{videoId} from Redis (TTL 1 h); a miss reads a replica and refills the key. A title edit or status change deletes it.
  3. Database: Postgres sharded by hash(videoId), each shard a primary plus read replicas; a watch is one single-shard lookup, and Chunk rows live on their video’s shard. Replica lag can show a new video seconds late, which NFR 1 allows.
  4. Search: a title query can’t use the shard key, so CDC (Debezium → Kafka) feeds an Elasticsearch videos index, and the search service queries it with a fuzzy match on title. The index lags by seconds.

Follow up: a video goes viral, 20M views in its first hour. What breaks first?

Answer: Not the bytes at steady state: once every edge holds the segments, the CDN serves them. The risk is the first minutes, when hundreds of edges miss the same segment at once; request collapsing at each edge and the origin shield turn that into one S3 GET per segment. Its metadata is one hot Redis key, so the video service also caches it in-process for 5 s, one Redis read per server per 5 s. View counts never write the video row per view: INCR views:{videoId} in Redis, flushed to the database every minute. For a scheduled premiere, pre-warm the CDN by pushing the first segments to edges ahead of time.