Design Video Streaming

How to design video upload and playback: resumable uploads, transcoding, adaptive bitrate streaming, CDN delivery, and the follow-ups interviewers ask.

Case study29 minLesson 2 of 8
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A video streaming service lets users upload videos and lets other users watch them on demand on phones, browsers and TVs with very different screens and network speeds. Interviewers ask it because the video files are enormous compared with the records that describe them, so the design must keep video bytes away from the parts of the system that handle small records.

The design therefore has two halves. A small system handles titles, upload sessions and processing status. A much larger system stores, converts and delivers the video files using object storage and a CDN. The steps below follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a video streaming service.

You

Do you want uploads and on-demand playback only, or live streaming as well? And are search and recommendations part of the question?

Interviewer

Uploads and on-demand playback only.

You

How many videos are uploaded per day, how long are they, and how much do people watch?

Interviewer

About 100,000 uploads a day, 10 minutes long on average. There are 50 million daily viewers, and each watches about 30 minutes a day.

You

Then playback is the main system. A video should start within about 2 seconds and rarely stall, and an upload must survive a bad mobile connection. I expect most of the cost to be bandwidth, so I will design around the CDN.

Functional requirements:

  • Users can upload a video, and an interrupted upload can be resumed.
  • Each upload is converted into formats that every device can play, and playback adapts to the viewer's network speed.
  • Each video has a title, a processing status and a view count.

Non-functional requirements:

  • Playback starts in about 2 seconds, stalls rarely, and is highly available.
  • A video is ready within a few minutes of the upload finishing, and an uploaded video is never lost.
  • Metadata may be eventually consistent, so a view count can lag by a few seconds.

Out of scope: live streaming, search, recommendations, comments and copy protection.

Estimate the scale

  • The average number of concurrent viewers is 50 million × 30 minutes ÷ 1,440 minutes in a day, which is about 1 million. An evening peak of twice the average gives 2 million.
  • Uploads arrive at 100,000 ÷ 86,400 seconds, about 1.2 a second. If an original is 1 GB, that is 100 TB of new originals a day, or about 1.2 GB/s of incoming data.
  • Each video is converted into five qualities from 240p to 1080p, with bitrates of 0.4, 0.8, 1.5, 3 and 6 Mbit/s. Together they total 11.7 Mbit/s, so a 10-minute video produces 11.7 × 106 × 600 ÷ 8 bytes, about 0.88 GB. That is about 88 TB of converted copies per day.
  • Encoding all five qualities takes about 10 CPU-minutes per minute of video (an assumption that depends on the codec). That is 100,000 × 10 × 10 = 10 million CPU-minutes a day, so about 6,900 cores are busy on average.
  • Originals and copies add up to about 188 TB a day, or roughly 69 PB a year before replication. The metadata is tiny by comparison, about 36.5 GB a year.
Estimate: Playback bandwidth

At the average of 1 million concurrent viewers, how much video leaves the system each second?

You know
  • 1 million viewers at any moment
  • Average bitrate 4 Mbit/s (phones and TVs mixed)

Show the working
  1. 106 × 4 × 106 bit/s = 4 × 1012 bit/s = 4 Tbit/s
  2. 4 × 1012 ÷ 8 = 5 × 1011 B/s = 500 GB/s
  3. At the 2x peak this is 1 TB/s

Estimate 500 GB/s (anything from 150 GB/s to 1.5 TB/s is a good answer)

This has to be served from CDN edges close to the viewers.

Your turn: Define the API

Write the upload endpoints so that a connection that drops at 90% does not force the user to start over, and write the calls the player makes to play a video.

Compare with a model answer

The client starts an upload session, sends numbered chunks and calls complete, and a status call lists the arrived chunks so it can resume. Playback is one metadata call followed by plain file requests for a manifest and segments, which a CDN can cache.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
POST /v1/uploads   { "filename", "size_bytes", "sha256" }
  201 { "upload_id", "chunk_size": 8000000, "chunk_urls": [signed URLs...] }
PUT  <signed chunk URL n>      (8 MB of bytes, goes straight to object storage)
  200 { "etag" }    400 checksum mismatch
