A video platform like YouTube or Netflix has two very different halves. The upload side accepts huge files over unreliable networks and runs a compute-heavy pipeline that turns one source file into dozens of encoded versions. The playback side streams those versions to hundreds of millions of screens, switching quality every few seconds to match each viewer's bandwidth, from caches placed as close to viewers as possible. Bandwidth, not request rate, is the defining constraint: video is the majority of all downstream internet traffic.
Think of it like
A publisher and its bookstores
An author hands in one manuscript. The publisher prints it in many editions (hardcover, paperback, large print, pocket size), cut into numbered chapters so a reader can switch editions at any chapter break. Popular titles are stocked in every neighborhood bookstore before launch day; obscure ones sit in a regional warehouse and are shipped on request. A reader on a bumpy bus grabs the pocket edition for the next chapter, then switches back to hardcover at home without losing their place.
1. Requirements
Functional
- Upload videos of any size, resuming after network drops
- Process uploads into streamable formats for every device
- Watch with adaptive quality, fast start, seeking and resume from where you left off
- Video metadata: title, description, thumbnails, captions
- View counts and likes
- Personalized recommendations on the home page (high level)
Non-functional
- Playback starts in under ~2 s with minimal rebuffering
- Playback is highly available; processing may take minutes
- Originals are never lost (11 nines object durability)
- Global reach with low latency to the nearest cache
- Cost efficiency: storage and egress dominate the bill
- Content protection (signed URLs, DRM for premium content)
| In scope | Out of scope (mention, then park) |
|---|---|
| Resumable upload and the transcoding pipeline | Live streaming (similar packaging, very different latency constraints) |
| Codecs, bitrate ladders, HLS/DASH and adaptive bitrate | Video search (see Search Systems) |
| CDN and ISP edge caching | Comments, subscriptions and creator monetization |
| Metadata, view counting, watch history | Ads insertion and the ads auction |
| Recommendations at a high level | Copyright matching internals |
2. Back-of-the-envelope estimation
Use YouTube-like public figures: about 500 hours of video uploaded every minute (cited by YouTube in 2019) and about 1 billion hours watched per day (announced in 2017). Assume an original averages 2 GB per hour of video, the encoded renditions add about 3 GB per hour, and average playback bitrate is 3 Mbps. See Back-of-the-Envelope Estimation.
Video ingested
720k h /day
500 hours per minute
New storage
~3.6 PB /day
originals + renditions
Egress
~125 Tb/s
average; peaks ~2×
Concurrent streams
~42M
1B hours ÷ 24
3. API design
# 1. Start a resumable upload session
POST /v1/uploads
{ "filename": "trip.mov", "sizeBytes": 4831838208, "contentType": "video/quicktime", "sha256": "9f2c..." }
-> 201 Created { "uploadId": "up_7Kd2", "chunkSize": 8388608 }
# 2. Send chunks; after a drop, ask where to resume
PUT /v1/uploads/up_7Kd2?offset=16777216
Content-Length: 8388608
Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
-> 200 OK { "committedBytes": 25165824 }
GET /v1/uploads/up_7Kd2
-> 200 OK { "committedBytes": 25165824, "state": "uploading" }
# 3. Finish and attach metadata (processing starts asynchronously)
POST /v1/uploads/up_7Kd2/complete
{ "title": "Road trip", "description": "...", "visibility": "public" }
-> 202 Accepted { "videoId": "v_Qx81", "status": "processing" }
# 4. Playback: metadata plus a signed manifest URL on a chosen CDN host
GET /v1/videos/v_Qx81/play
-> 200 OK { "manifest": "https://edge-17.cdn.example.com/v_Qx81/master.m3u8?sig=...&exp=...",
"resumeAtSec": 312, "captions": [ ... ] }
# 5. Playback heartbeats feed view counts and watch history
POST /v1/videos/v_Qx81/events
{ "sessionId": "s_19", "positionSec": 342, "rendition": "720p", "rebufferMs": 0 }- Video bytes never pass through the API. Uploads go to an upload service that streams chunks to object storage; playback segments come from the CDN. The API handles only small JSON.
- 202 Accepted on completion: processing takes minutes, so clients poll the status or get notified when the video is ready.
- Signed, expiring manifest URLs stop hotlinking and let the playback API choose which cache cluster serves this viewer. See Authentication & Security.
4. Data model
| Data | Store | Why |
|---|---|---|
| Video metadata (owner, title, status, duration, visibility) | Sharded MySQL (YouTube built Vitess for exactly this) | Relational, moderate size, transactional status changes |
| Renditions and manifests (codec, resolution, bitrate, path) | Same database, child table of videos | Read on every play; cached aggressively |
| Originals and encoded segments | Object storage, many PB | Immutable blobs with high durability. See Blob & Object Storage |
| Watch history and resume positions | Wide-column store (Cassandra), keyed by user | Huge write volume from heartbeats, read by user |
| View and like counters | Stream-aggregated counters in a key-value store | Write-hot on viral videos; exact real-time counts not required |
| Search and recommendations features | Search index and feature store | Derived from the above by pipelines. See Batch & Stream Processing |
CREATE TABLE videos (
video_id BIGINT PRIMARY KEY,
owner_id BIGINT NOT NULL,
title VARCHAR(200) NOT NULL,
description TEXT,
status ENUM('uploading','processing','ready','failed','blocked') NOT NULL,
visibility ENUM('public','unlisted','private') NOT NULL,
duration_ms INT,
source_key VARCHAR(512), -- object key of the original
created_at TIMESTAMP NOT NULL,
INDEX by_owner (owner_id, created_at)
);
CREATE TABLE renditions (
video_id BIGINT,
codec ENUM('h264','vp9','hevc','av1'),
height SMALLINT, -- 240, 360, 480, 720, 1080, 2160
bitrate_kbps INT,
playlist_key VARCHAR(512), -- e.g. v_Qx81/av1/1080p/index.m3u8
PRIMARY KEY (video_id, codec, height)
);5. High-level architecture
The top half is an asynchronous pipeline: chunks land in raw storage, an event starts a workflow, and a fleet of transcoders writes segments and playlists to the origin. The bottom half is the playback path: a small API call returns a manifest URL, then the player fetches segments from the nearest cache, which falls back to a regional shield and finally the origin. Press play to follow each path.
6. Deep dive: resumable upload
A 4 GB upload over mobile data takes many minutes, and a single dropped connection must not throw away progress. The fix is to upload in chunks against a server-side session that remembers how many bytes are durably committed. Google's resumable upload protocol and the open tus protocol both work this way.
- 1
Create a session
The client sends size, type and a whole-file checksum. The server returns an
uploadIdand a chunk size (for example 8 MB), and starts a multipart upload in object storage. - 2
Send chunks in order (or a few in parallel)
Each chunk carries its offset and a checksum. The server verifies it, writes it as one part, and advances
committedBytesonly after the write is durable. - 3
Recover
After any failure, the client asks for
committedBytesand continues from that offset. Re-sending a chunk that was already committed is harmless because the offset identifies it. - 4
Complete
When every byte is in, the server assembles the parts, verifies the whole-file checksum, and emits the event that starts processing.
- 5
Expire abandoned sessions
Sessions idle for days are aborted and their parts deleted, so half-finished uploads do not accumulate storage cost.
7. Deep dive: the transcoding pipeline
Transcoding is the most compute-hungry part of the system, and it is a DAG of jobs, not one job. Splitting the source into independent chunks turns a two-hour sequential encode into hundreds of parallel tasks that finish in minutes, and lets a failed task be retried alone. A workflow engine (Netflix built Conductor; many teams use Temporal, Airflow-style schedulers or cloud step functions) tracks dependencies, retries and timeouts.
import asyncio
from collections import deque
from dataclasses import dataclass, field
from typing import Awaitable, Callable
@dataclass
class Task:
name: str
run: Callable[[], Awaitable[None]] # must be idempotent: writes to a deterministic key
deps: list[str] = field(default_factory=list)
retries: int = 3
def topo_order(tasks: dict[str, Task]) -> list[Task]:
indegree = {n: len(t.deps) for n, t in tasks.items()}
children: dict[str, list[str]] = {n: [] for n in tasks}
for t in tasks.values():
for d in t.deps:
children[d].append(t.name)
ready = deque(n for n, k in indegree.items() if k == 0)
order = []
while ready:
n = ready.popleft()
order.append(tasks[n])
for c in children[n]:
indegree[c] -= 1
if indegree[c] == 0:
ready.append(c)
if len(order) != len(tasks):
raise ValueError("cycle in pipeline")
return order
async def run_dag(tasks: dict[str, Task], max_parallel: int = 64) -> None:
sem = asyncio.Semaphore(max_parallel)
running: dict[str, asyncio.Task] = {}
async def execute(t: Task) -> None:
await asyncio.gather(*(running[d] for d in t.deps)) # wait for dependencies
for attempt in range(t.retries + 1):
try:
async with sem:
await t.run()
return
except Exception:
if attempt == t.retries:
raise
await asyncio.sleep(2 ** attempt) # back off, then retry this task only
for t in topo_order(tasks): # dependencies are created first
running[t.name] = asyncio.create_task(execute(t))
await asyncio.gather(*running.values())The runner above is the essence of Topological Sort applied to infrastructure: tasks start as soon as their dependencies finish, and a failure retries only the failed task. Production systems add durable state (so the orchestrator itself can crash and resume), priorities (a creator with millions of subscribers, or a short clip, jumps the queue), and hardware awareness (GPU or ASIC encoders for some codecs).
8. Deep dive: codecs and bitrate ladders
| Codec | Efficiency vs H.264 | Licensing | Where it is used |
|---|---|---|---|
| H.264 / AVC | baseline | Patent pools, but universally licensed in hardware | Plays everywhere; the fallback rendition |
| H.265 / HEVC | roughly 25–50% fewer bits | Complex, multiple patent pools | Apple devices, 4K and HDR on TVs |
| VP9 | similar to HEVC | Royalty-free (Google) | YouTube on browsers and Android |
| AV1 | roughly 30% fewer bits than VP9/HEVC | Royalty-free (Alliance for Open Media) | Growing on YouTube and Netflix where hardware decode exists; slow to encode |
| Rung | Resolution | Typical H.264 bitrate | Who gets it |
|---|---|---|---|
| 240p | 426 × 240 | ~300–400 kbps | Very poor mobile connections, fast start |
| 360p | 640 × 360 | ~700 kbps | Weak 3G or congested Wi-Fi |
| 480p | 854 × 480 | ~1.2 Mbps | Small phone screens |
| 720p | 1280 × 720 | ~2.5–3 Mbps | Phones and laptops on decent networks |
| 1080p | 1920 × 1080 | ~4.5–6 Mbps | Laptops and TVs |
| 2160p (4K) | 3840 × 2160 | ~15–20 Mbps | 4K TVs on fast broadband (much less with HEVC or AV1) |
9. Deep dive: HLS/DASH segments and adaptive bitrate
Players do not download one big file. Each rendition is cut into short segments (typically 2–6 seconds; Apple's HLS guidance targets 6 s), all aligned on the same keyframe boundaries so the player can switch rendition between any two segments. A manifest lists the renditions and their segments: .m3u8 playlists for HLS and an .mpd file for MPEG-DASH. With CMAF, both formats can point at the same fragmented MP4 segments, so the platform stores one copy.
# master.m3u8: one entry per rendition
#EXTM3U
#EXT-X-VERSION:7
#EXT-X-INDEPENDENT-SEGMENTS
#EXT-X-STREAM-INF:BANDWIDTH=6000000,AVERAGE-BANDWIDTH=4500000,RESOLUTION=1920x1080,CODECS="avc1.640028,mp4a.40.2"
h264/1080p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=3300000,AVERAGE-BANDWIDTH=2600000,RESOLUTION=1280x720,CODECS="avc1.64001f,mp4a.40.2"
h264/720p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=900000,AVERAGE-BANDWIDTH=700000,RESOLUTION=640x360,CODECS="avc1.4d401e,mp4a.40.2"
h264/360p/index.m3u8
# h264/720p/index.m3u8: the segments of one rendition
#EXTM3U
#EXT-X-VERSION:7
#EXT-X-TARGETDURATION:6
#EXT-X-PLAYLIST-TYPE:VOD
#EXT-X-MAP:URI="init.mp4"
#EXTINF:6.000,
seg_00000.m4s
#EXTINF:6.000,
seg_00001.m4s
#EXTINF:4.200,
seg_00002.m4s
#EXT-X-ENDLISTThroughput-based ABR
- Estimate bandwidth from recent segment downloads
- Pick the highest rendition below a safety fraction of it
- Reacts quickly, but noisy estimates cause oscillation
Buffer-based ABR
- Choose quality from how many seconds are buffered
- Low buffer: drop quality; full buffer: climb
- Stable and avoids stalls (Netflix researchers published BBA in 2014)
Hybrid / model-based
- Combine throughput and buffer (for example model predictive control)
- Optimize a quality score minus rebuffering and switching penalties
- What most modern players approximate
- Fast start: begin at a low or medium rung so the first frame appears quickly, then climb as the buffer fills.
- Switch only at segment boundaries, and limit up-switches to one rung at a time; drop as far as needed when the buffer is in danger.
- Seeking jumps to the segment containing the target time; short segments make seeks and switches more responsive, while long segments compress better and mean fewer requests.
- Quality metrics such as rebuffer ratio, startup time and average bitrate are reported in heartbeats and drive both player tuning and CDN steering.
10. Deep dive: CDN and ISP edge caching
Video popularity is extremely skewed: a small head of popular titles accounts for most watch time, while a huge tail is watched rarely. The caching strategy follows the curve: put the head as close to viewers as possible, and keep the tail in fewer, larger tiers. Large platforms place their own cache servers inside ISP networks: Netflix's Open Connect appliances and Google's Global Cache for YouTube are both offered to ISPs at no charge, because serving traffic locally saves both sides transit costs.
- Tiered caching: edge, then regional shield, then origin. The shield turns thousands of edge misses into one origin request and protects origin storage from thundering herds.
- Request collapsing: when many viewers miss on the same new segment at once, the cache fetches it once and serves everyone.
- Steering: DNS, anycast or (as above) an explicit API decides which cache serves each viewer, using cache load, health and content.
- Multi-CDN: platforms without their own edge often contract several CDNs and switch between them on quality metrics.
- Pre-positioning: a premiere or big release is pushed to edges before it goes live, so launch traffic never reaches the origin.
11. Deep dive: views, watch history and recommendations
View counts look like a simple increment, but a viral video can receive tens of thousands of views per second, and counts must resist bots. Players send periodic heartbeats (position, rendition, rebuffering) into a stream. A stream processor validates and deduplicates them, counts a 'view' only after meaningful watch time, and aggregates counts per video per minute before writing to a counter store. See Message Queues & Pub/Sub and Batch & Stream Processing.
- 1
Collect
Heartbeats every ~10–30 s go to a regional ingestion tier and into Kafka, partitioned by video ID.
- 2
Validate
Drop events from known bots, impossible rates or repeated sessions. This is why public counts can lag or be corrected later.
- 3
Aggregate
Windowed aggregation turns millions of events into one increment per video per minute, so the counter store sees thousands of writes instead of millions.
- 4
Approximate where acceptable
Unique viewers per video can use HyperLogLog sketches rather than storing every viewer ID. See Bloom Filters & Probabilistic Structures.
- 5
Watch history
The same heartbeats update the user's resume position and history in a wide-column store keyed by user, which also feeds recommendations.
12. Scaling, bottlenecks and failures
| Problem | Mitigation |
|---|---|
| Transcoder crashes mid-task | Tasks are small and idempotent (deterministic output keys); the orchestrator retries just that task with backoff |
| Corrupt or malicious upload | Probe and validate first; sandbox decoders; after N failures mark the video failed and notify the creator |
| Upload spike (a big event) | Queue depth absorbs it; autoscale encoders; prioritize low rungs so videos become watchable sooner |
| Storage cost grows by PB per day | Move originals and rarely watched renditions to colder storage classes; regenerate rare renditions on demand |
| Edge or CDN outage | Players fail over to the next cache URL; multi-CDN for platforms without their own edge |
| Origin overload on a new release | Pre-position content; shields and request collapsing so each segment is fetched from origin once |
| Metadata hot spot on a viral video | Cache video metadata and manifests at the edge and in memory; they change rarely |
- Separate fleets: upload ingestion, transcoding, playback API and caches scale on different signals (bytes in, queue depth, requests, egress). See Scalability.
- Playback degrades gracefully: if recommendations or view counting are down, video still plays. See Resilience Patterns.
- Observability: startup time, rebuffer ratio and bitrate per ISP and region are the metrics users feel; alert on them. See Observability.
Implementation
Uploads a large file in fixed-size chunks against a session. After any failure it asks the server for the committed offset and resumes from there, with exponential backoff between attempts.
import base64
import hashlib
import random
import time
import requests
API = "https://api.example.com/v1/uploads"
def committed_bytes(upload_id: str) -> int:
r = requests.get(f"{API}/{upload_id}", timeout=10)
r.raise_for_status()
return r.json()["committedBytes"]
def resumable_upload(path: str, upload_id: str, size: int, chunk_size: int) -> None:
offset = committed_bytes(upload_id) # 0 for a new session
failures = 0
with open(path, "rb") as f:
while offset < size:
f.seek(offset)
chunk = f.read(min(chunk_size, size - offset))
md5 = base64.b64encode(hashlib.md5(chunk).digest()).decode()
try:
r = requests.put(f"{API}/{upload_id}", params={"offset": offset},
data=chunk, headers={"Content-MD5": md5}, timeout=60)
r.raise_for_status()
offset = r.json()["committedBytes"]
failures = 0
except requests.RequestException:
failures += 1
if failures > 8:
raise
time.sleep(random.uniform(0, min(30.0, 0.5 * 2 ** failures)))
offset = committed_bytes(upload_id) # resume from what the server has
requests.post(f"{API}/{upload_id}/complete", timeout=10).raise_for_status()Key takeaways
- Separate the asynchronous upload/processing pipeline from the latency-critical playback path; they scale on different resources.
- Resumable uploads use a server-side session and a committed offset, so a dropped connection costs one chunk, not the whole file.
- Transcoding is a DAG of small idempotent tasks: split at keyframes, encode chunks × renditions in parallel, package, then publish after checks.
- Each video is stored as a bitrate ladder in several codecs, cut into aligned 2–6 s segments described by HLS/DASH manifests.
- Adaptive bitrate runs in the player: it estimates bandwidth and buffer health and switches rendition at segment boundaries.
- At ~100+ Tb/s, nearly every byte must come from caches near viewers: tiered CDNs and appliances inside ISPs, filled ahead of demand.
Common pitfalls
- Routing video bytes through application servers instead of straight to object storage and from the CDN.
- Encoding a whole video as one sequential job, so a failure at 95% restarts everything and long videos take hours.
- Segments that are not keyframe-aligned across renditions, which makes quality switches glitch or impossible.
- Ignoring the long tail: assuming everything is a cache hit and leaving the origin unprotected without shields or request collapsing.
- Counting views with a synchronous database increment per play, which melts on viral videos and is trivially inflated by bots.
Interview tips
- Clarify YouTube-style (user uploads, long tail) or Netflix-style (curated catalog, pre-positioned) before designing.
- Do the egress arithmetic out loud: watch hours × bitrate shows why the CDN is the core of the design.
- Draw the transcoding DAG and explain chunk-level parallelism and idempotent retries.
- Explain adaptive bitrate concretely: segments, manifests, throughput and buffer signals, switching at boundaries.
Real-world applications
- YouTube: has cited more than 500 hours uploaded per minute (2019) and over a billion hours watched per day (2017); its metadata runs on Vitess (a MySQL sharding system created at YouTube); it introduced custom transcoding chips (Argos) in 2021 and serves much traffic from Google Global Cache nodes inside ISPs.
- Netflix: encodes titles with per-title and shot-based optimization, orchestrates media workflows with its Conductor and successor systems, and delivers video from Open Connect appliances inside ISPs and at exchange points, filled during off-peak hours.
- Twitch and other live platforms reuse HLS segments and adaptive bitrate but transcode in real time with seconds of latency.
- E-learning, video conferencing recordings and social video (Instagram Reels, TikTok) use the same upload, transcode and CDN pipeline at different scales.
Test yourself
Why is the source video split into chunks before encoding?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.