Case studies

Design video streaming

Take an uploaded video, turn it into segments at several qualities, and play it smoothly on any network. Delivery bandwidth dominates the cost, so the CDN and the encoding ladder drive the design.

Case study25 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

When YouTube launched in 2005, a video was essentially one file at one quality, downloaded from start to finish while it played. That design is simple, and it fails in a predictable way. If the viewer’s connection is slower than the video’s bitrate, playback stalls while the buffer refills. If the connection is much faster, the viewer watches a worse picture than they could have had. A phone on a train moves between both situations every few minutes.

The other approach of that period used dedicated streaming servers that held a session per viewer and pushed video over a special protocol. It adapted better but scaled poorly, because every viewer needed server state and nothing could be cached by ordinary web infrastructure.

Apple’s HTTP Live Streaming, introduced in 2009, took a third path that the industry has followed since: cut the video into small files at several qualities, serve them over plain HTTP, and let the player choose. MPEG-DASH standardised the same idea in 2012.

An interviewer asking this question wants to see three things: that you treat upload and processing as an asynchronous pipeline, that you understand why segmented delivery makes a CDN do the heavy lifting, and that you notice where the money goes.

Requirements

Functional

  • A creator uploads a video file of up to several gigabytes.
  • The service processes it into formats that play on phones, browsers and televisions.
  • A viewer watches on demand, with quality that adapts to their network, and can seek.
  • Each video has metadata: title, description, thumbnail, duration, owner.
  • Each video shows a view count.

Out of scope unless asked: live streaming, recommendations and search, comments, digital rights management, adverts.

Non-functional

  • Start-up time: first frame within about 2 seconds.
  • Smooth playback: rebuffering should be rare. Viewers tolerate lower quality better than stalls.
  • Processing time: a typical upload is watchable within a few minutes.
  • Durability: an uploaded source file is never lost.
  • Availability: 99.99% for playback. Uploads can tolerate less.
  • Scale: 10 million daily viewers, 100,000 uploads a day.

Capacity estimates

Quantity Working Result
Watch time 10M viewers x 30 minutes 5 million hours a day
Egress 5M hours x 1.125 GB (2.5 Mbit/s average) about 5.6 PB a day
Peak bandwidth 208,000 average concurrent x 3, at 2.5 Mbit/s about 1.6 Tbit/s
CDN cost 5.6M GB x $0.01 (assumed contract price) about $56,000 a day, $20M a year
Storage per video 5 minutes: 250 MB source + 400 MB of renditions about 650 MB
New storage 100,000 uploads x 650 MB 65 TB a day, about 24 PB a year
Transcoding 500,000 minutes x 10 core-minutes each (assumed) about 3,500 cores on average

The 400 MB comes from an illustrative H.264 ladder of 0.4, 0.8, 1.5, 3 and 5 Mbit/s (240p to 1080p), which totals 10.7 Mbit/s, over 300 seconds. The price per gigabyte and the encoding cost per minute are assumptions that vary several-fold in practice, so state them as such.

The conclusion is that delivery dominates. Petabytes leave the system every day, and that bill is larger than storage and compute together. Design decisions should be judged first by what they do to egress. Uploads are a much smaller, bursty batch workload that needs elastic compute. Metadata is tiny by comparison.

API

POST /v1/videos
{ "title": "Harbour at dawn", "size_bytes": 262144000, "content_type": "video/mp4" }

201 Created
{ "video_id": "v_9f2", "upload": { "upload_id": "...", "part_size": 8388608, "part_urls": ["https://uploads.example.com/..."] } }
POST /v1/videos/v_9f2/complete        { "parts": [ { "number": 1, "etag": "..." } ] }     -> 202, status "processing"

GET  /v1/videos/v_9f2                 -> { "status": "ready", "duration_s": 300, "view_count": 1204,
                                           "manifest_url": "https://cdn.example.com/v/v_9f2/master.m3u8" }

POST /v1/videos/v_9f2/views           { "session_id": "...", "watched_s": 30 }

The API hands out URLs and records state. The upload goes to object storage and the playback comes from the CDN.

Data model

Store Key Contents
videos video_id owner, title, description, status, duration, renditions, manifest path
transcode_tasks video_id, task_id type, rendition, chunk, status, attempt, lease expiry, dependencies
view_counts video_id (and by hour) totals written by the aggregators

status moves through uploading, processing, ready or failed. Metadata is small and relational, read far more than written, so a replicated SQL database behind a cache is enough.

Objects follow a predictable layout, which matters because task outputs are addressed by name:

raw/v_9f2/source.mp4
out/v_9f2/720p/seg_00007.m4s
out/v_9f2/720p/playlist.m3u8
out/v_9f2/master.m3u8