GET  /v1/uploads/{id}        -> { "received": [0..111] }   resume from here
                                (the API asks storage which parts landed)
POST /v1/uploads/{id}/complete      safe to repeat: same video_id
  202 Accepted { "video_id", "status": "processing" }
  409 Conflict   chunks missing
 
GET  /v1/videos/{id}  -> { title, status, duration_s, "manifest_url" }
GET  cdn/v/{id}/master.m3u8             manifest: the qualities on offer
GET  cdn/v/{id}/720p/seg_00042.ts       one 4-second segment

Routing 1.2 GB/s of uploads through the API servers would tie each server up for minutes per request. Instead, the API gives the client signed URLs, which are short-lived links that allow the client to write one chunk directly to object storage.

The cost is that the API never sees the bytes. At complete, object storage confirms that every part arrived, and the first transcoding job verifies the sha256. The complete call returns 202 rather than 200 because the video is not playable yet. Calling it twice returns the same video_id, so a retry is safe.

Your turn: Model the data

List the records for videos, upload sessions and processing work, and decide which of them belong in a database and which are files.

Compare with a model answer

Video rows, upload sessions and transcoding jobs are small records for a database. Originals, segments and manifests are files for object storage, keyed by video ID.

Model the data

Metadata tables
videos:   video_id BIGINT PRIMARY KEY, owner_id BIGINT, title TEXT,
          status TEXT,          -- uploading | processing | ready | failed
          duration_s INT, renditions TEXT, jobs_left INT, created_at TIMESTAMP
uploads:  upload_id, video_id, size_bytes, storage_upload_id, expires_at
          -- which parts arrived is asked of object storage, not stored here
jobs:     job_id, video_id, segment_no INT, rendition TEXT,
          status TEXT, attempts INT, lease_until TIMESTAMP
 
-- object storage keys
originals/{video_id}
v/{video_id}/master.m3u8, v/{video_id}/{rendition}/index.m3u8
v/{video_id}/{rendition}/seg_{n}.ts

The metadata is small, relational and read-heavy, so a relational database with read replicas fits. It also provides an atomic counter, which the transcoding step needs. Each finished job decrements jobs_left, and the job that brings it to 0 writes the manifests and then sets the status to ready.

View counts are not written to the videos row on every view, because a viral video would turn that row into a hot spot. They are batched through a queue, as in the click counting of the URL shortener.

Your turn: High-level design

Draw the upload path and the playback path, and mark which boxes handle video bytes.

Compare with a model answer

Video bytes travel from the client to object storage, to the transcoders and back, and then through the CDN to viewers. The API, the database and the job queue only handle IDs and status.

High-level design

Video bytes go through object storage and the CDN, while the API and database handle only small records. Transcoding runs from a job queue.Phone, TV, browser to CDN edges (segments); Phone, TV, browser to API servers (metadata, upload); Phone, TV, browser to Object storage (PUT chunks); CDN edges to Object storage (miss); API servers to Video metadata; API servers to Object storage (join parts); API servers to Transcode jobs (enqueue), asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage (read, write); Transcoders to Video metadata (status).Phone, TV,browserCDN edgesAPI serversObject storageVideo metadataTranscode jobsTranscoderssegmentsmetadata, uploadPUT chunksmissjoin partsenqueueread, writestatus

request and replyasynchronous message

