Build a Global Video Platform with Resumable Upload and ABR Streaming
System DesignModel answerLast updated
Architect a scalable video platform supporting chunked uploads, distributed transcoding into adaptive bitrate formats, moderation workflows, and CDN-backed delivery.
Problem
You're building the backend for a video platform that allows users to upload large video files, processes them into multiple quality levels, and streams them efficiently to a global audience.
Functional Goals
-
Chunked Upload Flow: Users upload videos up to 10 GB in size. The system must support pause, resume, and automatic retry on connection drops without restarting from zero.
-
Multi-Quality Encoding: Every uploaded video is transcoded into adaptive bitrate formats (HLS or DASH) at 360p, 480p, 720p, and 1080p. The pipeline must handle retries gracefully—if a worker crashes mid-encode, no duplicate or corrupted output should be produced.
-
Content Review Gates: Before a video becomes public, it passes through automated moderation (frame analysis, audio transcription, copyright fingerprinting). The review step should not delay encoding itself.
-
Adaptive Playback: Clients receive video segments that match their current bandwidth. Segment delivery should start within 1.5 seconds globally.
-
Access Rules: Videos can be public, unlisted, or private. Private videos require time-limited signed tokens for playback.
Scale Targets
- 50,000 uploads daily (~100 TB of raw video per day)
- 10 million daily viewers streaming 50 million hours total
- 99.99% availability for playback; 99.9% for upload
- 11-nines durability for all video files
What You Should Address
- Upload mechanism: How clients send large files reliably, how state is tracked, and how the system resumes interrupted transfers.
- Transcoding orchestration: How the work is split, distributed to workers, and protected against duplicate execution.
- Data schema: Tables or collections for videos, jobs, chunks, moderation results, and access policies.
- Delivery architecture: How manifests and video segments are cached at the edge, how access control integrates with CDN signed URLs, and cache invalidation strategy.
- Moderation flow: Where it fits in the state machine and how it gates publication without blocking encoding.
Hints
Hint 1
Separate the upload data plane from the control plane—clients should write bytes directly to object storage using pre-signed URLs.
Hint 2
Make transcoding deterministic by using content-addressed output keys; a retried task will produce the same filename and can skip work if the file already exists.
Hint 3
Run moderation and transcoding in parallel branches, then join the results before marking the video as published.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Global Video Platform Architecture
1. Scope and Capacity Planning
Start by confirming boundaries. This is video-on-demand (VOD), not live streaming. Outputs are HLS and DASH; using fMP4/CMAF segments allows one file set to serve both protocols, cutting storage in half. Recommendations and social features are out of scope.
Capacity estimates:
- Upload rate: 50,000/day ≈ 0.6/s average, ~3/s at peak
- Ingest volume: 100 TB/day ≈ 10 Gbps average, ~30 Gbps peak
- Playback: 50M hours/day with 2M concurrent viewers on average. At ~3 Mbps average adaptive bitrate, egress is ~6 Tbps average, peaking at ~15 Tbps—this must be handled by CDN; origin sees <5%
- Storage growth: ~36 PB/year for sources. Renditions add ~40%. Move sources to cold storage post-transcode; keep renditions in standard tier with lifecycle rules shifting older content to infrequent-access.
The asymmetry shapes the design: ingest is moderate and durability-focused; playback is massive and cache-driven.
2. API Surface
POST /v1/uploads → {upload_id, part_size, presigned_urls[]}
GET /v1/uploads/{upload_id} → {parts_uploaded[], state}
POST /v1/uploads/{upload_id}/finish → {video_id}
GET /v1/videos/{video_id} → metadata + processing state
PATCH /v1/videos/{video_id} → update title, visibility
POST /v1/videos/{video_id}/token → signed playback token
GET /v1/videos/{video_id}/playlist.m3u8 (served via CDN)
3. Resumable Upload Flow
Control vs. data plane separation: clients never stream bytes through app servers.
- Client calls
POST /v1/uploadswith filename, size, and optional SHA-256. The Upload Service initiates a multipart upload in object storage (S3, GCS, Azure Blob), chooses 16–64 MB part size, and returns anupload_idplus an array of short-lived pre-signed PUT URLs for each part. - Client uploads parts directly to object storage in parallel (4–8 streams). Each part is idempotent: re-PUTting part N replaces it.
- Resume: on reconnect, client calls
GET /v1/uploads/{upload_id}. Server queries storage for completed parts (ListParts), reconciles state, and returns fresh pre-signed URLs for missing parts. - Completion: client calls
POST .../finishwith part ETags. Server callsCompleteMultipartUpload, validates size and checksum, then atomically writes the video record and emits anUploadCompletedevent (via transactional outbox or CDC) to trigger downstream processing. - Lifecycle policies abort incomplete uploads after 7 days to prevent orphaned part accumulation.
Durability: object storage provides 11-nines via erasure coding across availability zones. Enable cross-region replication for source files.
4. Data Model
Use a sharded relational database (Postgres with Citus, CockroachDB, Spanner) keyed by video_id.
videos (
video_id UUID PRIMARY KEY,
owner_id UUID,
title TEXT,
visibility ENUM('public','unlisted','private'),
state ENUM('uploading','uploaded','processing','moderation_pending','ready','published','blocked','failed'),
version INT,
source_key TEXT,
source_sha256 BYTEA,
duration_ms INT,
created_at TIMESTAMPTZ
)
upload_sessions (
upload_id UUID PRIMARY KEY,
video_id UUID,
owner_id UUID,
storage_key TEXT,
multipart_upload_id TEXT,
size_bytes BIGINT,
part_size INT,
parts_bitmap BYTEA, -- or JSON array
state ENUM('active','completed','expired'),
expires_at TIMESTAMPTZ
)
transcode_jobs (
job_id UUID PRIMARY KEY,
video_id UUID,
version INT,
profile_hash TEXT,
state ENUM('pending','running','done','failed'),
total_chunks INT,
done_chunks INT,
attempt INT,
lease_owner TEXT,
lease_expires_at TIMESTAMPTZ
)
chunk_tasks (
job_id UUID,
chunk_index INT,
rendition TEXT, -- '1080p', '720p', etc.
input_range_ms INT[2],
output_key TEXT,
output_hash TEXT,
state ENUM('pending','running','done'),
attempt INT,
lease_expires_at TIMESTAMPTZ,
PRIMARY KEY (job_id, chunk_index, rendition)
)
moderation_results (
video_id UUID,
version INT,
check_type TEXT, -- 'safety', 'copyright', 'audio_toxicity'
verdict ENUM('pass','review','block'),
score FLOAT,
reviewed_by TEXT,
PRIMARY KEY (video_id, version, check_type)
)
State transitions are compare-and-swap: UPDATE videos SET state = $new WHERE video_id = $id AND state = $expected AND version = $v. Duplicate events become no-ops.
5. Transcoding Pipeline with Idempotency
Use a workflow orchestrator (Temporal, Step Functions, or a custom queue + CAS state manager).
- Probe: extract duration, codec metadata, and keyframe index (read container header only; no decode).
- Chunk split: divide the source into ~10-second chunks aligned on GOP boundaries using byte-range reads. A 2-hour video becomes ~720 chunks. Don't re-encode during split.
- Fan-out: enqueue ~2,900 tasks (720 chunks × 4 renditions) to a distributed queue (SQS, Kafka).
- Worker pool: autoscaled GPU/CPU spot instances.
- Worker leases a task with visibility timeout + heartbeat.
- Transcodes the chunk using FFmpeg or hardware encoders.
- Writes output to a content-addressed key:
segments/{SHA256(source_sha256 || chunk_idx || rendition || encoder_version)}.m4s.
- Idempotency guarantees:
- Output keys are deterministic. Retries write the same key with identical bytes—duplicate work is harmless and detectable.
- Before encoding, worker checks if output key exists. If yes, skip and mark done (global dedup: re-uploading identical files reuses outputs).
- Task completion is CAS:
UPDATE chunk_tasks SET state='done' WHERE job_id=? AND chunk_index=? AND rendition=? AND state='running' AND attempt=?. Stale workers cannot overwrite newer results.
- Manifest generation: when
done_chunks == total_chunks, a single finalizer constructs HLS (playlist.m3u8) and DASH (manifest.mpd) manifests referencing all segment keys. Guard with CAS ontranscode_jobs.stateto ensure exactly-once execution.
Quality consistency: run a fast analysis pass before chunking to compute per-title encoding ladders, then pin encoder settings per rendition so chunk boundaries don't produce visual artifacts.
6. Moderation Integration
On upload completion, fork two parallel branches:
- Encode branch: described above.
- Moderation branch:
- Sample frames (~1 fps) from a low-res proxy or keyframes.
- Extract audio track.
- Fan out to: safety classifiers (NSFW, violence), ASR + text toxicity, copyright fingerprint matching.
- Write results to
moderation_results.
Join logic: video reaches READY when transcoding completes AND all required moderation checks pass. Moderation never blocks encoding—a clean video publishes as soon as the slower branch finishes. Ambiguous scores go to human review queues. Hard violations transition the video to BLOCKED; renditions are retained for appeals but CDN access is revoked.
7. CDN Delivery and Access Control
- Manifests (
playlist.m3u8,manifest.mpd): serve from origin with short TTL (30–60s) to allow metadata updates. CDN caches aggressively once the video is published. - Segments (
.m4s,.ts): immutable, cache for weeks withCache-Control: public, max-age=604800. - Signed URLs/cookies: for private/unlisted videos, origin issues time-limited tokens. CDN validates signatures at the edge (Lambda@Edge, Cloudflare Workers). Token scope covers the manifest and all segment requests.
- Cache invalidation: on video deletion or policy change, purge by tag or URL prefix. Segment keys are content-addressed, so updates naturally create new paths.
TTFF optimization: place ABR manifests and the first ~2 segments of each rendition in edge PoPs with predictive prefetch or smart cache warming after transcode completion.
8. Common Mistakes and Trade-Offs
- Streaming uploads through app servers: burns bandwidth and adds latency. Pre-signed URLs eliminate this bottleneck.
- Non-idempotent workers: relying on "run exactly once" semantics is fragile. Content-addressed keys and CAS make retries safe.
- Blocking encoding on moderation: serializing the two paths adds minutes to publish time. Parallel branches with a join keep the critical path short.
- Monolithic transcode jobs: encoding a 2-hour video on one machine takes hours and wastes money on failures. Chunking parallelizes the work and makes retries cheap.
- Hot origin: serving video segments from origin saturates egress. CDN PoP hit rates >95% are essential at this scale.
Complexity and Scale
- Upload latency: dominated by client bandwidth; server overhead is O(parts) metadata operations.
- Transcode throughput: linear in chunk count and worker pool size. With 100 workers, a 2-hour video completes in ~5–10 minutes.
- Storage: O(uploads × renditions). Lifecycle tiering and deduplication control costs.
- Playback: CDN cache hit rate >95% means origin serves <300 Gbps even at 6 Tbps total egress.
This architecture handles the target scale with high availability, strong durability, and subsecond global playback latency.