High-level architecture

Video streaming reference architecture13 components: CDN, Encoded video store, Raw upload store, Transcode workers, Player and uploader, Workflow orchestrator, Task queue, Video API, Metadata store, View events, Metadata cache, View aggregators, View counts. Connections: Player and uploader to CDN (watch); CDN to Encoded video store; Player and uploader to Raw upload store (multipart upload); Player and uploader to Video API; Video API to Metadata store; Video API to Metadata cache (read through); Video API to Workflow orchestrator (start workflow); Workflow orchestrator to Metadata store (status); Workflow orchestrator to Task queue; Task queue to Transcode workers; Raw upload store to Transcode workers (source chunks); Transcode workers to Encoded video store (segments, playlists); Video API to View events (view beacons); View events to View aggregators; View aggregators to View counts.CDNsegments and playlistsEncodedvideo storeorigin for the CDNRaw uploadstoreobject storageTranscodeworkersPlayer anduploaderWorkfloworchestratortask graph per videoTask queueVideo APIMetadata storeView eventsstreamMetadata cacheViewaggregatorsView countswatchmultipart uploadread throughstart workflowstatussource chunkssegments, playlistsview beacons
Video streaming reference architecture

Upload. The client asks the API for an upload session and sends the file in parts directly to the raw upload store. When it calls complete, the API marks the video processing and starts a workflow.

Process. The orchestrator builds the task graph for this video and puts runnable tasks on the queue. Transcode workers take tasks, read the source from the raw store, and write segments and playlists to the encoded store. When the last task finishes, the orchestrator sets the status to ready.

Watch. The player fetches metadata from the API (served mostly from cache), then requests the manifest and segments from the CDN. On a miss the CDN pulls from the encoded store and caches the result.

Count. The player reports progress with a beacon. The API appends it to a view-event stream. Aggregators remove repeats from the same session, filter obvious automation, sum per video in short windows and write totals to the counts store. The page shows a cached total that lags by seconds to minutes. Incrementing a row per play would make a popular video a hot row.

Deep dives

Upload and the transcoding pipeline

Resumable upload. A 2 GB file over a mobile connection will be interrupted. With multipart upload the client sends fixed-size parts, several in parallel, each to its own pre-signed URL. A failed part is retried alone, and the app can resume after a restart by asking which parts exist. On S3, for example, parts are between 5 MiB and 5 GiB and an upload may have up to 10,000 of them. Add a lifecycle rule that discards incomplete uploads after a few days, or abandoned parts are stored and billed indefinitely.

The pipeline is a graph. Processing a video is not one job:

  1. Probe: check the file really is video, read its codec, resolution and duration, and reject what is unsupported.
  2. Split: cut the source into chunks of about a minute at keyframes.
  3. Encode: for every chunk and every rendition, produce the output. These tasks are independent.
  4. Package: assemble encoded chunks into segments and write a playlist per rendition and the master playlist.
  5. Side tasks: thumbnails, and anything else such as captions or content checks, in parallel with encoding.
  6. Publish: mark the video ready.

Chunking is what makes long videos tractable. A two-hour upload becomes 120 chunks. With five renditions that is 600 encode tasks, each taking a minute or two, and elapsed time depends on the number of workers, not the length of the video. If a worker dies, one chunk is repeated.

Tasks must be idempotent. Each writes to an output key derived from the video, rendition and chunk, so running it twice overwrites the same object. A worker holds a lease on its task and renews it while working. If the lease expires, the task returns to the queue. A task that fails repeatedly marks the video failed with a reason and goes to a dead-letter queue.

Elastic workers. Uploads are bursty and encoding is CPU-bound. Scale the worker pool on queue depth. Because tasks are short and retriable, cheap interruptible instances suit them well.

Publish early. Encode the lowest rendition first and make the video playable as soon as it exists, then add higher qualities to the manifest as they complete.

Adaptive bitrate streaming

Each rendition is cut into segments of a few seconds. Apple’s guidance for HLS is six seconds. A manifest describes what exists. In HLS, a master playlist lists the renditions with their resolution and bandwidth, and each rendition has its own playlist of segment URLs. DASH describes the same structure in one XML file.

Adaptive bitrate streaming, one segment at a time6 components: Master playlist, 1080p segments, Video player, CDN edge, 720p segments, 360p segments. Connections: Video player and CDN edge; CDN edge to Master playlist; CDN edge to 1080p segments; CDN edge to 720p segments; CDN edge to 360p segments.Master playlistlists every quality1080p segmentsabout 5 Mbit/sVideo playerCDN edge720p segmentsabout 3 Mbit/s360p segmentsabout 0.8 Mbit/s