Video bytes go through object storage and the CDN, while the API and database handle only small records. Transcoding runs from a job queue.
From upload to first playUse the arrows or ← → keys
  1. From upload to first play, step 1Phone, TV, browser to CDN edges; Phone, TV, browser to API servers; Phone, TV, browser to Object storage; CDN edges to Object storage; API servers to Video metadata; API servers to Object storage; API servers to Transcode jobs, asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage; Transcoders to Video metadata.Phone, TV,browserCDN edgesAPI serversObject storageVideo metadataTranscode jobsTranscoders
    chunks
    0 / 125

    1The phone starts a 1 GB upload. The API records a session and returns 125 signed URLs, one per 8 MB chunk. The phone sends them straight to object storage.

  2. From upload to first play, step 2Phone, TV, browser to CDN edges; Phone, TV, browser to API servers; Phone, TV, browser to Object storage; CDN edges to Object storage; API servers to Video metadata; API servers to Object storage; API servers to Transcode jobs, asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage; Transcoders to Video metadata.Phone, TV,browserCDN edgesAPI serversObject storageVideo metadataTranscode jobsTranscoders
    chunks
    112 / 125

    2After 112 chunks the train enters a tunnel and the connection drops. Only the 4 chunks in flight are lost, not the 900 MB already stored.

  3. From upload to first play, step 3Phone, TV, browser to CDN edges; Phone, TV, browser to API servers; Phone, TV, browser to Object storage; CDN edges to Object storage; API servers to Video metadata; API servers to Object storage; API servers to Transcode jobs, asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage; Transcoders to Video metadata.Phone, TV,browserCDN edgesAPI serversObject storageVideo metadataTranscode jobsTranscoders
    chunks
    125 / 125

    3When the connection returns, the phone asks the API which chunks arrived, and the API asks object storage. The phone then sends only the 13 missing chunks.

  4. From upload to first play, step 4Phone, TV, browser to CDN edges; Phone, TV, browser to API servers; Phone, TV, browser to Object storage; CDN edges to Object storage; API servers to Video metadata; API servers to Object storage; API servers to Transcode jobs, asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage; Transcoders to Video metadata.Phone, TV,browserCDN edgesAPI serversObject storageVideo metadataprocessingTranscode jobsTranscoders
    chunks
    125 / 125

    4The phone calls complete. Object storage checks and joins the 125 parts, and the API marks the video processing and answers 202.

  5. From upload to first play, step 5Phone, TV, browser to CDN edges; Phone, TV, browser to API servers; Phone, TV, browser to Object storage; CDN edges to Object storage; API servers to Video metadata; API servers to Object storage; API servers to Transcode jobs, asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage; Transcoders to Video metadata.Phone, TV,browserCDN edgesAPI serversObject storageVideo metadataTranscode jobs750 jobsTranscoders
    jobs left
    750

    5A split job verifies the whole-file checksum, cuts the video into 150 four-second pieces and enqueues 150 × 5 = 750 encode jobs, which many transcoders then run in parallel.

  6. From upload to first play, step 6Phone, TV, browser to CDN edges; Phone, TV, browser to API servers; Phone, TV, browser to Object storage; CDN edges to Object storage; API servers to Video metadata; API servers to Object storage; API servers to Transcode jobs, asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage; Transcoders to Video metadata.Phone, TV,browserCDN edgesAPI serversObject storageVideo metadataTranscode jobslease expiredTranscodersdown
    jobs left
    37

    6A transcoder dies mid-job. When its 2-minute lease expires, another worker redoes that piece and replaces the same output file.

  7. From upload to first play, step 7Phone, TV, browser to CDN edges; Phone, TV, browser to API servers; Phone, TV, browser to Object storage; CDN edges to Object storage; API servers to Video metadata; API servers to Object storage; API servers to Transcode jobs, asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage; Transcoders to Video metadata.Phone, TV,browserCDN edgesAPI serversObject storageVideo metadatareadyTranscode jobsTranscoders
    jobs left
    0

    7The last job takes jobs_left to 0. That worker writes the manifests first and then sets the video to ready, so a ready video always has its manifests.

  8. From upload to first play, step 8Phone, TV, browser to CDN edges; Phone, TV, browser to API servers; Phone, TV, browser to Object storage; CDN edges to Object storage; API servers to Video metadata; API servers to Object storage; API servers to Transcode jobs, asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage; Transcoders to Video metadata.Phone, TV,browserCDN edgesAPI serversObject storageVideo metadataTranscode jobsTranscoders

    8A viewer opens the video. The API returns the title and the manifest URL, and the player fetches everything else from the nearest CDN edge.

  9. From upload to first play, step 9Phone, TV, browser to CDN edges; Phone, TV, browser to API servers; Phone, TV, browser to Object storage; CDN edges to Object storage; API servers to Video metadata; API servers to Object storage; API servers to Transcode jobs, asynchronous; Transcode jobs to Transcoders, asynchronous; Transcoders to Object storage; Transcoders to Video metadata.Phone, TV,browserCDN edgesmiss, now cachedAPI serversObject storageVideo metadataTranscode jobsTranscoders

    9The edge does not have the segment yet, so it fetches it from object storage once and then serves nearby viewers from its copy.

