Design Netflix's Global Video Streaming & Zuul API Architecture
1. Problem Statement & Scope Clarification
System Mission
Design the global video streaming, API gateway, and edge routing infrastructure for Netflix, serving over paid subscribers across countries. The platform must handle continuous high-throughput video delivery ( peak video egress), millisecond-tier API routing across multi-region AWS infrastructure ( peak API QPS), automated regional evacuation during major AWS infrastructure outages within , and resilient distributed caching that guarantees zero playback disruption.
Separation of Concerns: Control Plane vs. Data Plane Invariant: 100% of video bits (HLS/DASH media payloads) are delivered outside the AWS cloud via the Open Connect Content Delivery Network (custom Open Connect Appliances deployed directly inside ISP networks and Internet Exchange Points). AWS hosts 100% of the scalable control plane: client authentication, playback licensing, personalized recommendations, billing, transcoding pipelines, and dynamic ingress routing via the Zuul edge gateway.
Synthesizing vector architecture diagram...
Functional Requirements
- User Profile & Discovery API: Deliver sub-second personalized homepage carousels, playback bookmarks, and search queries with .
- Dynamic Ingress API Gateway (Zuul 2): Terminate TLS, authenticate via cryptographic Passport tokens, execute dynamic routing/canary routing, enforce distributed rate limiting, and multiplex traffic via non-blocking asynchronous Netty event loops.
- Automated Multi-Region Active-Active Evacuation: Detect catastrophic AWS regional degradations (e.g., transit provider fiber cuts or AZ failures in
us-east-1) and seamlessly evacuate of ingress traffic tous-west-2andeu-west-1in without user logout or playback interruptions. - Adaptive Bitrate Streaming Manifest Negotiation: Calculate the optimal Open Connect Appliance (OCA) steering manifest based on client ISP AS-path, IP prefix health, and server load, returning signed DRM license tokens (Widevine, PlayReady, FairPlay).
- Continuous Resilience via Chaos Automation: Continuously inject host failures, latency degradation, and full regional network partitions (Chaos Monkey & Chaos Kong) during live production traffic to validate self-healing boundaries.
Non-Functional Requirements (SLAs & SLOs)
- High Availability: uptime for playback initialization (less than 5.26 minutes of downtime per calendar year).
- Gateway Ingress Latency: , , processing overhead added by Zuul edge filters.
- Playback Start Latency (Time-to-First-Frame): , globally over broadband and 5G connections.
- Regional Traffic Evacuation SLO: Shift of regional traffic () to alternate regions within () with zero increase in user error rates.
- Data Durability Guarantee: 11 Nines () for master media assets and subscriber accounts stored across Amazon S3 and multi-region distributed databases.
- CAP / PACELC Classification:
- Playback Control Plane: AP system under CAP; PA/EL under PACELC (Partition Availability; Else Latency over Consistency). Playback bookmarks and viewing history rely on eventual consistency; stale bookmarks are preferred over failing a playback request.
- Billing & Account Tiering: CP / PC/EC system enforcing strict ACID guarantees via Amazon Aurora PostgreSQL Multi-Region.
Out-of-Scope
- Physical manufacturing and ASIC hardware acceleration design of Open Connect Appliance servers.
- Content studio production workflows, raw film ingestion, and post-production editorial review pipelines.
- Direct credit card payment acquisition gateways (delegated to certified PCI-DSS Level 1 payment processors).
2. Capacity & Scale Estimation (Back-of-the-Envelope Math)
Traffic Scale & Concurrency Calculations
- Global Paid Subscribers: active accounts ( active viewer profiles).
- Peak Concurrent Video Streams: concurrent playback sessions during prime-time evening hours (8:00 PM - 11:00 PM local time across time zones).
- Average Stream Bitrate: (weighted blend of 50% 1080p @ 3.5 Mbps, 30% 4K HDR @ 15 Mbps, and 20% Mobile 720p @ 1.2 Mbps).
- Peak Video Delivery Bandwidth (Data Plane - Offloaded to OCAs):
Control Plane API Throughput Calculations (AWS Ingress)
- API Requests per Active Viewer Session: Average during browsing/discovery; during active video playback (telemetry pings, adaptive bitrate metrics, bookmark heartbeats every 10 seconds).
- Active Browsing Viewers: concurrent users navigating discovery carousels.
- Peak Ingress API QPS (Zuul Edge Gateway):
- Per-Region Load (Divided across 3 Active-Active AWS Regions: us-east-1, us-west-2, eu-west-1):
Distributed In-Memory Cache Sizing (EVCache / Memcached)
- Active User Session Context (Passport Tokens, Profile Settings):
- Personalized Discovery Graph / Metadata Working Set: Top 20% most active viewer profiles () cached in memory with recommendation arrays ( per profile):
- Video Catalog & OCA Routing Metadata: (negligible).
- Total In-Memory Cache Footprint per Region: With an 80/20 Pareto buffer, cache replication across 3 Availability Zones, and regional evacuation headroom ( multiplier):
Persistent Storage Calculations (3-Year Horizon)
- User Viewing History Records: .
- Replication Factor ( per region 3 active regions, matching the
NetworkTopologyStrategykeyspace in §5):
Fleet Sizing & Compute Infrastructure
- Zuul 2 Gateway Fleet (AWS ECS Fargate / EC2
c6i.8xlarge- 32 vCPU, 64 GB RAM): Each optimized Netty async gateway node handles active concurrent HTTP/2 connections and processes .
3. AWS-First High-Level Architecture
Synthesizing vector architecture diagram...
Split the picture into two planes. Data plane: in the "Global Open Connect Edge Delivery" panel (dotted arrows), video bytes go straight from Open Connect appliances inside the viewer's ISP, or at an internet exchange as a fallback, to the TV; they never pass through AWS. Control plane: everything else goes through Route 53 and the NLB to Zuul in AWS, where the "Zuul Netty Ingress Filter Pipeline" panel authenticates the request, applies the rate limit and routes canary traffic, and Eureka provides the current service instances. Services read from EVCache first and Cassandra or DynamoDB behind it, while playback events flow through Kinesis and Flink into the S3 analytics lake. The "AWS Region: us-west-2" panel is kept in sync so traffic can fail over within minutes. Putting video on ISP appliances is what lets AWS handle only small API calls while tens of terabits per second of video go elsewhere.
Data Flow Walkthrough
- Client Boot & Discovery Request: The subscriber device sends an HTTP/2 GET request for personalized carousels. Amazon Route 53 performs Anycast latency routing, resolving the DNS record to the nearest healthy AWS region (
us-east-1). - Edge Ingress & Netty Non-Blocking Pipeline: AWS NLB delivers the raw TCP streams to the Zuul 2 gateway fleet. A Netty event loop thread receives the request, parses the HTTP headers, and passes the payload through Zuul inbound filters:
- Passport Auth Filter: Validates the cryptographic HMAC signature of the client's session token without making an external database call.
- Adaptive Concurrency Limiter: Evaluates CPU and downstream latency. If the system is saturated, non-critical background telemetry is shed immediately.
- Canary Filter: Inspects client device metadata, user ID hash, and experiment cohorts to route traffic to the appropriate backend service version.
- Client-Side Discovery & Routing (Eureka): Zuul consults its local in-memory Eureka registry cache, selects a healthy target instance for
DiscoveryService, and routes via internal gRPC. - Cache-Aside Read (EVCache):
DiscoveryServicequeries the multi-AZ EVCache cluster. On a cache hit ( of requests), the personalized carousel payload is returned in . - Playback Manifest Generation & OCA Steering: When the user clicks "Play", a request hits
SvcPlaybackandSvcSteering. The steering engine inspects the user's IP prefix, autonomous system number (ASN), and the real-time load/health reports from Open Connect Appliances deployed inside the user's ISP. It constructs a dynamic HLS/DASH manifest containing ranked URLs pointing directly to local ISP OCAs. - Video Streaming Delivery (Off-Cloud Data Plane): The client media player fetches encrypted video/audio chunks directly from the assigned OCA via TLS 1.3 over HTTPS/QUIC. Video traffic never touches the AWS transit backbone.
- Telemetry Streaming: During playback, client players transmit periodic telemetry pings (bitrate switches, buffer health, frame drops) back through Zuul into Amazon Kinesis for real-time aggregation by Apache Flink.
End-to-End Request Tracing Walkthrough
| Step # | Event / Action | Component State | Distributed Transition | Output / Response |
|---|---|---|---|---|
| Step 1 | Subscriber launches client application | Client device cold launch | Route 53 resolves DNS via latency-based routing to lowest latency AWS region | Ingress connection targets AWS NLB VIP in us-east-1 |
| Step 2 | TLS 1.3 Handshake terminated at Zuul 2 | Inbound connection active | Netty worker thread binds connection to non-blocking channel pipeline | Epoll event loop dispatches request to Inbound Filter chain |
| Step 3 | Passport Token Cryptographic Validation | Zuul Inbound Filter chain | In-memory HMAC-SHA256 signature verification over client identity cookie | Decrypted Passport claims struct attached to Netty ChannelHandlerContext |
| Step 4 | Dynamic Service Route Discovery | Zuul Routing Filter | Local Eureka cache lookup resolves target IP for PlaybackService cluster | Selected target node: 10.120.45.12:50051 via round-robin with circuit check |
| Step 5 | Manifest & DRM Request Dispatched | Inter-service gRPC call | HTTP/2 multiplexed gRPC frame forwarded across AWS internal VPC mesh | PlaybackService initiates parallel manifest generation and license check |
| Step 6 | Subscriber Viewing Context Query | In-memory cache evaluation | PlaybackService queries EVCache for profile_id:video_id bookmark | Cache HIT: retrieved last playback offset (1:24:12) in |
| Step 7 | OCA Steering Engine Execution | Steering algorithm execution | Steering engine cross-references client IP BGP prefix with ISP OCA health table | 3 optimal OCA IPs identified (1 primary in local ISP, 2 IXP fallbacks) |
| Step 8 | Playback Manifest Assembled & Signed | Serialization stage | DRM challenge signed via AWS KMS; manifest URLs stamped with HMAC tokens | PlaybackManifestResponse protobuf serialized and returned to Zuul |
| Step 9 | Outbound Filter & Response Stream | Zuul Outbound Filter chain | Netty flushes HTTP/2 headers and compressed JSON payload to client socket | Client receives playback manifest with OCA endpoints and resume timestamp |
| Step 10 | Video Playback Stream Commences | Direct media delivery | Media player initiates chunked HTTP GET requests directly to local ISP OCA | Video segments stream at with latency impact on AWS core |
4. API Interface Design & Wire Protocol
1. Playback Manifest & Steering Negotiation (POST /v1/playback/manifest)
Initiates video playback, acquires DRM licensing tokens, and retrieves ranked Open Connect Appliance endpoints.
httpPOST /v1/playback/manifest HTTP/2 Host: api.netflix.com Content-Type: application/json X-Netflix-Passport: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... X-Device-Type: SMART_TV_TIZEN X-Client-BGP-ASN: AS7922 Idempotency-Key: 7f8a9b2c-3d4e-5f6a-7b8c-9d0e1f2a3b4c { "subscriber_id": "sub_84920192", "profile_id": "prof_3019", "video_id": "vid_81049281", "requested_audio_track": "en-US", "requested_subtitle_track": "es-419", "supported_drm_schemes": ["WIDEVINE_L1", "PLAYREADY_SL3000"], "display_capabilities": { "max_resolution": "3840x2160", "hdr_format": "DOLBY_VISION", "audio_codec": "ATMOS" }, "client_ip": "73.189.42.15" }
Response: 200 OK
json{ "playback_session_id": "sess_01HZX894KMNPQ", "video_id": "vid_81049281", "resume_position_ms": 5052000, "drm_license": { "scheme": "WIDEVINE_L1", "license_server_url": "https://drm.netflix.com/widevine/v1/license", "token": "dGVzdC1saWNlbnNlLXRva2Vu..." }, "manifest": { "type": "DASH", "master_url": "https://manifest.netflix.com/vid_81049281/master.mpd", "preferred_oca_endpoints": [ { "server_id": "oca-sea01-isp-comcast", "base_url": "https://ipv4-c001-sea001-comcast-isp.oca.nflxvideo.net", "priority": 1, "location": "Seattle, WA, US" }, { "server_id": "oca-sea02-ixp-equinix", "base_url": "https://ipv4-c002-sea002-ixp.oca.nflxvideo.net", "priority": 2, "location": "Seattle IXP, WA, US" } ], "segment_duration_ms": 2000 }, "telemetry_interval_ms": 10000 }
2. Playback State Heartbeat Protocol (POST /v1/playback/heartbeat)
Transmitted by clients every 10 seconds to update playback bookmarks, report quality of experience (QoE), and maintain active concurrent stream counts.
protobufsyntax = "proto3"; package netflix.telemetry.v1; message PlaybackHeartbeatRequest { string playback_session_id = 1; string subscriber_id = 2; string profile_id = 3; string video_id = 4; int64 current_playback_position_ms = 5; int64 buffer_health_ms = 6; int32 current_bitrate_kbps = 7; int32 dropped_frames_count = 8; string active_oca_server_id = 9; int64 timestamp_epoch_ms = 10; } message PlaybackHeartbeatResponse { bool continue_playback = 1; string steering_override_oca_url = 2; // Non-empty if client must failover to alternate OCA int32 updated_heartbeat_interval_sec = 3; }
3. Status Codes & Error Contracts
| HTTP Status | Reason Code | Error Contract Payload | Client Handling / Recovery Strategy |
|---|---|---|---|
200 OK | SUCCESS | Standard manifest / heartbeat response | Initialize or continue playback stream |
400 Bad Request | INVALID_DEVICE_PARAMS | {"error": "Unsupported DRM scheme for 4K rendition"} | Downscale stream to 1080p SDR; request fallback manifest |
401 Unauthorized | PASSPORT_EXPIRED | {"error": "Passport token signature invalid"} | Trigger background OAuth token refresh without disrupting buffer |
403 Forbidden | CONCURRENCY_LIMIT_EXCEEDED | {"error": "Max concurrent streams reached for account"} | Display friendly modal: "Too many people using account" |
404 Not Found | TITLE_NOT_LICENSED | {"error": "Content unavailable in subscriber geofence"} | Return user to browsing catalogue; refresh location tags |
429 Too Many Requests | RATE_LIMIT_EXCEEDED | {"error": "Zuul adaptive rate limit engaged"} | Exponential backoff with jitter on non-critical heartbeats |
503 Service Unavailable | REGIONAL_EVACUATION | {"error": "Region evacuating, retry with alternate DNS"} | Client immediately falls back to secondary region endpoint |
5. Data Models & Storage Architecture
Storage Tier Selection Justification
- Amazon Keyspaces / Apache Cassandra: Selected for subscriber viewing history, bookmarks, and playback sessions. Wide-column distributed architecture provides linear horizontal write scaling, multi-region asynchronous active-active WAN replication, and deterministic latency without lock contention.
- EVCache (Distributed Memcached): Sharded multi-AZ in-memory caching tier fronting Cassandra. Absorbs of read QPS, decoupling database clusters from prime-time browsing spikes.
- Amazon DynamoDB Global Tables: Selected for real-time concurrent stream tracking counters. Strongly consistent reads are available only within the writing region; cross-region replication is asynchronous (typically ), so a household could briefly exceed its stream limit by starting streams in two regions during an evacuation window. That over-admission is accepted (fail-open) rather than blocking playback on a cross-region round-trip.
Synthesizing vector architecture diagram...
Read the relationships from SUBSCRIBER. One subscriber has many PROFILEs, and each profile has its own VIEWING_BOOKMARKs (keyed by profile + video, so "resume where I stopped" is one lookup) and WATCH_HISTORY (keyed by profile + time, so history comes back newest first in one range query). CONCURRENT_STREAM_SESSION is keyed by subscriber, with one row per active stream and a heartbeat expiry; the service counts live rows against max_allowed_streams to enforce the plan's limit, and a crashed player's row simply expires. Every key starts with the ID the app already has (profile or subscriber), so each screen loads from a single partition, which is how the data model fits Cassandra and DynamoDB.
Cassandra CQL Schema: Viewing Bookmarks & History
sqlCREATE KEYSPACE netflix_playback WITH replication = { 'class': 'NetworkTopologyStrategy', 'us-east-1': 3, 'us-west-2': 3, 'eu-west-1': 3 }; -- Real-Time Viewing Bookmark (Upserted on every 10-second heartbeat) CREATE TABLE netflix_playback.viewing_bookmarks ( profile_id uuid, video_id text, bookmark_offset_ms bigint, duration_ms bigint, completion_pct int, device_type text, updated_at timestamp, PRIMARY KEY ((profile_id), video_id) ) WITH CLUSTERING ORDER BY (video_id ASC) AND compaction = { 'class': 'SizeTieredCompactionStrategy', 'max_threshold': 32 } AND default_time_to_live = 7776000; -- 90-day auto retention -- Append-Only Detailed Viewing History (for Recommendation Engines) CREATE TABLE netflix_playback.viewing_history ( profile_id uuid, watched_year_month int, -- Partition bucket e.g., 202609 to bound partition size event_timestamp timestamp, video_id text, total_seconds_viewed int, completed boolean, PRIMARY KEY ((profile_id, watched_year_month), event_timestamp, video_id) ) WITH CLUSTERING ORDER BY (event_timestamp DESC, video_id ASC) AND compaction = { 'class': 'TimeWindowCompactionStrategy', 'compaction_window_unit': 'DAYS', 'compaction_window_size': 1 };
Unlock Complete Architecture & Production Runbooks
You have explored the free architectural preview (~41%). Spend 1 Coin to unlock the remaining 6 production deep-dive sections for a full 24 hours.