Step 1 of 8

A stored video is not one file. It is cut into segments a few seconds long, and every segment exists at several qualities. A small text file, the master playlist, lists the qualities and the bandwidth each one needs.

Read the steps as text
  1. A stored video is not one file. It is cut into segments a few seconds long, and every segment exists at several qualities. A small text file, the master playlist, lists the qualities and the bandwidth each one needs.
  2. The player downloads the master playlist first. It learns that this video comes in 360p, 720p and 1080p, needing about 0.8, 3 and 5 megabits a second.
  3. The player knows nothing about the network yet, so it starts low and requests the first segment at 360p. A small segment arrives quickly, and the first frame is on screen with little delay.
  4. The player timed that download. The data arrived at about 8 megabits a second, more than 1080p needs, and the buffer is filling. For the next segment it asks for 1080p.
  5. A few segments later the viewer walks out of Wi-Fi range. Segment 6 at 1080p arrives slowly. The player now measures about 2 megabits a second, and its buffer starts to drain.
  6. Before the buffer runs out, the player switches down. Two megabits a second is not enough for 720p, so segment 7 is requested at 360p. The picture is softer, but playback does not stop.
  7. The switch is clean because segments are aligned. Segment 7 covers the same seconds of video at every quality and begins with a keyframe, so the decoder can start from it without needing segment 6 at the same quality.
  8. The server did nothing clever. Every request was an ordinary HTTP GET for a static file, which is why any CDN can cache the segments and serve millions of viewers. All the decisions are made in the player, every few seconds.
Adaptive bitrate streaming, one segment at a time

The player downloads the manifest, picks a starting rendition (usually a low one, so the first frame appears quickly), and requests segments one at a time. After each, it knows how fast the data arrived and how many seconds are buffered, and it chooses the rendition for the next. Segments are aligned across renditions and each begins with a keyframe, so a switch is invisible apart from the change in sharpness.

The property that matters for system design is that the server side is stateless. A segment is an immutable file with a URL. There are no sessions, and seeking is a request for a different segment. Any HTTP cache can serve it.

Segment length is a trade-off. Shorter segments let the player react sooner and reduce latency for live video, but mean more requests and more keyframes, which costs compression efficiency.

To support both protocols without storing everything twice, encode segments once as fragmented MP4 (the CMAF format) and publish two manifests that point at the same files.

CDN delivery, cost and the long tail

Segments never change, so they are cached with a long TTL and need no invalidation. Manifests for a finished video are equally stable. Give them a short TTL only while renditions are still being added.

Views are heavily skewed. A small share of videos receives most of the watch time, and a very large number of videos are watched a few times a month.

  • Popular videos are in the cache of every edge location. The origin is barely touched.
  • Long-tail videos are rarely in an edge cache when requested. Each miss goes to the origin. Put a shield tier between the edges and the origin so a tail video is fetched from storage once per region, not once per edge location. Their sources and rarely used renditions can move to a cheaper storage class.

Since egress is the main cost, the levers are worth naming: re-encode popular videos with a more efficient codec, cap quality by device (a phone screen does not need 4K), keep the cache hit ratio high, and negotiate across more than one CDN. At the largest scale, companies place their own cache servers inside internet providers’ networks, as Netflix does with Open Connect.

For private or paid content, the API issues signed URLs or cookies with an expiry, and the CDN verifies them at the edge without calling the origin.

Bottlenecks and failure modes

  • Transcode backlog. An upload spike outruns the workers. Scale on queue depth, process short videos and low renditions first, and show the creator honest progress.
  • Worker lost mid-task. The lease expires and the task is retried. Output keys are deterministic, so a half-written object is overwritten.
  • Bad or hostile uploads. Media parsers are a common source of security bugs. Run the probe and encode steps in a sandbox with limits on time, memory and output size.
  • Manifest visible before its segments. Write segments first and the manifest last, so a player never sees a reference to a missing file.
  • Cold or purged CDN. Many edges miss on the same segment at once. The shield tier collapses these into one origin request per object (stampede).
  • CDN outage. Keep a second CDN and let the player or DNS switch between them.
  • Hot view counter. A viral video produces thousands of view events a second. They are summed in the stream processor and written as one update per window.
  • Metadata database. Video pages are read-heavy. Serve them from the cache and read replicas (replication).

Trade-offs

Decision Chosen Alternative Why
Upload path Multipart, direct to object storage Through application servers No video bytes on our fleet, and resumable; needs a completion step
Transcoding Chunked task graph One job per video Parallel and cheap to retry; more orchestration
Delivery Segmented HLS and DASH over a CDN Progressive download of one file Adapts to the network and caches as static files; several renditions to store
Codec policy H.264 for all, efficient codecs for popular videos Best codec for everything Compute is spent where bandwidth savings repay it
View counts Stream aggregation Synchronous increment No hot rows; counts lag slightly