1 / 9

Deep dives

Chunked, resumable upload

A single PUT of a 1 GB file over a mobile network often fails partway and loses everything sent so far. Splitting the file into chunks, each uploaded and checksummed as its own request, means a failure costs only the chunks in flight.

Receiving chunks in the API servers would route 1.2 GB/s through them, so the better choice is the multipart upload feature of object storage. The API starts a multipart upload and returns one signed URL for each part, the client uploads the parts in any order, and a final call asks storage to join them. Storage keeps the list of received parts, so resuming is a single question to storage and the database holds no part list.

A 256 KB chunk means 4,000 requests for a 1 GB file, each paying a round trip, while a 100 MB chunk takes minutes to redo on a slow phone. A size between 4 and 16 MB works well, and 8 MB is a reasonable pick.

Transcoding as a queue of jobs

Phones record in formats many devices cannot play, so each upload is converted into five qualities. This costs about 100 CPU-minutes for a 10-minute video, so the question is how to divide it across machines.

The simplest option is one machine per video, which needs no splitting or joining but takes more than an hour and a half and loses all the work in a crash near the end. A second option is one job for each quality, which runs five machines in parallel, but the 1080p encode does most of the work and sets the total time.

The third option is to cut the video into segments of about 4 seconds on keyframe boundaries and run one job for each segment and quality. A 10-minute video gives 150 segments and 750 jobs of about 8 CPU-seconds each, and hundreds can run at once. With 150 workers free, the encoding takes about 40 seconds, plus time for queueing, splitting and the final step. The cost is a split step, the jobs_left counter, and cuts only on keyframes.

How to run the transcoding work
OptionGood atBad atPick it when
One machine per videoIt needs no splitting or joining.A crash near the end means starting over.Use it only when videos are very short.
One job per qualityFive machines work in parallel.The 1080p job sets the total time.Use it for short videos.
One job per segment and quality Usual defaultA failure redoes only 4 seconds of video.It needs a split step and a counter.Use it for long videos that must be ready within minutes.

The jobs must be safe to run twice, because a queue delivers each job at least once. Two rules achieve this. Output files have fixed names, so a job that runs twice overwrites the same file. A job decrements jobs_left only when its own row moves from running to done, so it cannot be counted twice. This is idempotency: the job may run more than once but has one effect. The jobs run from a queue.

Adaptive bitrate streaming

A fixed-quality file stalls on a slow connection and wastes bandwidth on a fast one. Adaptive bitrate streaming solves this by cutting every quality into the same 4-second segments and publishing a manifest, a small text file that lists the available qualities and the URL of every segment. HLS and DASH are the two common manifest formats.

The player does the adapting. Before each segment, it checks its recent download speed and how many seconds of video it has buffered, and it requests the highest quality it expects to download before the buffer runs out. If the network slows down, the viewer sees a softer picture for a few seconds instead of a frozen one.

The player picks a quality for each segmentUse the arrows or ← → keys
  1. ladder (Mbit/s)
    00.4
    10.8
    21.5
    33
    46
    measured
    ?
    buffer
    0 s

    1The player starts at a low quality so the first frame appears quickly. At 1.5 Mbit/s, the first 4-second segment is 0.75 MB.

  2. ladder (Mbit/s)
    00.4
    10.8
    21.5
    33
    46
    measured
    12 Mbit/s
    buffer
    4 s

    2The segment arrives in 0.5 seconds, a speed of 12 Mbit/s. The buffer is still thin, so the player moves up only one step, to 3 Mbit/s, and reaches 6 Mbit/s as the buffer grows.

  3. ladder (Mbit/s)
    00.4
    10.8
    21.5
    33
    46
    measured
    2 Mbit/s
    buffer
    16 s

    3In a lift the speed falls to 2 Mbit/s. A 6 Mbit/s segment would take 12 seconds to download, so the player drops to 1.5 Mbit/s and plays from its buffer.

  4. ladder (Mbit/s)
    00.4
    10.8
    21.5
    33
    46
    measured
    9 Mbit/s
    buffer
    18 s

    4When the doors open, the player climbs back one step at a time, so that a short burst of speed does not cause a stall.

