Design YouTube Video Streaming Platform
1. Problem Statement & Scope
System Mission
Design a global-scale video sharing, processing, and streaming platform capable of ingesting over 500 hours of video content uploaded per minute (), executing parallel Group of Pictures (GOP) chunk splitting and GPU transcoding pipeline Directed Acyclic Graphs (DAG) across heterogeneous codecs (H.264/AVC, H.265/HEVC, VP9, AV1), serving Adaptive Bitrate (ABR) streams via HLS and MPEG-DASH, and delivering media globally with sub-second Time-To-First-Frame (TTFF) via multi-tier edge caching, CloudFront Origin Shield, and S3 lifecycle storage tiering.
Synthesizing vector architecture diagram...
Functional Requirements
- Resilient Chunked Video Upload: Support resumable, chunked multipart uploads for large video files (up to ) over unreliable client connections with pause/resume capability.
- Parallel GOP Transcoding Pipeline DAG: Decompose uploaded raw videos at keyframe (I-frame) boundaries into 4-second Group of Pictures (GOP) chunks, transcode in parallel across 6 resolution tiers () and multiple codecs (H.264, VP9, AV1), and extract normalized audio streams.
- Adaptive Bitrate (ABR) Streaming: Generate HLS (
.m3u8master and media playlists) and MPEG-DASH (.mpd) manifests supporting dynamic runtime switching based on client network bandwidth and forward buffer health. - Metadata, Real-Time Counters & Search: Ingest and query video metadata, channel subscriptions, and manage atomic video view counting buffering millions of concurrent playback events.
- Storage Lifecycle & CDN Optimization: Tier raw master files to Amazon S3 Glacier Instant Retrieval and use CloudFront Origin Shield to eliminate origin thundering herds on trending uploads.
Non-Functional Requirements (SLAs/SLOs)
- High Availability: availability for video playback ( downtime/year); for ingestion.
- Latency SLOs:
- Time-To-First-Frame (TTFF): () globally across edge CDN Points of Presence (PoPs).
- Rebuffer / Stall Rate: of active playback sessions experiencing mid-stream buffering.
- Transcoding Turnaround SLA: Video ready for standard playback () in video duration; full multi-codec ladder ready in video duration.
- Durability Guarantee: (11 Nines) zero-loss durability for master raw videos and transcoded segments in Amazon S3.
- CAP / PACELC Classification:
- Playback & CDN Tier: AP / PA-EL (Availability and low latency prioritized; stale view counts and playlist versions tolerable).
- Transcoding & Metadata Ingestion: CP / PC-EC (Consistent DAG state transitions, strict idempotency on upload chunks).
2. Capacity & Scale Estimation
Traffic Calculations
- Active Viewer Base: 2 Billion Monthly Active Users (MAU), 500 Million Daily Active Users (DAU).
- Video Ingestion Volume:
- Global Ingest Velocity: 500 hours of raw video uploaded per minute.
- Average raw video duration ().
- Total Daily Uploads:
- Upload QPS:
- Playback Traffic:
- 5 Billion video views per day across global audience.
- Playback Initiation QPS:
Storage Calculations (3-Year Horizon)
- Raw Ingest Footprint:
- Average source upload bitrate .
- Size per 10-min raw video: .
- Daily Raw Storage:
- Transcoding Profile Ladder (Renditions & Codecs):
- Transcoding ladder per video across H.264/AVC baseline and AV1/VP9 high-efficiency codecs:
- ( @ ):
- ( @ ):
- ( @ ):
- ( @ ):
- ( @ ):
- ( @ ):
- Isolated Audio Stream (AAC/Opus @ ):
- Cumulative Transcoded Bitrate for one codec family (H.264/HEVC ladder). Publishing a second family (VP9 or AV1, roughly smaller at equal quality) adds again; the figures below count a single ladder, which is also why AV1 is only generated for videos that earn views (Section 2, lifecycle).
- Transcoded footprint per 10-min video .
- Daily Transcoded Ingress:
- Transcoding ladder per video across H.264/AVC baseline and AV1/VP9 high-efficiency codecs:
- 3-Year Cumulative Volume (Raw + Transcoded):
- S3 Lifecycle Tiering Strategy:
- Raw source masters moved to S3 Glacier Instant Retrieval after 7 days ( storage cost reduction).
- Transcoded videos with zero views in 90 days moved to S3 Glacier Flexible Retrieval; cold renditions () purged and regenerated on-demand if re-requested.
Network Bandwidth
- Ingress Bandwidth (Raw Uploads):
- CDN Egress Bandwidth (Video Playback):
- Average stream watch time () at average ().
- Data delivered per view .
- Total Daily Egress:
- Average and Peak Egress Bandwidth:
- Origin Shield Egress (Assuming Edge Cache Hit Ratio):
Memory & Cache Sizing (80/20 Pareto Working Set)
- Top of videos generate of all playback sessions.
- Daily active catalog working set referencing approximately 50 Million unique trending videos.
- Cache entry per video (manifests, metadata, initial segment headers): .
- View counter buffer (100 Million active counters):
Fleet Sizing & GPU Transcoder Provisioning
- Daily transcoding compute demand: .
- Target transcoding speed using AWS Batch with NVIDIA A10G GPUs (
g5.2xlargeinstances):- Hardware NVENC encodes a single rendition at real-time (a 4-second GOP chunk in , the figure used in Section 3).
- 1 GPU therefore produces rendition-hours per real-time hour per GPU.
- Every uploaded hour becomes 6 rendition-hours (the 4K to 240p ladder), so the demand is rendition-hours/day. Sizing the fleet against raw video-hours alone undercounts it by , which is the most common mistake in this estimate.
- Base GPU Fleet Size:
- Provisioning for peak ingest surges: Decoding the source once and feeding all six encoders from that decode (NVDEC 6 NVENC on the same card) roughly halves this in practice; the ladder count, not the raw hours, is what dominates the bill. Operated as Spot instances backed by On-Demand buffer with auto-requeuing on spot reclamation.
3. AWS-First High-Level Architecture
Synthesizing vector architecture diagram...
Follow a video from upload to playback. In the "Ingestion & Upload Control Plane" panel, the creator uploads the raw file to S3 (with transfer acceleration) and its metadata goes to DynamoDB. The S3 upload event reaches EventBridge, which starts the "Chunked Transcoding Pipeline DAG" panel: Step Functions has the file split into roughly 4-second chunks at keyframes, each chunk is queued in SQS and transcoded in parallel by the GPU fleet, and the packager assembles HLS and DASH manifests, so a one-hour video takes about as long as its slowest chunk. Viewers stream through the "Multi-Tier Edge Acceleration & CDN Layer" panel, where Origin Shield merges identical cache misses from many edges into one request to S3. In the "Playback, Counters & Discovery Services" panel, view counts flow through Kinesis and Flink into Redis counters, which are flushed to DynamoDB every 60 s instead of costing one write per view. Raw uploads move to Glacier after 7 days, and old renditions after 90.
Data Flow Walkthrough
- Resilient Ingestion: Creators initiate multipart uploads via the Upload Control Service, obtaining presigned S3 URLs. Files stream directly to S3 Raw Ingest with S3 Transfer Acceleration.
- GOP Chunk Splitting: S3 triggers AWS Step Functions via EventBridge. The GOP Splitter decodes video keyframes (I-frames) and dispatches 4-second GOP chunk transcode jobs to Amazon SQS.
- Parallel GPU Transcoding: AWS Batch EC2
g5.2xlargeinstances poll SQS, transcode GOP chunks across the multi-resolution ladder using hardware NVENC, and write.ts/.m4schunks to S3 Transcoded Segments. - Packaging & Manifest Generation: Once all chunks complete, the Packager Worker compiles the variant playlists (
1080p/index.m3u8, etc.) and master manifest (master.m3u8), marking the videoREADYin DynamoDB. - Multi-Tier Edge Playback: Players fetch the master playlist via CloudFront. Origin Shield deduplicates concurrent requests, and edge PoPs serve media segments with byte-range optimization. View beacons stream to Kinesis for sharded Redis buffering before DynamoDB persistence.
Concrete Step-by-Step Request Walkthrough: Tracing Upload to Playback
| Step # | Event / Action | Component State | Distributed Transition | Output / Response |
|---|---|---|---|---|
| 1 | Creator client initializes upload via POST /v1/videos/uploads/initialize | Upload Control Service validates JWT and file schema ( limit) | Allocates video_id, initializes S3 Multipart Upload via AWS SDK, writes STATUS=UPLOADING to DynamoDB | Returns 201 Created with S3 upload_id and presigned part URLs |
| 2 | Creator client streams 400 parts ( each) directly to Amazon S3 | S3 receives concurrent binary parts across multi-AZ storage | Client performs exponential retry on dropped chunks; verifies MD5 ETags per part | S3 returns ETag for each completed part |
| 3 | Creator issues POST /v1/videos/uploads/complete with parts list | Upload Service calls s3.CompleteMultipartUpload; emits EventBridge event | Step Functions orchestrator starts; invokes GOP Splitter task on ECS Fargate | Returns 202 Accepted (status: PROCESSING); creator polls or awaits WebSocket push |
| 4 | GOP Splitter analyzes keyframe Presentation Timestamps (PTS); cuts 4s chunks | Raw video demuxed; 150 GOP chunk references created | Dispatches 150 tasks per resolution tier (900 tasks total) to SQS Transcode Queue | SQS queue depth scales AWS Batch GPU compute environment |
| 5 | GPU workers pull chunk jobs; transcode via NVENC; write to S3 | AWS Batch g5.2xlarge processes chunk in | Uploads vid_101/1080p/seg_001.ts to S3 Transcoded Segments; sends completion token | Packager Lambda verifies all 900 chunks present; generates master.m3u8 |
| 6 | Viewer requests GET /v1/videos/vid_101/master.m3u8 via CloudFront Edge | CloudFront Edge misses; forwards to CloudFront Origin Shield | Origin Shield executes request collapsing (1 S3 read for 50k concurrent requests) | Returns 200 OK with HLS playlist; edge caches the VOD manifest for 60 seconds (Section 9.2) |
| 7 | Viewer player downloads media segments (seg_000.ts .. seg_005.ts) | Player ABR engine monitors TCP throughput and buffer occupancy | Requests segment via HTTP byte-range; CloudFront Edge serves directly with 98.5% CHR | Video plays smoothly; TTFF ; view beacon sent to Kinesis |
4. API Interface Design
1. Initialize Multipart Video Upload (POST /v1/videos/uploads/initialize)
Initializes a resumable chunked upload session and generates presigned S3 URLs.
httpPOST /v1/videos/uploads/initialize HTTP/1.1 Host: api.media.aws.internal Authorization: Bearer <jwt_token> Content-Type: application/json { "title": "Distributed Consensus in Practice: Raft & Paxos", "description": "Comprehensive architectural guide to state machine replication.", "category_id": 28, "privacy": "PUBLIC", "file_name": "consensus_master_4k.mov", "file_size_bytes": 10737418240, "chunk_size_bytes": 26214400, "total_parts": 410, "source_codec": "prores_422", "client_md5": "d41d8cd98f00b204e9800998ecf8427e" }
Response: 201 Created
json{ "video_id": "vid_998124a87c1", "upload_id": "s3_upload_987654321_abcde", "presigned_parts": [ { "part_number": 1, "url": "https://s3.us-east-1.amazonaws.com/raw-ingest/vid_998124a87c1?partNumber=1&uploadId=s3_upload_987654321_abcde&X-Amz-Signature=...", "expires_at": 1773651600 }, { "part_number": 2, "url": "https://s3.us-east-1.amazonaws.com/raw-ingest/vid_998124a87c1?partNumber=2&uploadId=s3_upload_987654321_abcde&X-Amz-Signature=...", "expires_at": 1773651600 } ], "expires_in_seconds": 86400 }
2. Complete Multipart Upload & Trigger Transcoding (POST /v1/videos/uploads/complete)
Verifies part ETags in S3 and activates the Step Functions DAG.
httpPOST /v1/videos/uploads/complete HTTP/1.1 Host: api.media.aws.internal Authorization: Bearer <jwt_token> Content-Type: application/json { "video_id": "vid_998124a87c1", "upload_id": "s3_upload_987654321_abcde", "parts": [ {"part_number": 1, "etag": "\"d41d8cd98f00b204e9800998ecf8427e\""}, {"part_number": 2, "etag": "\"0cc175b9c0f1b6a831c399e269772661\""} ] }
Response: 202 Accepted
json{ "video_id": "vid_998124a87c1", "status": "PROCESSING", "estimated_completion_seconds": 120, "status_url": "/v1/videos/vid_998124a87c1/status" }
3. Master HLS Playlist Manifest (GET /v1/videos/{video_id}/master.m3u8)
Served via CloudFront with ABR variant ladder:
m3u8#EXTM3U #EXT-X-VERSION:6 #EXT-X-INDEPENDENT-SEGMENTS # Audio Rendition (Demuxed AAC 128kbps) #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio-aac",NAME="English",DEFAULT=YES,AUTOSELECT=YES,LANGUAGE="en",URI="audio/128k/index.m3u8" # 4K UHD Profile (HEVC / Main 10 @ Level 5.1) #EXT-X-STREAM-INF:BANDWIDTH=15000000,AVERAGE-BANDWIDTH=14000000,RESOLUTION=3840x2160,FRAME-RATE=60.000,CODECS="hvc1.2.4.L153.B0,mp4a.40.2",AUDIO="audio-aac" 4k/index.m3u8 # 1080p Profile (AVC1 / High Profile @ Level 4.2) #EXT-X-STREAM-INF:BANDWIDTH=5500000,AVERAGE-BANDWIDTH=5000000,RESOLUTION=1920x1080,FRAME-RATE=60.000,CODECS="avc1.64002a,mp4a.40.2",AUDIO="audio-aac" 1080p/index.m3u8 # 720p Profile (AVC1 / Main Profile @ Level 3.1) #EXT-X-STREAM-INF:BANDWIDTH=2500000,AVERAGE-BANDWIDTH=2200000,RESOLUTION=1280x720,FRAME-RATE=30.000,CODECS="avc1.4d401f,mp4a.40.2",AUDIO="audio-aac" 720p/index.m3u8 # 480p Profile (AVC1 / Main Profile @ Level 3.0) #EXT-X-STREAM-INF:BANDWIDTH=1200000,AVERAGE-BANDWIDTH=1000000,RESOLUTION=854x480,FRAME-RATE=30.000,CODECS="avc1.4d401e,mp4a.40.2",AUDIO="audio-aac" 480p/index.m3u8 # 360p Profile (AVC1 / Baseline Profile @ Level 3.0) #EXT-X-STREAM-INF:BANDWIDTH=600000,AVERAGE-BANDWIDTH=500000,RESOLUTION=640x360,FRAME-RATE=30.000,CODECS="avc1.42e01e,mp4a.40.2",AUDIO="audio-aac" 360p/index.m3u8
4. Status Codes & Error Contracts
| HTTP Status | Reason Code | Error Contract Payload | Mitigation / Client Action |
|---|---|---|---|
200 OK | SUCCESS | Entity payload / manifest data | Normal completion |
201 Created | UPLOAD_INITIALIZED | Presigned URL session tokens | Client begins multipart chunk upload |
202 Accepted | TRANSCODING_QUEUED | Processing tracking URL | Client polls status or waits for push |
400 Bad Request | INVALID_CODEC_OR_CONTAINER | {"error": "Unsupported codec: wmv"} | Client re-encodes source container |
404 Not Found | VIDEO_NOT_FOUND | {"error": "Video ID does not exist"} | Display video removed / private page |
409 Conflict | ETAG_CHECKSUM_MISMATCH | {"error": "Part 4 MD5 checksum differs"} | Client re-uploads corrupted part |
429 Too Many Req | VIEW_BEACON_RATE_LIMITED | {"error": "Beacon QPS exceeded", "retry_after": 5} | Exponential backoff on telemetry client |
503 Service Unavail | TRANSCODE_CAPACITY_EXHAUST | {"error": "Batch queue depth high"} | System falls back to on-demand compute |
5. Data Models & Storage Architecture
Physical Storage Layout: Amazon S3
| Bucket | Key path | What it holds |
|---|---|---|
s3://youtube-raw-ingest/ | uploads/{creator_id}/{video_id}/master.mov | The creator's original upload |
s3://youtube-raw-ingest/ | uploads/{creator_id}/{video_id}/parts/part-0001 … part-0410 | The multipart upload parts |
s3://youtube-transcoded-vod/ | videos/{video_id}/master.m3u8 | Master ABR HLS playlist |
s3://youtube-transcoded-vod/ | videos/{video_id}/manifest.mpd | MPEG-DASH manifest |
s3://youtube-transcoded-vod/ | videos/{video_id}/audio/128k/index.m3u8 | Audio playlist |
s3://youtube-transcoded-vod/ | videos/{video_id}/audio/128k/seg_000.m4s … seg_150.m4s | Audio segments |
s3://youtube-transcoded-vod/ | videos/{video_id}/1080p/index.m3u8 | Variant playlist |
s3://youtube-transcoded-vod/ | videos/{video_id}/1080p/seg_000.ts … seg_150.ts | 4-second GOP chunks |
s3://youtube-transcoded-vod/ | videos/{video_id}/720p/ … 360p/ | The lower renditions, laid out like 1080p/ |
s3://youtube-transcoded-vod/ | videos/{video_id}/thumbnails/poster_maxres.jpg | Poster image |
s3://youtube-transcoded-vod/ | videos/{video_id}/thumbnails/storyboard_sprite.vtt | Video scrub preview sprites |
DynamoDB Single-Table Schema (YouTubeCoreTable)
Partition Key (PK) | Sort Key (SK) | Attributes & Payloads | GSI1-PK / GSI1-SK |
|---|---|---|---|
VIDEO#<video_id> | METADATA | channel_id, title, duration_s: 600, status: "READY", master_url, created_at | CHANNEL#<channel_id> / DATE#<created_at> |
VIDEO#<video_id> | RENDITION#1080P | codec: "avc1.64002a", bitrate: 5500000, chunks: 150, size_bytes: 412500000 | — |
VIDEO#<video_id> | RENDITION#720P | codec: "avc1.4d401f", bitrate: 2500000, chunks: 150, size_bytes: 187500000 | — |
VIDEO#<video_id> | COUNTER#VIEWS | total_views: 45892010, hourly_delta: 34200, last_flush: 1773648000 | — |
USER#<user_id> | WATCH_HISTORY#<video_id> | progress_seconds: 420, completed: false, updated_at: 1773648120 | USER#<user_id> / UPDATED#<updated_at> |
CHANNEL#<channel_id> | SUBSCRIBERS | sub_count: 1250000, tier: "PARTNER", handle: "@distributed_eng" | — |
Unlock Complete Architecture & Production Runbooks
You have explored the free architectural preview (~45%). Spend 1 Coin to unlock the remaining 6 production deep-dive sections for a full 24 hours.