45-minute interview script

A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.

  1. 0:00 to 5:00

    Requirements 5 min

    Confirm upload and on-demand playback, not live. Ask about video length, the devices to support, and whether content is public. State the targets for time to first frame, rebuffering and time until an upload is playable.

  2. 5:00 to 10:00

    Capacity estimates 5 min

    Derive hours watched, daily egress, peak bandwidth, storage per video and transcoding compute. Say the conclusion aloud. Egress is petabytes a day and costs more than everything else combined.

  3. 10:00 to 13:00

    API 3 min

    Create a video and get an upload session, complete the upload, fetch metadata with a manifest URL, report a view. Point out that video bytes never touch the API servers in either direction.

  4. 13:00 to 16:00

    Data model 3 min

    Video metadata with a status field, transcode tasks, view counts, and the object key layout for sources, segments and playlists.

  5. 16:00 to 24:00

    High-level design 8 min

    Draw the upload path to object storage, the orchestrator and task queue feeding transcode workers, the encoded store behind the CDN, and the metadata and view-count paths. Narrate one upload and one play.

  6. 24:00 to 32:00

    Deep dive: upload and transcoding 8 min

    Resumable multipart upload. The pipeline as a graph of tasks. Splitting into chunks so a long video encodes in parallel and a failure costs one chunk. Idempotent tasks, leases, autoscaling on queue depth.

  7. 32:00 to 39:00

    Deep dive: adaptive bitrate and the CDN 7 min

    Segments, renditions and manifests. The player chooses quality per segment. Everything is a static file over HTTP. Then caching, popular against long-tail content, and the levers on cost.

  8. 39:00 to 43:00

    Failure modes and trade-offs 4 min

    Transcode backlog, worker loss, bad uploads, CDN miss storms, hot view counters. Summarise the main trade-offs.

  9. 43:00 to 45:00

    Wrap-up 2 min

    Summarise in three sentences and name extensions such as live streaming, DRM or recommendations.

Sketch this design on the whiteboard Run it as a timed mock

Key takeaways

  • Video bytes never pass through application servers. Uploads go straight to object storage and playback comes from a CDN.
  • Transcoding is a graph of small, idempotent tasks. Splitting a video into chunks lets a long upload encode in parallel, and a failed worker costs one chunk.
  • Adaptive bitrate streaming cuts each video into short segments at several qualities. The player picks a quality for every segment from measured throughput and buffer level.
  • HLS and DASH are just static files over HTTP, which is why ordinary CDNs can cache and serve them.
  • Delivery bandwidth is the largest cost. Encoding is paid once per video and delivery once per view, so spend extra encoding effort on popular videos.
  • A small share of videos takes most of the views. Popular videos live at the CDN edge, and long-tail videos are served through a shield tier from the origin.
  • Count views through a stream and aggregate. A synchronous counter update on every play creates a hot row.

Check yourself

1. Why does the client upload the video file directly to object storage instead of posting it to the API servers?
2. A two-hour video is split into one-minute chunks before encoding. What is the main benefit?
3. In adaptive bitrate streaming, which component decides the quality of the next segment?
4. Why must segment boundaries be aligned across renditions, each starting with a keyframe?
5. The platform re-encodes its most watched videos with a slower, more efficient codec but leaves the rest in H.264. Why?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What is adaptive bitrate streaming?

The video is stored as short segments at several bitrates. The player downloads a manifest, then chooses the quality of each segment from measured throughput and buffer level, so playback adapts to the network.

HLS versus DASH?

HLS is Apple's protocol with .m3u8 playlists and is native on Apple devices. DASH is an ISO standard with an XML manifest. With CMAF fragmented MP4 segments, one set of files can serve both.

Why model transcoding as a DAG of tasks?

Steps have dependencies (probe, split, encode each chunk and rendition, package, publish) and many can run in parallel. Small idempotent tasks retry cheaply and scale across workers.

How does a resumable upload work?

The client splits the file into parts and uploads each to object storage with a pre-signed URL. Failed parts are retried alone, and a final call assembles them.

What dominates the cost of a video platform, and what reduces it?

CDN egress. Reduce it with efficient codecs for popular videos, a sensible bitrate ladder, device-appropriate quality caps, high cache hit ratios and negotiated or in-house delivery.

How should view counts be recorded?

Players send beacons, the API writes events to a stream, aggregators deduplicate and sum them in windows, and totals are stored and cached. The displayed count is eventually consistent.

Review the deck