1 / 4

Because the logic is in the player, the servers hold plain static files with identical URLs for every viewer, and a CDN can cache every segment. Shorter segments let the player react faster but create more requests and compress slightly worse, so about 4 seconds is a common choice.

CDN delivery and cost

The playback estimate of 500 GB/s is more than any single location can serve. A CDN keeps copies of segments on edge servers close to viewers, and only a miss travels to the origin, which is object storage.

The hit rate decides the cost. At 95% the origin serves the other 5% of 500 GB/s, which is 25 GB/s, and at 99% it serves 5 GB/s.

A few popular videos account for most views and stay in every edge cache. Rarely watched videos miss almost every time, so a second tier of larger regional caches between the edges and the origin answers many misses without reaching storage.

Segment URLs must be identical for every viewer, because a per-user token in the URL would give each viewer its own cache entry.

Bottlenecks and failures

At 10 times the viewing, there are 10 million concurrent viewers and 5 TB/s of traffic, so delivery is the first thing to break. The fixes are more CDN capacity, a higher hit rate and a regional cache tier that protects the origin. At 10 times the uploads, transcoding needs about 70,000 busy cores, which calls for an elastic worker fleet with the queue absorbing bursts. The metadata database is affected last.

When this failsWhat happensWhat you do
A CDN edgePlayers time out on a segment.DNS or anycast routing sends them to the next nearest edge, and the player's buffer hides the switch.
Object storage in one regionEdge misses and uploads fail there.Replicate segments to a second region and fail over; edges keep serving cached segments.
A transcoderThe job it was running stops making progress.The lease on the job expires, and another worker redoes that one piece.
The job queueNew videos stay in the processing state.Playback of existing videos is not affected. Replicate the queue and alert on the age of its oldest job.
The metadata database primaryUploads cannot complete, but playback continues from the replicas.Promote a replica. Clients retry complete, which is safe to repeat.

What a strong answer sounds like

LevelWhat the answer does
JuniorStores videos in object storage with a CDN in front, and adds transcoding only when asked.
Mid-levelEstimates the bandwidth, uses chunked uploads and a transcoding queue, and explains manifests and segments.
SeniorSeparates metadata from bytes from the start, transcodes per segment with idempotent jobs, explains why adaptation in the player makes the CDN effective, and reasons about cost through hit rate.
Defending the transcoding designStrong answer
Interviewer

Why do you split videos into segments for transcoding? It adds a join step.

You

A 10-minute video needs about 100 CPU-minutes to encode. On one machine that is more than an hour and a half, and a crash near the end means starting over. As 750 jobs of about 8 CPU-seconds each, it finishes in minutes, and a failure redoes only 4 seconds of video. We need segments for playback anyway, so the join step only consists of writing the manifest.

Follow-up questions

How do you count views?

The player sends a view event after a few seconds of watching. The events go through a queue to a worker that adds them up in batches and updates the stored count, so the count lags slightly but a viral video does not create a hot row.

How do you stop people from downloading paid videos?

Signed URLs that expire stop a link from being shared for long. The edge checks the signature but leaves it out of the cache key, so caching still works. They do not stop a user from saving the segments, so real protection needs encrypted segments and a licence key for each viewer, called digital rights management, which is usually bought rather than built.

What happens when a creator deletes a video?

The API marks the video as deleted and stops returning it, which makes it disappear for viewers immediately. A background job then purges the segments from the CDN and deletes the objects from storage. Short-lived signed URLs limit how long a copied link keeps working.

How do you make playback start quickly?

The player starts with a low quality so that the first small segment downloads fast, and it moves up once its buffer fills. The manifest and the first segments are served from a nearby CDN edge, so the start time depends mostly on the first segment being small and already cached.

How do you reduce the cost of storing videos nobody watches?

Most of the 69 PB a year is converted copies of videos that are rarely watched. Old or unpopular videos can move to a cheaper storage class, and the highest and lowest qualities of a long-tail video can be deleted or created only when someone first asks for them. The cost is that the first viewer of such a video waits for the conversion.

Self-review: video streaming0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure