Global Video-on-Demand Streaming Platform
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a global video-on-demand (VOD) streaming platform capable of serving millions of simultaneous viewers while ingesting raw studio releases from content partners.
Your design must fulfill these core product and operational goals:
- Core capabilities: Let viewers explore a title catalog and watch pre-recorded movies or episodes, let studios upload large raw master video files, and maintain uninterrupted playback as a viewer's network bandwidth fluctuates.
- Operational targets: Deliver high availability and horizontal scale across peak evening audiences, sustain massive aggregate video egress throughput, and minimize startup delay (time to first frame, or TTFF) after a viewer presses Play.
Scope & Expectations
- End-to-end architecture & media pipeline: Connect partner ingest, asynchronous transcoding/packaging, origin storage, and edge delivery, showing how raw master uploads become adaptive streamable segments.
- Global edge delivery & startup optimization: Explain how CDN caching, regional traffic steering, and client-side adaptive bitrate (ABR) selection keep TTFF sub-second and mid-stream rebuffering rare worldwide.
- Metadata & activity data modeling: Choose appropriate data stores for catalog/licensing metadata versus high-write viewer watch progress and playback telemetry.
- System trade-offs: Weigh consistency against availability across billing, catalog updates, and bookmarks, as well as storage costs against encoding compute and egress bandwidth.
Step-by-step walkthrough
Clarify requirements and scope
A video-on-demand (VOD) service—where viewers watch pre-recorded movies and shows whenever they choose on a global entertainment platform—is really two very different systems glued together at storage:
- The supply pipeline (ingest and transcoding): Content studios upload a few hundred hours of raw video per day. Transcoding means converting a huge studio video file into smaller, compressed versions that TVs and phones can play. Volume in requests per second is tiny, each job burns hours of CPU, and a half-finished or corrupted file must never become visible to viewers.
- The delivery path (catalog, playback startup, and streaming): Millions of viewers browse and watch the same finished files at the same time. Here the bottleneck is network bandwidth, time to first frame (TTFF)—the delay between pressing Play and seeing the first image on screen—and avoiding mid-movie stalls.
Before sketching boxes, lock down the requirements and ask clarifying questions for the numbers that drive compute, storage, and bandwidth.
Functional requirements
- Viewers browse a catalog of movies and series, resume where they left off, and stream videos.
- Content providers upload raw studio files, metadata, captions, and country licensing schedules.
- Playback adapts smoothly when a viewer's home Wi-Fi or mobile network speeds up or slows down.
Non-functional requirements
- High availability: 99.99% for playback; if a backend database degrades, already-playing streams must keep playing and paid subscribers should still be able to start watching.
- Fast startup: TTFF median (p50) under 1 second and 95th percentile (p95) under 2 seconds on home broadband; rebuffering (mid-stream stalls) under 0.5% of total watch time.
- Scale and ingest SLA: Support millions of concurrent streams at prime-time peak, and make newly uploaded titles playable within a few hours (or guaranteed before a scheduled premiere).
Assumptions from clarifying questions
- User scale: 80M monthly active accounts and 10M concurrent streams during evening peak hours.
- Catalog and daily ingest: 100,000 hours of movies and episodes (80% up to 1080p HD, 20% up to 4K Ultra HD). Providers upload ~500 new hours per day, often in bursts when a full season drops at once.
- Client mix: Primarily living-room smart TVs and connected-TV streaming players on home broadband, plus mobile and web. Because big TV screens stream higher resolutions than phones, assume an average stream bitrate of 5 Mbps.
- Raw source format: Studios deliver a mezzanine file—a near-lossless master video file (for example, Apple ProRes 422 HQ at ~220 Mbps for 1080p, or ~100 GB per hour; ~350 GB per hour for 4K).
- Content protection: Licensed studio titles require DRM (Digital Rights Management)—cryptographic access control (Google Widevine, Microsoft PlayReady, or Apple FairPlay depending on the device)—and per-country licensing windows.
- Out of scope: Subscription billing, dynamic ad insertion, and live broadcasts.
Back-of-the-envelope numbers
Four numbers shape every architectural choice in a VOD platform: peak outbound bandwidth, edge request rate, catalog storage (masters vs. streamable copies), and daily transcoding CPU.
To support smooth playback across devices, each movie is encoded into a bitrate ladder (encoding ladder)—a set of renditions, meaning copies of the same video at different resolutions and bitrates (for example, 240p at 0.3 Mbps up to 4K at 15 Mbps). Video and audio are stored as demuxed (separate) tracks so that supporting 3 audio languages does not require duplicating the much larger video files 3 times.
1) Delivery traffic at evening peak (10M concurrent streams) Peak outbound bandwidth 10M streams x 5 Mbps avg = 50 Tbps (must come from CDNs) Segment fetch rate 4 s segments -> 10M / 4 s = 2.5M video + 2.5M audio = ~5M HTTP GETs/s at CDN edges Playback starts 10M streams / 2,700 s (45 min avg) = ~3,700 starts/s x2 for trailers, retries, zapping = ~7,500 starts/s (API + DRM) Telemetry heartbeats 10M streams / 30 s = ~333,000 events/s to event log Watch-position saves every 60 s or on pause/stop = ~170,000 writes/s Catalog browse calls ~3M active browsers / 10 s per call = ~300,000 reads/s (cacheable) 2) Bitrate ladder per content hour (4-second segments) H.264 video (all devices) 240p (0.3) + 360p (0.7) + 480p (1.2) + 720p (2.5) + 1080p (5.0) = 9.7 Mbps -> ~4.4 GB/hour HEVC video (modern TVs) 1080p (3.5 Mbps) = ~1.6 GB/hour 2160p 4K (15.0 Mbps, 4K titles) = ~6.75 GB/hour Audio (3 languages) AAC stereo (128 kbps) + Dolby 5.1 (640 kbps) = 0.768 Mbps x 3 languages = ~2.3 Mbps -> ~1.0 GB/hour Total per HD hour 4.4 + 1.6 + 1.0 = ~7.0 GB/hour Total per 4K hour 7.0 + 6.75 = ~13.75 GB/hour 3) Total storage (100,000 catalog hours: 80,000 HD + 20,000 4K) Streamable renditions 80,000 x 7.0 GB + 20,000 x 13.75 GB = 560 TB + 275 TB = ~835 TB Studio mezzanine archive 80,000 x 100 GB + 20,000 x 350 GB = 8 PB + 7 PB = ~15 PB (18x!) 4-second segment objects 100,000 h x 900 segs/h x ~12 tracks = ~1.1 billion objects 4) Daily ingest and transcoding (500 new hours/day) Upload volume 500 h x (0.8 x 100 GB + 0.2 x 350 GB) = 75 TB/day (~7 Gbps avg) CPU cost (benchmark est.) ~20 core-hours per HD hour, ~60 per 4K hour -> 28 core-hours avg Daily transcode compute 500 h x 28 core-hours = 14,000 core-hours/day (~580 cores 24/7, spiking to 2,800 core-hours at once for a 100-hour season drop)What these numbers immediately tell us:
- 50 Tbps cannot leave our own servers. Only a CDN (Content Delivery Network)—globally distributed cache servers placed close to users and inside major internet service providers (ISPs)—can deliver 50 Tbps.
- Storage bytes are dominated by the 15 PB studio masters, not the 835 TB of streamable video. Streamable renditions stay in standard object storage (like Amazon S3 Standard at ~20 USD/TB-month, ~17,000 USD/month). Mezzanine masters move after a few weeks to deep archive storage (~1 USD/TB-month, ~15,000 USD/month instead of ~300,000 USD/month) so we can re-encode the catalog years later when newer codecs arrive.
- Transcoding is bursty and embarrassingly parallel, so it belongs on an autoscaled worker queue, not fixed web servers.
- 170,000 watch-position writes per second would overwhelm a single relational primary database; watch progress needs a horizontally partitioned key-value or wide-column store.
API design
We split the APIs into three clean planes: provider ingest APIs, viewer JSON APIs, and CDN media fetches. Application servers only ever handle small JSON payloads; video bytes never flow through our API tier.
For 100–400 GB studio uploads, providers use a multipart upload with presigned URLs—temporary, cryptographically signed URLs that grant the uploader permission to
PUTfixed-size 1 GB slices directly into object storage in parallel. If a network blip drops slice 87, only that 1 GB slice is retried.1) Content provider ingest APIs POST /v1/assets Body: { "title_id": "t_840", "filename": "feature_master.mov", "size_bytes": 360000000000, "sha256": "..." } 200: { "asset_id": "a_4c", "part_size_bytes": 1073741824, "part_urls": ["https://ingest-store.example.com/...signed-part-1...", "..."] } PUT <signed_part_url> -> raw 1 GB slice uploaded straight to object storage POST /v1/assets/{asset_id}:complete -> { "parts": [{ "part_no": 1, "etag": "..." }, ...] } GET /v1/assets/{asset_id} -> { "status": "TRANSCODING", "progress": 0.62 } PUT /v1/titles/{title_id} -> localized titles, synopsis, cast, rating, artwork PUT /v1/titles/{title_id}/availability -> [{ "country": "US", "start_at": "...", "end_at": "..." }] 2) Viewer control-plane APIs GET /v1/home?profile_id=p_1 -> rows of title cards (personalized + editorial) GET /v1/titles/{title_id} -> title metadata, episode list, artwork URLs POST /v1/playback:start Body: { "title_id": "t_840", "profile_id": "p_1", "device": { "drm": ["widevine"], "codecs": ["avc", "hevc"], "max_height": 2160 } } 200: { "session_id": "ps_92", "manifest_url": "https://cdn-a.example.com/tok/<jwt>/v/t_840/v3/master.m3u8", "fallback_urls": ["https://cdn-b.example.com/tok/<jwt>/v/t_840/v3/master.m3u8"], "license_url": "https://drm.example.com/v1/license", "license_token": "...", "resume_at_s": 2140, "token_ttl_s": 21600 } POST /v1/drm/license -> device DRM challenge + license_token -> decryption keys POST /v1/playback/{session_id}/events -> 30 s heartbeats (position_s, bitrate, buffer_s, stall_ms) 3) CDN media path (pure cacheable HTTP GETs; zero backend app servers involved) GET https://cdn-a.example.com/tok/<jwt>/v/t_840/v3/master.m3u8 (or manifest.mpd) GET https://cdn-a.example.com/tok/<jwt>/v/t_840/v3/hevc_1080p/0058.m4sWhy this API boundary works so well:
- All business rules run once at
playback:start. That single call checks subscription status, verifies country licensing rights, filters out codecs the TV cannot decode (for example, omitting 4K on a 1080p TV), chooses the healthiest CDN for the viewer's ISP, and returns signed URLs. - Versioned URLs (
/v3/) make media immutable. Re-encoding a movie or fixing audio sync publishes/v4/alongside/v3/instead of overwriting files in place. - Built-in client failover. Returning
fallback_urlson a second CDN lets the player switch automatically if CDN A starts timing out mid-movie.
- All business rules run once at
Data model and consistency choices
Different parts of a VOD service have completely different read/write shapes and tolerance for staleness. Strong consistency means every read immediately sees the latest committed write; eventual consistency means replicas catch up within seconds so writes stay fast and highly available even during network hiccups.
Relational metadata & workflow state (PostgreSQL primary + read replicas) titles title_id (PK), kind (movie | series | episode), parent_id, duration_s, localized_meta (JSONB), maturity_rating, active_version availability (title_id, country) PK, start_at, end_at, subscription_tier asset_versions (title_id, version) PK, status (UPLOADING..READY), mezzanine_key, ladder_spec (JSONB), manifest_keys, drm_key_ids, created_at transcode_jobs job_id (PK), title_id, version, priority (launch | new | backfill), state transcode_tasks task_id (PK), job_id, step, rendition, chunk_idx, state, attempts, lease_expires_at, output_key Account & billing state (PostgreSQL primary + synchronous standby + 60 s Redis cache) accounts account_id (PK), email, home_country, plan_tier entitlements account_id (PK), status (active | past_due | canceled), paid_through profiles profile_id (PK), account_id, display_name, maturity_cap, locale High-write user interaction stores watch_progress Wide-column store (Cassandra / DynamoDB), multi-region: Partition key: profile_id | Sort key: title_id Columns: position_s, duration_s, is_finished, updated_at playback_events Append-only Kafka stream -> hourly Parquet files in object-storage data lake: session_id, profile_id, title_id, cdn, isp, device, ts, bitrate, stall_msWhy each store and consistency level fits its job:
- Catalog metadata (~6 GB total for 300,000 movies and episodes at ~20 KB each) easily fits in memory and CDN edge caches. Eventual consistency (1–2 minutes for a typo fix in a movie description to appear everywhere) is completely invisible to users.
- Publishing (
titles.active_version) and entitlements use strong writes. We must never pointactive_versionat a half-transcoded video. For entitlements, we cache "active subscriber" decisions for 60 seconds in Redis—and if the billing database goes down, we honor cached active tokens for up to 24 hours so paying viewers are never locked out during an internal outage. - Watch progress (~900 GB for 150M profiles × 100 watched titles × 60 bytes) absorbs 170,000 writes/s in a wide-column store—a distributed NoSQL database that partitions rows across many machines by
profile_idand resolves concurrent updates with last-write-wins (LWW) (keeping whichever write has the newest timestamp). Fetching a user's "Continue Watching" row reads just one partition.
High-level architecture
Content Providers | 1. Presigned multipart PUT (1 GB slices) v [ Object Storage: Mezzanine Bucket ] ---> lifecycle move after 30 days ---> [ Deep Archive ] | 2. "Upload Complete" event v [ Workflow Orchestrator ] <---> [ Jobs / Tasks DB (PostgreSQL) ] | 3. Enqueue tasks (launch / new / backfill) v [ Priority Task Queues ] <===> [ Autoscaled Transcode Workers (Spot + On-Demand) ] probe -> chunk encode -> audio/subs -> VMAF QC -> CMAF encrypt | 4. Write immutable versioned segments (/v/t_840/v3/...) v [ Object Storage: Renditions Origin ] | 5. Cache misses only (~1% of peak bytes) v [ Regional Origin Shields (per CDN) ] | +-------------------+------------------------+ v v v [ CDN A Edges ] [ CDN B Edges ] [ ISP-Embedded Caches ] \ | / \========= 6. 50 Tbps HLS / DASH segments / v [ TV, Mobile, and Web Players ] | | 7. Browse, playback:start, DRM license, 30 s heartbeats v [ API Gateway ] |-- Catalog & Home Service (Redis precomputed rows + Search + CDN JSON cache) |-- Playback Service (Entitlement cache, Rights snapshot, Multi-CDN steerer) |-- DRM License Service (HSM-backed content key store) |-- Watch Progress Service --> [ Cassandra / DynamoDB ] '-- Event Collector ---------> [ Kafka ] --> QoE Monitoring & Recs Data LakeTrace how the two halves stay decoupled:
- Supply trace: A studio uploads
feature_master.movstraight to the mezzanine bucket. The orchestrator fans out hundreds of short worker tasks that write encrypted 4-second segments to/v/t_840/v3/...in the origin bucket, verifies quality, and atomically flipstitles.active_version = 3. - Playback trace: When a viewer presses Play,
Playback Servicereturns a signed manifest URL in ~80 ms, the player fetches decryption keys fromDRM License Service, and for the next two hours the TV pulls video segments solely from CDN edges while sending tiny 30-second JSON heartbeats toEvent Collector.
- Supply trace: A studio uploads
Deep dive 1: Asynchronous transcoding pipeline
Encoding a 2-hour 4K movie takes ~120 CPU core-hours—roughly 7.5 hours if run start-to-finish on one 16-core machine, and a crash at minute 400 would lose everything. We solve both speed and reliability by turning one giant video into a directed acyclic graph (DAG) of small, independent worker tasks.
Upload Complete --> [1. Inspect & Probe] Verify SHA-256, check codec, frame rate, audio channels (1 task) --> [2. Per-Title Probe] Fast sample encode to pick bitrates tailored to visual complexity (1 task) --> [3. Split & Encode] 60 chunks (120 s each) x 7 video renditions (420 tasks, parallel) 3 audio languages + WebVTT/TTML subtitles + 10 s scrub thumbnails --> [4. Verify & Index] Confirm exact keyframe alignment across all 7 renditions (7 tasks) --> [5. Automated QC] Check VMAF perceptual quality, silent audio, black frames (7 tasks) --> [6. Package & Encrypt] Write CMAF (.m4s) segments + HLS (.m3u8) + DASH (.mpd) (1 task) --> [7. Atomic Publish] Mark version READY, then flip titles.active_version = v3 (1 task)Why mezzanine chunks can be encoded in parallel with zero visual seams:
- Every frame in a studio mezzanine file (like ProRes) is a keyframe (I-frame)—a complete, standalone picture that does not depend on earlier frames to decode (unlike compressed predicted frames that only store motion differences). Thus Worker 17 can seek straight to
t = 2,040 sand encode its 120-second slice without reading the first 34 minutes. - Forced keyframes every 4 seconds create closed GOPs. A GOP (Group of Pictures) is the span of frames from one keyframe to the next; a closed GOP means no frame inside a 4-second segment ever references a frame outside that segment. Because every rendition (
360p,720p,1080p,4K) places a closed-GOP keyframe at exact multiples of 4.0 seconds (0 s, 4 s, 8 s, ...), a player can switch from720psegment 10 to1080psegment 11 seamlessly.
import math SEGMENT_SECONDS = 4 def plan_encode_tasks(version_id: str, duration_s: int, renditions: list[str], chunk_s: int = 120) -> list[dict]: """Split a title into independent (rendition, chunk) tasks with deterministic output keys.""" # Chunk length must be an exact multiple of 4 s so chunk boundaries align with ABR segments. if chunk_s % SEGMENT_SECONDS != 0: raise ValueError("chunk_s must hold a whole number of 4-second segments") num_chunks = math.ceil(duration_s / chunk_s) # tasks: list of task dicts; deterministic output_key makes worker retries idempotent tasks = [] for rendition in renditions: for chunk_idx in range(num_chunks): start_s = chunk_idx * chunk_s end_s = min(duration_s, start_s + chunk_s) output_key = f"enc/{version_id}/{rendition}/chunk_{chunk_idx:05d}.mp4" tasks.append({ "task_id": f"{version_id}/{rendition}/{chunk_idx}", "rendition": rendition, "start_s": start_s, "end_s": end_s, "output_key": output_key, }) return tasksHow the asynchronous worker fleet stays fast, cheap, and fault-tolerant:
- Priority queues + spot instances: Tasks route to three queues:
launch(premieres within 48 hours, backed by reserved on-demand VMs),new(normal daily uploads), andbackfill(catalog re-encodes).newandbackfillrun on cheap cloud spot instances because losing a preempted VM wastes at most one ~5-minute chunk task. - Time-bounded leases and deterministic keys: A worker claims a task under a lease—a temporary 15-minute ownership timer renewed by 1-minute heartbeats. If the worker crashes, the lease expires and another worker re-runs the task, safely overwriting the exact same
output_key. After 3 failed attempts (for example, a corrupt input file), the task moves to a dead-letter queue (DLQ)—a holding queue for permanently failing jobs—and fires a webhook telling the studio why the file failed. - Per-title bitrate optimization and VMAF QC: A 2D cartoon compresses cleanly at 1.8 Mbps for 1080p, whereas a grainy action film needs 5.5 Mbps. Running a cheap sample pass first customizes the ladder per title, saving 20–30% of CDN bandwidth on every view. Automated QC computes VMAF (Video Multimethod Assessment Fusion)—an industry-standard perceptual video quality score from 0 to 100 that predicts how sharp the video looks to human eyes—blocking publication if any rendition drops below threshold.
- Single-copy CMAF packaging and tiered DRM: Apple devices prefer HLS (
.m3u8text playlists) while Android and many smart TVs use DASH (.mpdXML manifests). By storing media in CMAF (Common Media Application Format)—fragmented MP4 files encrypted with the sharedcbcsAES standard—both HLS and DASH manifests point to the exact same media bytes instead of doubling our 835 TB storage. (Note: to avoid managing 1.1 billion tiny.m4sobjects in S3, we can pack each rendition into a single indexed CMAF.mp4object—~1.2M objects total—and let CDN caches fetch 4-second byte ranges via HTTPRangeheaders.) Separate DRM keys protect SD vs. HD/4K tracks so compromised software-only devices can never decrypt 4K streams.
- Every frame in a studio mezzanine file (like ProRes) is a keyframe (I-frame)—a complete, standalone picture that does not depend on earlier frames to decode (unlike compressed predicted frames that only store motion differences). Thus Worker 17 can seek straight to
Deep dive 2: Multi-tier CDN caching, immutable versions, and regional steering
Delivering 50 Tbps reliably while keeping origin traffic tiny relies on a three-tier caching hierarchy:
[ Viewers: 50 Tbps ] ^ 95% edge cache hit (popular ~15% of catalog drives ~85-95% of views) [ Tier 1: ISP-Embedded Caches & CDN Edge PoPs (hundreds of locations worldwide) ] ^ 2.5 Tbps edge misses -> 80% absorbed by regional shields [ Tier 2: Regional Origin Shields (1 per CDN per continent, request coalescing on) ] ^ 0.5 Tbps shield misses (5% x 20% = 1% of peak traffic) [ Tier 3: Object Storage Origin ]Sharing one cached copy across millions of authenticated viewers: If we put each user's auth signature in a URL query string (
.../0058.m4s?sig=user99), two bad things happen: relative segment URLs inside HLS playlists drop the master playlist's query string, and naive CDNs treat every user's URL as a separate cache entry (0% cache hit rate!). Instead:playback:startembeds a short-lived signed token (title ID, allowed country, 6-hour expiry) as a URL path prefix:/tok/<signed_token>/v/t_840/v3/hevc_1080p/0058.m4s. Relative URLs inside playlists automatically inherit that path prefix!- The CDN edge verifies the HMAC signature in
<signed_token>at the border using shared keys (zero backend calls), checks that the viewer's geo-IP matches the token's country, and strips/tok/<signed_token>before looking up its cache key (/v/t_840/v3/hevc_1080p/0058.m4s). Millions of viewers now hit the exact same cached segment.
Cache invalidation: design so you almost never need it:
- Because every manifest and segment path contains
/v3/, cached bytes are immutable (Cache-Control: public, max-age=31536000, immutable). - Fixing a bad subtitle or re-encoding video writes
/v4/objects, then updatestitles.active_version = 4in PostgreSQL. Newplayback:startcalls immediately hand out/v4/URLs, active viewers finish watching/v3/smoothly without manifest mismatches, and/v3/segments naturally evict from CDN caches via least-recently-used (LRU) eviction. - Only urgent legal takedowns trigger an explicit CDN path-prefix purge (
/v/t_840/*) paired with blocking new tokens and DRM licenses at the control plane.
Region-based routing, multi-CDN steering, and off-peak pre-positioning:
- Multi-CDN control-plane steering:
Playback Servicemaintains a live quality table grouped by(country, ISP, CDN)updated every minute from player telemetry (rebuffering rate and TTFF). If CDN A develops congestion on Comcast in Chicago,Playback Serviceshifts new Chicago Comcast sessions from a 70/30 split to 0/100 onto CDN B within minutes, while mid-stream TVs fail over automatically viafallback_urls. - Edge PoP routing: Within the chosen CDN, anycast (advertising the same IP from many locations so internet routers pick the closest hop) or geo-DNS directs the TV to a nearby PoP (Point of Presence) or a dedicated cache appliance rack installed directly inside the viewer's ISP network.
- Off-peak push vs. long-tail pull: At 3 AM local time when ISP links sit idle, we proactively push upcoming releases and top-1,000 trending titles into ISP caches so 8 PM prime-time hits 99%+ locally. Long-tail classics are fetched on demand (pull-cached) through the origin shield.
Deep dive 3: Adaptive bitrate streaming and fast startup
Adaptive bitrate (ABR) streaming—used by both HLS (HTTP Live Streaming) and DASH (Dynamic Adaptive Streaming over HTTP)—solves fluctuating network speeds by letting the video player choose the quality of every 4-second chunk independently right before downloading it.
To hit a sub-second TTFF on living-room TVs, we engineer every millisecond of the startup critical path:
Viewer highlights movie tile on TV remote for >= 1.0 s (before pressing Play!): -> Prefetch playback:start + master playlist + DRM license in background (rate-limited) Viewer presses Play (critical path when prefetched vs. cold): 1. playback:start API (cached entitlement + rights) ~80 ms cold | 0 ms prefetched 2. Fetch HLS/DASH manifest from local CDN edge ~40 ms cold | 0 ms prefetched 3. Fetch DRM decryption license (parallel with #4) ~120 ms cold | 0 ms prefetched 4. Download init header + seg 0 at 480p (1.2 Mbps) ~200 ms | ~200 ms (0.6 MB @ 25 Mbps) 5. Hardware video decode -> render first frame ~100 ms | ~100 ms ----------------------------------------------------------------------------------------------- Total Time to First Frame (TTFF) ~450 ms p50 | ~300 ms p50 (p95 < 2.0 s)Four design choices make startup fast and playback stall-free:
- Prefetch on remote focus: On connected-TV directional-pad interfaces, a viewer moves a highlight selector across movie posters before clicking OK. Once the highlight rests on a poster for 1 second, the app prefetches the manifest and DRM license over already-open HTTP/2 connections.
- Start modest, ramp fast: Downloading the first 4-second segment in 4K (15 Mbps = 7.5 MB) would take 2.4 seconds on a 25 Mbps link! Starting at 480p or 720p (~0.6–1.2 MB) puts video on screen in ~300–450 ms, then ramps to 1080p/4K over the next 2–3 segments.
- 4-second segments instead of 10-second segments: Smaller segments shrink the initial download and let the player drop bitrate within 4 seconds when someone starts a microwave or large download on home Wi-Fi.
- Buffer-aware harmonic-mean ABR controller: Averaging recent download speeds with a plain arithmetic mean is dangerous: four fast downloads (
20 Mbps) plus one congested download (2 Mbps) give an arithmetic mean of16.4 Mbps, tricking the player into requesting 4K (15 Mbps) right as Wi-Fi collapses! Instead, players use the harmonic mean—the reciprocal of the average of reciprocals—which weights slow outliers heavily (5 / (4/20 + 1/2) = 7.1 Mbps), multiplied by a buffer-dependent safety factor:
def harmonic_mean_kbps(samples_kbps: list[float]) -> float: """Compute harmonic mean of positive throughput samples so one slow dip pulls the estimate down.""" reciprocal_sum = 0.0 for speed in samples_kbps: # Clamp to >= 1.0 kbps so a completely stalled probe never causes division by zero. safe_speed = max(speed, 1.0) reciprocal_sum += 1.0 / safe_speed return len(samples_kbps) / reciprocal_sum def choose_next_bitrate( ladder_kbps: list[int], recent_throughputs_kbps: list[float], buffer_seconds: float, ) -> int: """Pick the highest rendition in sorted ladder_kbps that fits our safe bandwidth budget.""" if not recent_throughputs_kbps: return ladder_kbps[0] # Estimate network speed from the last 5 segment downloads. estimated_kbps = harmonic_mean_kbps(recent_throughputs_kbps[-5:]) # Low playback buffer -> be very conservative to prevent a stall; healthy buffer -> use 90%. if buffer_seconds < 8.0: safety_factor = 0.50 elif buffer_seconds < 20.0: safety_factor = 0.75 else: safety_factor = 0.90 safe_budget_kbps = estimated_kbps * safety_factor # Walk ascending ladder and keep the highest bitrate <= safe_budget_kbps. chosen_kbps = ladder_kbps[0] for rate_kbps in ladder_kbps: if rate_kbps <= safe_budget_kbps: chosen_kbps = rate_kbps return chosen_kbpsIn production, the player also requires 3 consecutive comfortable segments before switching up (hysteresis, so picture sharpness does not flicker every 4 seconds), switches down immediately on buffer drain, caps resolution at the TV's physical panel height, and stops buffering past ~30 seconds ahead so early exits do not waste CDN gigabytes.
Scaling, failure handling, and key trade-offs
Scaling bottlenecks and how each tier grows
- CDN egress (50 Tbps): Scaled via ISP-embedded caches, dual-CDN contracts, HEVC/AV1 codecs (~30% bitrate savings over H.264), and per-title encoding ladders.
- Control-plane APIs (
playback:startat 7,500/s, browse at 300,000/s): Stateless regional containers across 3+ regions. Browse rows are served from CDN JSON caches (editorial rows) and Redis (precomputed personalized rows);playback:startchecks cached entitlements and in-memory rights snapshots with zero live SQL queries on the hot path. - Watch progress (170,000 writes/s) & QoE telemetry (333,000/s): Watch progress scales horizontally by
profile_idacross Cassandra/DynamoDB nodes; raw QoE heartbeats stream into partitioned Kafka topics.
Failure modes and graceful degradation
Failure scenario Impact if unhandled How the architecture handles it Spot transcode worker preempted Encoding job hangs 15-minute task lease expires; another worker re-encodes that 120 s chunk to the same deterministic key Bad upload or VMAF QC failure Viewers see glitches Version never flips titles.active_version; previous version stays live and studio gets failure webhookCDN A brownout on one ISP Regional buffering spike Player switches to fallback_urlson CDN B immediately; control-plane steerer shifts new sessions in < 2 minOrigin object storage degraded Uncached titles fail Origin shields serve immutable cached segments indefinitely; top titles are already at edges/ISP caches Playback API region outage New plays fail in region Geo-DNS fails over to sibling region; active streams keep playing uninterrupted from CDN edges for up to 6 h Billing / entitlement DB down Paid users locked out Honor cached positive entitlements in Redis for up to 24 h (grace-period fail-open for known subscribers) Summary of core trade-offs
- 4-second vs. 10-second segments: 4-second segments cut startup download size and adapt faster to Wi-Fi drops, trading away ~1.5–2.5x higher CDN request rates and a small keyframe compression overhead.
- Pre-encoding the full ladder + per-title probe vs. on-demand encoding: Spending CPU once at ingest (storing < 1 PB of renditions) guarantees zero compute latency at play time and saves far more money on 50 Tbps CDN bandwidth.
- 15 PB mezzanine archive vs. deleting raw masters: Deep archive storage (~15,000 USD/month) preserves the ability to re-encode the catalog for next-generation codecs like AV1, accepting multi-hour retrieval delays on archive restores.
- Immutable versioned URLs vs. in-place CDN purges: Versioning eliminates stale-cache bugs and mid-playback manifest mismatches, requiring off-peak pre-positioning so major new versions do not start cold.
Intuition & how it works
Think of a video-on-demand (VOD) service like publishing a bestselling book worldwide instead of printing pages live while a reader waits. A movie studio hands you one fragile, gigantic master manuscript—a mezzanine file (a near-lossless studio master video that can exceed 350 GB for a single 4K movie). Instead of trying to stream that giant file from your own servers, a back-office factory chops the movie into 2-minute slices, converts them in parallel on hundreds of worker machines into 7 quality levels (from tiny 240p up to crisp 4K), cuts every quality level into aligned 4-second chapters, and stocks neighborhood kiosks—a CDN (Content Delivery Network), meaning cache servers placed inside local cities and internet providers—close to every viewer. When someone presses Play on their TV, your backend only checks their subscription and hands them a tiny table of contents called a manifest; for the next two hours, the TV fetches 4-second chapters straight from the nearest kiosk and shifts quality up or down smoothly whenever home Wi-Fi speeds change.
The naive approach—uploading an MP4 file to a web server and streaming it straight to users over a single HTTP connection—collapses immediately at scale. First, 10 million concurrent TV streams at 5 Mbps equals 50 Terabits per second (Tbps) of outbound traffic, hundreds of times more bandwidth than a cloud data center exit can carry. Second, a single fixed-bitrate file stalls whenever a user's connection dips, whereas transcoding synchronously inside the upload HTTP request would block for 7+ hours and lose all progress if one server crashed.
Walk through a concrete 5-step trace of one 2-hour movie (7,200 s) from upload to living-room screen:
- Upload: The studio uploads a 350 GB master in 350 parallel 1 GB parts straight into object storage.
- Parallel transcode: An orchestrator splits the 7,200 seconds into
60two-minute chunks across7bitrates (420short worker tasks), producing 4-second segments (1,800segments per track) under immutable version/v/t_840/v3/in under 30 minutes, then flipsactive_version = 3. - Prefetch on focus: When a viewer highlights the movie poster on their TV remote for 1 second, the app quietly prefetches the
/v3/manifest and DRM (Digital Rights Management) decryption key. - Sub-second start: The viewer clicks Play; the TV downloads segment
0(0–4 s) at a modest 1.2 Mbps (0.6 MB, taking~200 mson 25 Mbps broadband) and renders the first frame in~0.4 s. - Adaptive ramp-up: Measuring 25 Mbps of real download speed, the TV steps up to 1080p (
5 Mbps) by segment2(8–12 s) and streams the rest from the local CDN cache without touching your application servers for video bytes.
Key trade-offs
- Segment duration (4 seconds vs. 6–10 seconds): Adaptive bitrate (ABR) streaming cuts video into independent chunks starting with a keyframe (a complete standalone image frame) so the player can switch quality at every chunk boundary. Using 4-second segments keeps the initial startup download tiny (
~0.6 MBat 1.2 Mbps) and lets the player drop bitrate within 4 seconds of a Wi-Fi dip, trading away 1.5–2.5x more CDN HTTP requests and slightly lower video compression efficiency than 6- or 10-second segments. - Pre-computing renditions and per-title ladders vs. on-demand compute: Pre-encoding all 7 renditions up front stores
~835 TBacross a 100,000-hour catalog—cheap in object storage—so playback never waits on a live encoder. Running an extra sample pass per title to customize bitrates (lower bitrates for simple animation, higher for fast action) spends CPU once to save 20–30% on 50 Tbps CDN egress across millions of views. - Archiving 15 PB of mezzanine masters vs. deleting them: Keeping raw studio masters (
18xlarger than the streamable copies) in deep archive storage (~1 USD/TB-month, or~15,000 USD/month) preserves the ability to re-encode the entire catalog when better codecs like AV1 mature, at the cost of multi-hour restore times when pulling old files out of archive. - Single-copy CMAF packaging vs. per-protocol storage: Apple devices require HLS playlists while Android and many TVs use DASH manifests. Packaging encrypted fragmented MP4 chunks once in CMAF (Common Media Application Format) lets both HLS and DASH point to the exact same media bytes, avoiding double storage unless legacy devices force a second older encryption mode (
cencalongsidecbcs). - Immutable versioned URLs vs. CDN cache invalidation: Embedding
/v3/in every manifest and segment URL means cached bytes never change, eliminating stale-segment bugs and mid-movie audio/video mismatches. The trade-off is that publishing/v4/starts with cold caches unless popular titles are pre-positioned during off-peak hours. - Multi-CDN + ISP caches vs. single CDN: Contracting two CDNs plus placing cache appliances inside major ISPs prevents single-provider outages and lowers transit bills, at the cost of building real-time traffic-steering logic and warming two sets of regional origin shields (middle-tier caches that protect object storage).
- Strong vs. eventual consistency by data type: Subscription entitlements, country rights, and flipping
active_versionuse strongly consistent writes (with a 24-hour cached fail-open grace window for active subscribers if the billing database goes down). Watch progress (170,000 writes/s) and catalog browsing use eventual consistency (replicas catch up within seconds), because nobody minds a 2-second lag on a resume bookmark.
Common mistakes
- Streaming video bytes through backend application servers or a single data center, missing the back-of-the-envelope math that 10M streams × 5 Mbps = 50 Tbps.
- Transcoding synchronously inside the upload request or as one monolithic 8-hour job, instead of splitting into short, idempotent 2-minute chunk tasks managed by queues and expiring worker leases.
- Misaligned keyframes across renditions, which makes switching from 720p to 1080p freeze or show corrupted macroblocks because segment 11 in 1080p depends on frames from segment 10.
- Putting per-user auth tokens in URL query strings without stripping them at the CDN edge, which either breaks relative HLS segment URLs or gives every viewer a separate cache key (collapsing CDN cache hit rate toward 0%).
- Overwriting segment files in place and relying on slow, error-prone CDN cache purges, instead of immutable versioned paths (
/v3/->/v4/). - Starting playback at 4K (15 Mbps) or picking bitrates using an arithmetic mean alone, causing 2–3 second startup delays and frequent stalls when one slow download is masked by four fast ones.
- Writing 30-second watch-progress heartbeats directly to the primary SQL database, which melts under 170,000–333,000 writes per second instead of routing progress to a partitioned wide-column store and telemetry to Kafka.
- Forgetting studio mezzanine storage (
15 PB) when estimating costs, sizing only the835 TBof compressed streaming renditions.
Follow-up questions
- How do you prevent CDN and control-plane meltdowns when millions of viewers press Play simultaneously on a major premiere? For a scheduled premiere, encode days ahead, push segments into ISP caches and CDN edges during 3 AM off-peak windows, and pre-scale the stateless
playback:startand DRM license services for the thundering herd (for example, 5M viewers pressing Play within 10 minutes adds~8,300 starts/son top of normal load). Enable request coalescing (collapsing thousands of simultaneous misses for segment 0 into a single upstream fetch) at every CDN edge and origin shield, and add randomized client retry jitter. If regional CDN bandwidth still nears saturation—say 5M viewers averaging 8 Mbps adds 40 Tbps—playback:startcan temporarily omit the 15 Mbps 4K track from manifests in congested ISPs, cutting peak bandwidth roughly in half so everyone watches crisp 1080p instead of buffering; for unplanned breakout hits, an automated detector watching starts-per-minute triggers background edge pre-positioning as soon as a title crosses a velocity threshold. - How would you architect a personalized home-page recommendation pipeline driven by viewer watch events? Consume the existing
playback_eventsKafka stream into both a data lake (for nightly model training) and a real-time stream processor (for in-session signals), then run a two-stage pipeline. First, candidate generation narrows 100,000 titles down to ~500 candidates per profile using co-watch graphs ("users who watched X also watched Y"), a two-tower neural embedding model, and regional trending lists; second, a ranking model scores each candidate's probability of a qualified watch (say >= 5 minutes watched) using genre affinity, recency, device type, and time of day, then filters by country licensing rights and profile maturity ratings. Precompute and cache ranked home-screen rows perprofile_idin Redis (refreshing whenever a user finishes a title) soGET /v1/homestays a single fast key-value read, and validate changes offline with NDCG/recall@K and online via A/B tests measuring streaming hours and monthly retention. - Which client-side Quality of Experience (QoE) signals would you track and slice to catch playback regressions early? Collect QoE telemetry directly from the client video player—because server logs look completely green when an ISP link drops packets—and track time to first frame (TTFF) at p50 and p95, video start failure rate (errors before frame 1), exit-before-video-start rate (viewers abandoning slow startups), rebuffering ratio (
stall_time / total_watch_time), average played bitrate, and bitrate switches per hour. Crucially, slice every metric by(CDN, ISP, country, device_model, app_version)rather than watching global averages alone, because real incidents almost always hit one slice (such as one TV firmware build or one CDN on a single ISP) without moving the global mean. Feed per-ISP stall and TTFF anomalies directly into the automated multi-CDN traffic steerer so degraded routes are drained within minutes.
Follow-up questions
- How do you prevent CDN and control-plane meltdowns when millions of viewers press Play simultaneously on a major premiere?
- How would you architect a personalized home-page recommendation pipeline driven by viewer watch events?
- Which client-side Quality of Experience (QoE) signals would you track and slice to catch playback regressions early?
Similar questions
- Real-Time Bidding Ad Exchange at 1M QPS
- Longest Common Subsequence Length
- Decomposing Squared Prediction Error into Bias and Variance
- Communicating Bias-Variance Tradeoffs to Business Leaders
- Java Concurrent Maps, Cache Partitioning, and Batch Joins
- Causal Engagement Lift from Optional Speaker Adoption
More Roku interview questions
- Longest Common Subsequence Length Medium
- Real-Time Bidding Ad Exchange at 1M QPS Medium
- Communicating Bias-Variance Tradeoffs to Business Leaders Easy Pro
- Decomposing Squared Prediction Error into Bias and Variance Medium Pro
- Java Concurrent Maps, Cache Partitioning, and Batch Joins Medium Pro
- Causal Engagement Lift from Optional Speaker Adoption Medium Pro
- Rolling 7-Day Gross Profit by Category Medium Pro