Design a Global On-Demand Video Streaming Platform
Hard · System Design · Software Engineer · Onsite
Prompt
Architect a global subscription video-on-demand (SVOD) platform. Subscribers browse genre pages and curated home-screen rows (including "Recently Added", "Top Ten", and personalized recommendations), run typo-tolerant faceted search across titles, cast, and tags, watch adaptive-bitrate (ABR) streams across web browsers, iOS, Android, and smart TVs, and pick up playback from their last watched timestamp across sessions and devices. On the supply side, studios and individual creators upload source videos (1–10 GB masters) through a multipart ingestion pipeline that validates, transcodes, packages, and publishes streamable renditions.
Base your design on ~50M daily active users (DAU) and ~5M simultaneous streams at peak across multiple geographic regions (refining assumptions explicitly where needed). Meet strict targets for time-to-first-frame, low rebuffering, multi-region availability, graceful failure degradation, QoE observability, guardrail-backed A/B experimentation, bandwidth/encoding cost efficiency, and content security (tokenized edge URLs everywhere plus multi-DRM licensing on studio content). Explicitly contrast what you would ship for a lean ~100k-DAU MVP focused on browse, play, and resume against the full 50M-DAU architecture, calling out invariants that remain mandatory from day one.
Scope & Expectations
- Scale sizing, architecture & data models: Egress bandwidth, control-plane QPS, and storage estimates; service boundaries and API contracts for browsing, search, playback lifecycle, progress sync, and multipart uploads; polyglot schemas for catalog metadata, ABR assets, rankings, household profiles, active sessions, and watch history.
- Ingest, ABR packaging, DRM & CDN delivery: Chunked transcoding and ladder selection, shared CMAF segments across HLS and DASH, subtitles/thumbnails, Widevine/FairPlay/PlayReady CENC licensing, per-device capability fallback, multi-CDN origin shielding, and cache-key/TTL rules.
- Identity, entitlements, concurrency & rails: Household sign-in and smart-TV pairing, profile maturity controls, regional licensing windows, lease-based concurrent-stream enforcement, conflict-free cross-device resume, search indexing/cold-start recommendations, and materializing
"Recently Added"and"Top Ten"rankings. - Reliability, observability, security & cost controls: Multi-region failover and domain consistency models, client QoE telemetry and A/B testing guardrails, degradation playbooks for partial outages, anti-piracy/credential-abuse protections, and levers governing CDN egress and encoding spend.
Step-by-step walkthrough
Clarify requirements, scope, and the MVP cut line
A global video-on-demand (SVOD) platform is really two very different systems working together: - A control plane (our backend APIs and databases) that decides who can watch what, enforces account limits, serves catalog rows, and remembers where each viewer paused. - A data plane (a global network of edge caches) that delivers massive volumes of video bytes directly to screens without touching our application servers.
Naming that split first keeps every architectural decision grounded.
Functional requirements (full 50M-DAU platform)
- Catalog browse: A personalized home screen made of horizontal rows ("rails")—genre rows, editorial rows (
"Recently Added","Top Ten"),"Continue Watching", and ML-personalized rows—plus title detail pages with seasons and episodes. - Search: Typo-tolerant full-text search across titles, cast, and tags, with facets (genre, release year, language) and instant typeahead suggestions.
- Adaptive playback: Smooth adaptive bitrate (ABR) video streaming (automatically switching video quality mid-stream as the viewer's internet speeds up or slows down) across web browsers, iOS, Android, and smart TVs, with multi-language audio and subtitles.
- Cross-device resume: Save playback progress per profile so pausing on a TV lets the viewer pick up at the same timestamp on a phone seconds later.
- Accounts, profiles, and rights: Up to 5 profiles per account, maturity ratings with parental PINs, regional licensing windows, and plan-based caps on resolution and simultaneous streams.
- Content ingestion: Studios upload 1–10 GB master files (plus smaller user-generated content, or UGC, uploads) that become streamable automatically after validation, encoding, and packaging.
Non-functional targets
- Fast startup: Time to first frame (TTFF) (delay between pressing Play and seeing the first moving picture) of
p50 <= 1.5 sandp95 <= 3.0 son broadband. - Smooth playback: Rebuffering under
0.5%of total watch hours; play-start failure rate under0.5%. - High availability:
99.99%for playback start and license issuance;99.9%for catalog browse (which may gracefully fall back to unpersonalized cached rows). - Resume durability: At most
60 sof progress lost on an unexpected crash, and< 10 scross-device sync after an explicit pause or stop. - Content protection: Short-lived signed URLs on all media, plus studio-grade DRM (Digital Rights Management) encryption on licensed content.
Explicitly out of scope: Payment card processing (an external billing service emits plan status), live broadcasts, ad insertion, offline downloads, and social comments.
MVP cut line (~100k DAU: browse, play, resume) vs. non-negotiables
At 100k DAU (~10k peak concurrent streams × 4 Mbit/s =
40 Gbit/speak egress), we still must put a CDN in front of video bytes, yet the entire control plane fits comfortably in a single cloud region on one primary PostgreSQL database plus Redis.SHIP IN DAY-1 MVP (~100k DAU) DEFER TO FULL SCALE (50M DAU) Single commercial CDN + signed cookies/URLs Multi-CDN QoE steering + ISP-embedded caches Managed multi-DRM service + fixed H.264 ladder Per-title VMAF ladders + HEVC / AV1 + 4K HDR CMAF segments shared across HLS and DASH Forensic A/B watermarking + anti-sharing ML Web, iOS, and Android players Smart TV apps & QR pairing + legacy DRM modes Server-side entitlement, region & stream checks ML recommendations (start with editorial rails) Durable resume + SQL-computed Top Ten rails Real-time streaming rankings & A/B platform Studio multipart uploads + managed transcoding Public UGC uploads (needs copyright/moderation)Non-negotiable at any scale: Server-side checks for subscription entitlement, country licensing windows, and maturity ratings at play start; DRM + tokenized CDN URLs (required by studio contracts); immutable versioned segment URLs; atomic per-account stream-slot enforcement; deterministic cross-device resume ordering; and player TTFF/error telemetry from day one.
- Catalog browse: A personalized home screen made of horizontal rows ("rails")—genre rows, editorial rows (
Back-of-the-envelope sizing
Let us size all three dimensions—video egress, control-plane QPS, and storage—for 50M daily active users (DAU) and 5M peak concurrent streams, showing each unit conversion clearly.
1. DATA PLANE EGRESS (5M peak concurrent streams, ~4 Mbit/s average video + audio) Peak bandwidth 5,000,000 streams x 4 Mbit/s = 20,000,000 Mbit/s = 20 Tbit/s Bytes per watch hour 4 Mbit/s / 8 bits/byte = 0.5 MB/s -> x 3,600 s = 1,800 MB = 1.8 GB/h Daily egress 50M DAU x 1 h/day x 1.8 GB = 90,000,000 GB = 90 PB/day (Sanity check: 90 PB/day = ~8.33 Tbit/s daily average; 20 Tbit/s peak is ~2.4x) Daily egress cost At $0.002/GB blended CDN/peering rate: 90M GB x $0.002 = ~$180,000/day Edge segment QPS 4-second segments -> 5M / 4 s = 1.25M video req/s + 1.25M audio req/s = ~2.5M segment requests/s absorbed by CDN edge servers Origin shield load At 98% edge cache hit ratio, 2% miss = 400 Gbit/s -> collapsed by regional origin shields before touching cloud object storage 2. CONTROL PLANE HTTP QPS (at evening peak) Playback heartbeats 5M active streams / 30 s interval = ~167,000 req/s (~70% of total!) Home & catalog browse 50M DAU x 4 opens x 5 calls -> ~3x evening = ~35,000 req/s Player QoE batches 5M active streams / 300 s batch interval = ~17,000 req/s DRM license calls ~9k/s play starts + ~1.4k/s hourly renewals = ~10,000 req/s Play starts 50M x 3 plays/day = 150M/day (~1.7k/s x 5x) = ~9,000 req/s Search & typeahead 75M calls/day (~900/s avg, ~3x peak) = ~3,000 req/s Total client API QPS 167k + 35k + 17k + 10k + 9k + 3k = ~241,000 req/s Internal DB writes Progress saved every 2nd heartbeat (60 s): 5M streams / 60 s = ~83,000 writes/s 3. STORAGE Studio catalog 20k titles -> ~100k videos (movies + episodes), avg 50 min (0.833 h) Raw studio masters 100,000 x 5 GB avg = 500 TB (moved to cold archive storage after QC) Encoded ABR ladder 6 H.264 rungs (235..5,800 kbps = ~12.4 Mbps) + 4 HEVC/AV1 rungs (1,900..12,000 kbps = ~24.6 Mbps) + multi-language audio & thumbnails (~3.0 Mbps) = ~40 Mbit/s total 40 Mbit/s / 8 = 5 MB/s -> x 3,600 s = 18 GB per hour of video Encoded studio total 100,000 videos x (50/60 h) x 18 GB/h = ~1.5 PB (x3 regions = ~4.5 PB) UGC storage growth 20k uploads/day x 1 GB master = 20 TB/day (~7.3 PB/year if unpruned) Watch progress DB 300M profiles x 300 watched items x 100 B = ~9 TB Live session state 5M concurrent sessions x ~1 KB in Redis = ~5 GB in RAMWhat the numbers tell us:
- Video egress ($180k/day, 20 Tbit/s) dominates cost and architecture: Even a 10% bitrate saving from smarter encoding saves ~$6.5M/year, and cache-key mistakes at the CDN would instantly melt origin storage.
- Heartbeats make up ~70% of all backend API traffic (~167k req/s): Choosing a 30-second heartbeat instead of 5 seconds saves over 800,000 req/s, and isolating heartbeats in their own lightweight Redis-backed service protects catalog browse and play-start latency.
- UGC—not studio films—dominates long-term storage growth: UGC needs a lean default encoding ladder, upgrading to expensive codecs only when a clip actually gains views.
High-level architecture and core request flows
Clients: Web, iOS, Android, Smart TV API calls | | Manifests, 4s segments, artwork v v +-----------------------------+ +------------------------------------------+ | Global Load Balancer + WAF | | Multi-CDN Edges + ISP-Embedded Caches | | (TLS, token-bucket limits) | | (Verify URL token at edge; strip token | +--------------+--------------+ | from cache key -> Regional Shield) | v +--------------------+---------------------+ +-----------------------------+ | Cache misses (< 2%) | API Gateway + Device BFFs | v | (Stateless JWT check) | +-----------------------------+ +--------------+--------------+ | Multi-Region Object Storage | | | (/v/{id}/{ver}/seg_001.m4s) | +---------+----+----+----------+---------+-------------+---------------+ v v v v v v Catalog Search Rails & Auth & Playback & Session Service DRM License Service Service Recs Profiles | | \ Servers | | | | Redis Watch CDN | Postgres OpenSearch KV Sharded (Slots & Progress Steering KMS Key + KV doc Rails Postgres Leases) (NoSQL) Engine Service INGEST PIPELINE: Uploader -> Upload API -> Presigned Multipart S3 PUT -> Workflow Engine -> Probe/QC -> Parallel Chunk Workers -> CMAF + CENC Packager -> READY flip EVENT PIPELINE: Players/APIs -> Kafka -> Stream Jobs (QoE, 2-min Qualified Views) -> Lake -> Daily Batch (Top Ten, Recs) -> Versioned Rails KV & Search IndexerThree end-to-end flows:
- Browse: A smart TV calls
GET /v1/home. A BFF (Backend for Frontend) tailored to TVs fetches precomputed rail IDs for that profile, merges live"Continue Watching"items from the progress store, filters out titles outside the viewer's country license window or profile maturity tier, and returns one compact payload with CDN artwork URLs. - Play (fitting inside the 1.5 s TTFF budget):
POST /v1/playback/startchecks entitlements, atomically reserves a stream slot, selects the best codec/resolution ladder, ranks CDNs, and returns signed manifest URLs plusresume_position_msin ~150 ms. The player fetches the manifest (~50 ms), requests its DRM decryption license in parallel with downloading the first 4-second video segment at a moderate startup rung like 1.75 Mbit/s (875 KB, ~350 ms on a 20 Mbit/s connection), and decodes the first frame (~100 ms) -> ~0.65–0.90 s total TTFF. - Resume: Every 30 seconds the player sends a heartbeat (
seq,position_ms) to extend its 90-second slot lease; every second heartbeat (60 s)—plus immediately on pause, seek, or stop—writes the position to the profile-partitioned progress store so another device sees it right away.
- Browse: A smart TV calls
API contracts: client playback and multipart uploads
Every authenticated request carries a short-lived
Authorization: Bearer <JWT>access token, and every retriable write carries a client-generatedIdempotency-Keyso network retries never duplicate slots or uploads.CLIENT-FACING ENDPOINTS GET /v1/home?locale=en-US&device=tv -> {rails: [{id, kind: "CONTINUE" | "TOP_TEN" | "RECENTLY_ADDED" | "GENRE" | "PERSONAL", title, items: [{title_id, artwork_url, progress_pct?}]}], cache_ttl_s} GET /v1/browse/genres/{genre_id}?cursor=...&limit=40 -> {items[], next_cursor} GET /v1/titles/{title_id} -> {metadata, seasons[], resume} GET /v1/search?q=plnt+earth&genre=&year=&lang=&cursor= -> {hits[], facets: {genre[], year[], lang[]}, next_cursor} GET /v1/search/suggest?q=plan -> {suggestions[]} (<= 8 items) POST /v1/playback/start [Idempotency-Key] Body: {video_id, device_id, capabilities: {codecs[], drm, security_level, max_height, formats[]}} 200: {session_id, heartbeat_interval_s: 30, lease_ttl_s: 90, manifest_urls: [{cdn, signed_url}], drm: {system, license_url, session_token}, resume_position_ms, markers: {intro_ms, credits_start_ms}} 403: {code: "NOT_ENTITLED" | "OUTSIDE_LICENSE_WINDOW" | "MATURITY_LOCKED"} 409: {code: "TOO_MANY_STREAMS", active_sessions: [{session_id, device_name, title}]} POST /v1/playback/{session_id}/heartbeat {seq, position_ms, state} -> 200 | 410 SESSION_ENDED POST /v1/playback/{session_id}/stop {seq, position_ms} -> 200 POST /v1/playback/kick {session_id} -> 200 (frees a slot from 409 UI) POST /v1/license/{widevine|fairplay|playready} (binary DRM challenge + session_token -> license) GET /v1/continue-watching?limit=20 -> [{title_id, video_id, position_ms}] POST /v1/progress:flush {items: [{video_id, session_id, seq, position_ms}]} UPLOADER-FACING ENDPOINTS POST /v1/uploads [Idempotency-Key] Body: {kind: "STUDIO" | "UGC", filename, size_bytes, sha256, metadata} 200: {upload_id, part_size_bytes: 104857600, parts: [{part_num, presigned_put_url}]} PUT <presigned_put_url> (Direct binary upload from client to Object Storage) POST /v1/uploads/{upload_id}/complete {parts: [{part_num, etag}]} -> 202 {video_id, status: "VALIDATING"} GET /v1/uploads/{upload_id} -> {status, progress_pct, errors[]}Notice two UX-critical details:
playback/startfolds entitlement, slot reservation, CDN selection, DRM bootstrap, and resume lookup into one round trip to keep TTFF low, and uploads stream 100 MB chunks directly to object storage via presigned URLs (temporary, cryptographically signed upload links) so API servers never proxy gigabytes of raw video.Data model and polyglot storage choices
Different access patterns call for different storage engines rather than forcing everything into one database:
1. CATALOG & RIGHTS (PostgreSQL for transactional authoring -> denormalized JSON in KV cache) titles(title_id PK, kind: FILM | SERIES, original_name, release_year, genres[], cast_ids[], maturity_by_country JSONB, status) seasons(season_id PK, title_id, season_num) episodes(episode_id PK, season_id, episode_num, video_id) videos(video_id PK, title_id, duration_ms, status, current_asset_version INT, markers JSONB) video_assets(video_id, asset_version, ladder JSONB, audio_tracks JSONB, text_tracks JSONB, drm_key_ids JSONB, manifest_paths JSONB, encryption_scheme, PK (video_id, asset_version)) license_windows(title_id, country_code, start_at TIMESTAMPTZ, end_at TIMESTAMPTZ, max_height, PK (title_id, country_code, start_at)) 2. ACCOUNTS & PROFILES (PostgreSQL sharded by account_id — strong consistency for billing/access) accounts(account_id PK, email, plan_id, home_country, home_region, status) plans(plan_id PK, max_streams INT, max_height INT) profiles(profile_id PK, account_id, display_name, maturity_tier INT, locale, pin_hash, is_kids) devices(device_id PK, account_id, kind, drm_security_level, refresh_token_hash, last_seen_at) 3. LIVE SESSIONS & STREAM SLOTS (Redis in account's home_region — sub-ms atomic Lua scripts) stream_slots:{account_id} -> Hash of session_id -> {device_id, video_id, expires_at_s} session:{session_id} -> {account_id, profile_id, device_id, video_id, started_at_ms, last_seq} 4. WATCH PROGRESS (Wide-column / NoSQL like Cassandra or DynamoDB, partition key = profile_id) watch_progress(profile_id PK, video_id SK, series_id, position_ms, duration_ms, completed BOOL, session_started_at_ms BIGINT, seq INT, updated_at TIMESTAMPTZ) 5. MEDIA & RAILS Object Storage: /v/{video_id}/v{asset_version}/{track}/seg_{00001..N}.m4s (immutable!) Rails KV Store: rail:{kind}:{country}:{maturity_tier}:v{version} -> precomputed item listMaking every encoded segment path include
v{asset_version}means files are strictly immutable: if we re-encode a movie to fix an audio glitch, workers writev2/...and flipvideos.current_asset_versionfrom1to2without ever invalidating or corruptingv1files cached at CDNs for viewers currently mid-movie.Deep dive 1: Video ingestion, chunked transcoding, and CMAF packaging
Turning a 10 GB studio master into streamable ABR renditions reliably and quickly uses a durable workflow state machine (
UPLOADING -> VALIDATING -> ANALYZING -> ENCODING -> PACKAGING -> QC -> READY):[10 GB Master] --> Probe & Checksum --> Split at Keyframes into 120 x 1-min Chunks | +--------------------------------+--------------------------------+ v v v [Chunk 1 x 10 rungs] [Chunk 2 x 10 rungs] ... [Chunk 120 x 10 rungs] (Spot CPU workers) (Spot CPU workers) (Spot CPU workers) \ | / +-------------------------------+-------------------------------+ v 4s CMAF Segments (.m4s) + CENC Encryption + HLS (.m3u8) & DASH (.mpd) v Automated VMAF/Sync QC --> Atomic SQL READY Flip- Validation and early rejection: Once multipart upload completes, workers verify per-part and full-file SHA-256 hashes (deduplicating accidental re-uploads), probe container/frame-rate/audio specs, and run copyright fingerprinting plus policy moderation on UGC before spending CPU on encoding.
- Per-title ABR ladder selection: Cartoons look crisp at 1.5 Mbit/s whereas fast-moving rain or confetti needs 6 Mbit/s. For studio titles, the
ANALYZINGstage encodes short sample scenes across candidate(resolution, bitrate)pairs, scores visual quality with VMAF (an open perceptual video-quality metric from 0 to 100), and picks 5–8 rungs along the convex hull (the best-quality resolution at each bitrate step, spaced ~1.5–2× apart). Studio titles get H.264 (universal compatibility) plus HEVC/AV1 (30–50% lower bandwidth on modern devices); new UGC gets a cheap 3-rung H.264 ladder (360p/720p/1080p) until view counts justify HEVC/AV1. - Chunked parallel encoding with aligned keyframes: Encoding a 2-hour movie sequentially on one machine takes hours. Instead, we slice the master into ~1-minute chunks at scene boundaries and fan out
120 chunks × 10 rungs = 1,200independent tasks across cheap preemptible (spot) VMs. Every task writes to a deterministic object key (/encodes/{video_id}/v{ver}/{rung}/chunk_{i}) so crashed spot tasks retry idempotently, and forces closed GOPs (Groups of Pictures) with an exact keyframe (a self-contained full image frame) every 4.000 seconds across every rung so players can switch bitrates cleanly at any 4-second boundary without visual artifacts. - Single-copy CMAF + multi-DRM packaging: Historically, Apple devices required HLS (
.tssegments) while Android/TVs required DASH (.m4ssegments), doubling storage and halving CDN cache hits. Using CMAF (Common Media Application Format), we store one shared set of 4-second fragmented-MP4 (.m4s) video and demuxed audio segments, plus WebVTT/IMSC subtitles and 10-second trick-play scrub thumbnails, and generate tiny HLS.m3u8and DASH.mpdmanifest text files pointing to those exact same segments. Encrypting once with Common Encryption (CENCcbcsmode) supports Apple FairPlay, Google Widevine, and Microsoft PlayReady across modern devices using separate keys forSD,HD,UHD, andAUDIO(if legacy smart TVs lackingcbcsmust be supported, only popular catalog titles get a secondarycencCTR copy). - QC and atomic publish: Automated checks verify matching track durations (
±0.5 s), audio-video sync, loudness, absence of black frames, and VMAF thresholds. Then a single conditional SQL update flips the asset live without race conditions if an older re-encode finishes late:
UPDATE videos SET status = 'READY', current_asset_version = :new_version WHERE video_id = :video_id AND (current_asset_version IS NULL OR current_asset_version < :new_version);Deep dive 2: Adaptive bitrate streaming, multi-DRM, and CDN caching
1. Client ABR loop and 4-second segment trade-off
The player measures download throughput on every 4-second segment and watches its forward buffer: starting at a medium rung (~1.75 Mbit/s) for fast TTFF, stepping up when the buffer exceeds ~20 seconds, and stepping down immediately if the buffer drops toward ~8 seconds. Why 4-second segments? Shorter 2-second segments adapt slightly faster, but double CDN edge QPS (to 5M req/s) and hurt video compression because keyframes repeat twice as often; longer 8–10 second segments compress well, but slow startup and react too late when Wi-Fi suddenly drops.
2. Device DRM matrix and graceful resolution fallback
PLATFORM MANIFEST DRM SYSTEM HARDWARE SECURITY & RESOLUTION POLICY iOS, tvOS, macOS Safari HLS FairPlay Hardware-backed -> up to 4K UHD (per plan) Android phones & TVs DASH Widevine L1 / L3 L1 (hardware TEE) -> HD/4K; L3 (software) -> SD/720p Desktop Chrome/Firefox DASH Widevine L3 Software DRM -> capped at 720p by studio policy Smart TVs / Edge DASH PlayReady/Widevine Hardware-backed + HDCP 2.2 -> up to 4K UHDRather than rejecting a desktop browser that lacks hardware-backed DRM (
Widevine L3),playback/startintersectsdevice_capabilities ∩ plan.max_height ∩ drm_policy_max_heightand hands the player a pre-built manifest capped at720p(whoseSD/720pkey the license server authorizes), while requiring hardware DRM + HDCP output protection for1080p/4Kkeys. License renewals check Redis to verify the playback session's lease is still active.3. Signed URLs, CDN cache keys, TTL rules, and origin shielding
Every manifest and segment request carries a short-lived cryptographic token (valid for 6 hours, refreshed via heartbeats) in a path prefix or cookie. Critical CDN rule: the CDN edge verifies the HMAC signature and strips the token before computing the cache key—otherwise Maya and Liam would have different cache keys for the exact same segment and cache hit ratio would collapse to 0%!
ASSET / ENDPOINT CDN CACHE TTL WHY THIS EXACT TTL Segments & VOD manifests (/v/{id}/v{ver}/...) 365 days Versioned paths are 100% immutable Title artwork (/img/{sha256}.webp) 365 days Content-addressed; new art = new URL 404 / 5xx negative responses <= 10 seconds Prevents a pre-premiere 404 sticking for hours! Public rails (Top Ten, Recently Added) 1-15 minutes Keyed by (country, maturity_tier), capped at next upcoming license_window start_at Personalized /v1/home & /v1/continue-watching 0 (no-store) Unique per viewer profileAcross multiple commercial CDNs (plus ISP-embedded appliances for top broadband networks), a regional origin shield sits behind hundreds of edge POPs to collapse simultaneous cache misses into a single origin read. For major premieres, we pre-warm the first 5 minutes of every rung onto edge caches overnight during off-peak hours.
Deep dive 3: Playback leases, atomic stream limits, and cross-device resume
1. Lease-based sessions and atomic concurrency limits
Relying on explicit
start(+1) andstop(-1) counters permanently leaks stream slots whenever a browser tab closes, a phone loses signal in a subway, or a TV is unplugged. Instead, every active stream holds a 90-second lease renewed by a 30-second heartbeat (giving 2 retry chances on flaky networks before auto-expiring).To enforce
"at most N concurrent streams"without a check-then-act race condition (where two devices tap Play at the same millisecond, both read1 < 2, and both start a 3rd stream), we execute cleanup + check + insert as one atomic Redis Lua script onstream_slots:{account_id}in the account'shome_region:def acquire_stream_slot(slots, session_id, device_id, video_id, max_streams, now_s, lease_s=90): """Run atomically per account (e.g., inside a single Redis Lua script). slots maps session_id -> {'device_id': str, 'video_id': str, 'expires_at': int}. Returns (granted: bool, updated_or_active_slots: dict). """ # 1. Prune expired leases so crashed devices free their slots automatically active_slots = { sid: info for sid, info in slots.items() if info["expires_at"] > now_s } # 2. Exclude this exact session (idempotent retry) or same device (episode switch) other_device_slots = { sid: info for sid, info in active_slots.items() if sid != session_id and info["device_id"] != device_id } # 3. Reject if other devices already hold max_streams; keep active_slots intact! if len(other_device_slots) >= max_streams: return False, active_slots # 4. Grant/renew lease for this device and replace any prior session on same device updated_slots = dict(other_device_slots) updated_slots[session_id] = { "device_id": device_id, "video_id": video_id, "expires_at": now_s + lease_s, } return True, updated_slotsIf an account's
home_regionRedis is temporarily unreachable,playback/startfails open (allows playback with a short temporary lease rather than blocking paying subscribers, reconciling slots once Redis recovers), whereas rights and DRM checks always fail closed.2. Deterministic cross-device resume (
(session_started_at, seq))Suppose Maya watches Episode 1 to
18:30on her phone, enters an airplane-mode subway tunnel, then comes home and watches to41:00on her TV (or rewinds to27:00to rewatch a scene). An hour later her phone reconnects and flushes its old18:30heartbeat. Why do obvious conflict rules fail? - Client wall-clock timestamp wins: Broken whenever a phone's clock is skewed 5 minutes fast. - Largestposition_mswins: Broken whenever a viewer intentionally rewinds (27:00 < 41:00, snapping them forward!). - Last network arrival wins: The phone's delayed18:30flush overwrites the TV's27:00!Instead, the server stamps each session at creation with
session_started_at_ms(server clock) and the client incrementsseq = 1, 2, 3...on each heartbeat. A conditional write updateswatch_progressonly if(new_session_started_at_ms, new_seq) > (stored_session_started_at_ms, stored_seq):UPDATE watch_progress SET position_ms = :pos_ms, session_started_at_ms = :session_start_ms, seq = :seq, completed = (:pos_ms >= :credits_start_ms), updated_at = now() WHERE profile_id = :profile_id AND video_id = :video_id AND (session_started_at_ms, seq) < (:session_start_ms, :seq);When
position_msreachescredits_start_ms(or 95% of duration),completedflips totrue, and for a series"Continue Watching"automatically advances to Episodek + 1at00:00.Auth, profiles, parental controls, and regional entitlements
- Stateless gateway auth + revocable device tokens: Sign-in issues a device-bound refresh token (stored hashed in PostgreSQL, rotated on use so
"Sign out of all devices"revokes stolen sessions) plus a 15-minute signed JWT access token carrying(account_id, profile_id, plan_id, maturity_tier, home_region). The API gateway verifies JWT signatures in memory with zero database queries across all 241k req/s. - Smart TV QR/code pairing: Typing complex passwords with a directional TV remote causes massive drop-off, so TVs use the standard OAuth 2.0 Device Authorization Grant: the TV displays a 6-character code + QR code and polls a token endpoint while the user approves in two taps on their already-signed-in phone.
- Normalized maturity tiers & profile PINs: Rating boards vary globally (
TV-MAin the US,FSK 16in Germany,15in the UK), so we map country ratings onto 5 internal numeric tiers (0 = All Agesup to4 = Adult). Switching into a higher-tier profile requires the account's parental PIN before issuing that profile's JWT, and every catalog/search query plusplayback/startenforcestitle_tier_in_country <= profile.maturity_tier. - Read-time regional licensing windows: Studio rights are territorial, determined by IP geolocation at request time (not billing address). Rather than running brittle midnight cron jobs to toggle
is_available = true, every read checkslicense_window.start_at <= now() AND now() < license_window.end_atdirectly against current UTC time so premieres go live at the exact second worldwide.
- Stateless gateway auth + revocable device tokens: Sign-in issues a device-bound refresh token (stored hashed in PostgreSQL, rotated on use so
Search, recommendations, and "Recently Added" / "Top Ten" rails
1. Search & recommendations
- Full-text search (OpenSearch): One denormalized document per title stores localized titles, aliases, cast/directors, genres, tags, release year, country windows, maturity tiers, and log-popularity. Queries combine
fuzziness: AUTO(1–2 character edit distance so"plnt earth"matches"Planet Earth"), edge n-gram prefixes for< 50 mstypeahead, query-time window/maturity filters, and facet counts on genre/year/language. Catalog edits stream via CDC (Change Data Capture) through Kafka into OpenSearch in< 60 s. - Two-stage recommendations & cold start: Daily offline + nearline pipelines generate ~500 candidates per profile (co-watched item embeddings, favorite genres, country trends), then a ranking model scores probability of a
>= 2 minplay and expected watch hours, enforcing row diversity. Brand-new profiles avoid an empty screen via a 3-title onboarding picker plus country"Top Ten","Recently Added", and 10% exploration slots.
2.
"Recently Added"and"Top Ten"worked ranking example"Recently Added": Materialized per(country, maturity_tier)(~950 tiny lists in KV) from titles/seasons whose window opened in the last 30 days (plus upcoming 24 h openings filtered at read time againstnow(), with CDNCache-Control: max-agecapped atmin(900s, seconds_until_next_premiere))."Top Ten"metric design: Ranked daily per country over a rolling 7-day window, split into Top 10 Films and Top 10 Series. Look at five titles in one country to see why raw watch hours or runtime division distort rankings:
TITLE TYPE RUNTIME QUALIFIED ACCOUNTS HOURS VIEWED HOURS / RUNTIME A Film 2.0 h 1,200,000 1,900,000 950,000 B Series (8 x 1 h eps) 8.0 h 900,000 3,600,000 450,000 C Film 1.5 h 1,000,000 1,350,000 900,000 D Docuseries (4 x 45 min) 3.0 h 700,000 1,400,000 466,667 E Film 1.75 h 800,000 1,000,000 571,429 1. By raw Hours Viewed: B > A > D > C > E (8-hour series B dominates just by length!) 2. By Hours / Runtime: A > C > E > D > B (unfairly buries Series B in last place because not every viewer finishes all 8 hours in week 1) 3. By Qualified Accounts A > C > B > E > D (fair household reach; splitting by type gives (>= 2 min watched, 1 vote Films: [A, C, E] and Series: [B, D], breaking per account, not profile): ties by Hours Viewed!)A Kafka stream processor emits at most one
"qualified view"per(account_id, title_id, day)once cumulative play passes 2 minutes (ignoring accidental clicks and hover previews). A daily batch job counts exact distinct accounts over 7 days (~700M compact rows), stores the Top 30 per(country, film/series)in KV, and the API filters by the viewer's maturity tier to slice the top 10 (so a Kids profile still gets 10 valid items!).- Full-text search (OpenSearch): One denormalized document per title stores localized titles, aliases, cast/directors, genres, tags, release year, country windows, maturity tiers, and log-popularity. Queries combine
Multi-region scaling, consistency, observability, and experimentation
- Active-active control plane with regional headroom: Deploy stateless services across 3 geographic regions (Americas, Europe, APAC). Each region is sized to run at <= 66% peak utilization so if an entire region goes dark, the remaining two absorb
1.5×traffic without shedding load, while viewers already streaming keep fetching cached segments from CDNs uninterrupted. Separate Kubernetes deployments (bulkheads) isolateheartbeats(167k/s) fromplayback/start(9k/s) andhome(35k/s). - Right-sized consistency per domain:
- Strong / linearizable per account: Billing plan changes and home-region Redis stream slots.
- Read-time exact: Country licensing windows (
start_at <= now < end_at). - Deterministic eventual: Watch progress via
(session_started_at_ms, seq)tuple comparison, catalog metadata (~seconds), and Top Ten rails (daily versioned swap).
- Player-sliced observability & experimentation: Client QoE telemetry (
TTFF, rebuffer %, play-start error codes, average bitrate) is sliced by(CDN, ISP, country, device_model, app_version)with end-to-end trace IDs linkingplayback/start, DRM licensing, and CDN edge logs (excluded from cache keys!). A/B tests hash(account_id, experiment_id)—randomizing at the household account level so family members sharing a TV get consistent UX—and auto-abort if QoE guardrails (TTFF, rebuffer %, start errors) regress.
COMPONENT OUTAGE GRACEFUL DEGRADATION BEHAVIOR Single CDN degrades in an ISP Player auto-switches to fallback CDN #2 on 2 segment errors; Steering Engine demotes that CDN for new starts within 60 s Recommendations / Personal DB Serve CDN-cached static country rails (Top Ten + Genre rows) Home-region Redis slot store Fail open on stream-count limit; never block valid subscribers Watch-progress DB write spike Buffer positions locally on device + in Kafka; replay asynchronously Search cluster unavailable Hide search bar temporarily; rail and genre browsing work normally- Active-active control plane with regional headroom: Deploy stateless services across 3 geographic regions (Americas, Europe, APAC). Each region is sized to run at <= 66% peak utilization so if an entire region goes dark, the remaining two absorb
Security, anti-piracy, cost levers, and trade-off summary
- Abuse & anti-piracy: Token-bucket rate limits at the WAF protect login (credential stuffing),
playback/start, and DRM license endpoints (key-scraping bots). Edge URL signing keys rotate every 30 days using overlappingactive + previouskey IDs for zero-downtime rollover. For high-value premieres, A/B forensic watermarking encodes two visually identical variants (AandB) of each 4-second segment: serving a session-specific sequence likeA-B-B-A-B...embeds a 64-bitsession_id+ error correction in just ~5 minutes of leaked video (75 segments = 75 bits) while multiplying storage by only2×instead of per-viewer encoding! Household credential sharing is nudged softly (device/IP cluster drift triggers a one-time owner verification code or extra-member upsell rather than hard bans). - Ranked cost levers:
- Egress (#1 spend): Per-title VMAF ladders + AV1/HEVC on capable screens + cellular bitrate caps + immutable 1-year CDN caching + ISP-embedded caches (peering instead of paid transit).
- Encoding CPU: Tier ladders by popularity (3 H.264 rungs for long-tail UGC) and run chunk workers on cheap spot instances.
- Storage: Tier raw 5 GB masters to cold archive immediately after QC; prune unwatched high-rung UGC renditions.
- Control plane: Keep heartbeats at 30 s (
167k/s) and debounce durable DB progress writes to 60 s (83k/s).
Summary of key trade-offs
- Single CMAF +
cbcssegment set vs. separate HLS/DASH copies: Halves object storage and doubles CDN cache efficiency, trading off extra fallback handling for very old non-cbcsTVs. - 4-second segments + 30-second lease heartbeats: Balances sub-1.5s TTFF, fast bitrate adaptation, compression efficiency, and automatic slot cleanup against manageable edge and Redis QPS.
- Fail open on concurrency limits, fail closed on content rights: Protects viewer trust during internal Redis blips without ever violating studio licensing contracts.
- Abuse & anti-piracy: Token-bucket rate limits at the WAF protect login (credential stuffing),
Intuition & how it works
Think of a global video-on-demand (SVOD) platform as separating a ticket booth from a worldwide network of neighborhood vending machines. Our backend servers act strictly as the ticket booth (control plane, the lightweight decision-making APIs): they verify your subscription, check that a movie is licensed in your country, enforce your 2-screen limit, remember that you paused at minute 18, and hand your player a short-lived digital pass. The heavy video files never flow through our backend servers—instead, every movie is pre-sliced into 4-second chunks and stocked inside thousands of local CDN (Content Delivery Network) edge servers (data plane, distributed cache servers placed close to viewers and inside internet providers) so millions of TVs fetch video from a few miles away.
If you take the naive approach—storing one giant MP4 per movie on cloud servers, streaming bytes through your backend, checking stream limits with "SELECT count(*) then INSERT", and saving watch progress with "last request received wins"—four things fail immediately. First, 5 million viewers at 4 Mbit/s equals 20 terabits per second (90 petabytes/day), which would overwhelm any origin data center and bankrupt bandwidth budgets. Second, a single fixed video resolution either stalls constantly on shaky cellular networks or looks blurry on a 65-inch 4K TV. Third, two family members tapping Play simultaneously both read "1 of 2 screens active" and slip past plan limits, while an offline phone reconnecting hours later overwrites a newer timestamp watched on a living-room TV.
Walk through four concrete steps as Maya watches Episode 1 on her smart TV and resumes on her phone:
- Ingest & single-copy packaging: A studio uploads a 5 GB master file in parallel 100 MB parts directly to object storage. Spot workers split it at scene boundaries into 1-minute slices, encode 6 ABR (Adaptive Bitrate) quality rungs with aligned 4-second CMAF (Common Media Application Format) segments (a fragmented-MP4 format playable by both Apple HLS and Android/TV DASH players), encrypt them once, and atomically flip version
v1toREADY. - Play start in one round trip: Maya presses Play on her TV.
POST /v1/playback/startverifies her plan and country window, runs an atomic Redis script to claim 1 of her 2 stream slots under a 90-second lease (an auto-expiring reservation), and returns signed CDN manifest URLs plusresume_position_ms = 0. - Fast startup & heartbeats: Her TV downloads the manifest and fetches the first 4-second mid-quality segment from a nearby CDN cache while requesting its DRM (Digital Rights Management) decryption license (hardware-enforced content decryption keys) in parallel, rendering the first frame in ~0.8 seconds before stepping up to 4K. Every 30 seconds the TV sends a heartbeat (
seq = 1, 2, ...) to renew its 90-second lease, writing durable progress every 60 seconds. - Conflict-free cross-device resume: Maya pauses at
18:30(immediately writing(session_start=20:00, seq=38, pos=18:30)) and opens her phone on the train. Her phone reads18:30from her profile's partition, starts a newer session (session_start=20:15), and smoothly drops down to the 560 kbit/s rung when cellular signal weakens—and even if the TV later flushes a delayed packet from20:00, the database ignores it because20:00 < 20:15.
Key trade-offs
- Multi-CDN + origin shield for all video bytes vs. serving from cloud origins. Only distributed CDN edges and ISP-embedded caches can absorb 20 Tbit/s (
~2.5Msegment requests/s) with sub-second startup, while an origin shield (a shared regional middle cache that collapses misses from hundreds of edge servers into a single origin fetch) protects object storage. The trade-off is vendor integration complexity, mitigated by client-side multi-CDN failover. - Shared CMAF segments encrypted with
cbcsvs. separate HLS and DASH packages. Storing one fragmented-MP4 segment set referenced by both.m3u8(HLS) and.mpd(DASH) manifests cuts storage in half and doubles CDN cache hit efficiency across Apple, Android, web, and modern TVs. The trade-off is that older legacy TVs supporting only CENCcenc(AES-CTR counter-mode encryption rather thancbcspattern encryption) either require a second encrypted copy for top titles or explicit deprecation. - Per-title VMAF ladders + AV1/HEVC vs. a fixed H.264 ladder. Measuring scene complexity with VMAF (a perceptual video-quality score from 0 to 100) and encoding modern codecs cuts egress bandwidth—the #1 operating expense—by 30–50%, at the cost of 5–10× more encoding CPU. We spend that CPU on popular studio titles while giving long-tail uploads a cheap 3-rung H.264 ladder.
- 4-second segment duration vs. 2-second or 10-second segments. Four-second segments balance fast startup, responsive quality switching, compression efficiency, and CDN request rate. Two-second segments react faster to sudden Wi-Fi drops, but double edge QPS and require twice as many keyframes (large self-contained frames placed at segment boundaries so bitrates can switch cleanly); 10-second segments compress better, but feel sluggish at startup and stall when bandwidth dips.
- 90-second leases with 30-second heartbeats vs. explicit start/stop counters. Leases automatically free stream slots within 90 seconds when apps crash or TVs lose power, at the cost of
~167kheartbeat requests/s at 5M streams (choosing 30 s over 10 s saves~330k req/s, and writing durable progress every second heartbeat halves database writes to~83k/s). - Exact per-account slots in a home region (fail-open) vs. approximate local counters. Routing slot mutations to the account's
home_regionRedis gives exact atomic enforcement via a single Lua script, adding ~100 ms once at play start only when a subscriber travels abroad—and failing open if Redis goes down ensures paying viewers are never locked out by internal infrastructure hiccups, whereas licensing checks always fail closed. - Server-ordered
(session_started_at_ms, seq)resume vs. timestamp or max-position rules. Ordering writes by server-assigned session start time and monotonic heartbeat sequence number makes conflict resolution immune to skewed phone clocks, late offline flushes, and intentional rewinds, at the small cost of conditional tuple updates in the progress store. - Pragmatic 100k-DAU MVP vs. full day-one distributed platform. Launching with one region, one CDN, fixed H.264 CMAF, and SQL-computed rails ships browse/play/resume in weeks while still building the non-negotiable foundations (immutable versioned paths, server-side DRM/entitlements, atomic leases, and deterministic resume) that would be painful to retrofit later.
Common mistakes
- Leaving the signed auth token inside the CDN cache key. If
?token=abcstays part of the cache key, every viewer gets a unique key, CDN hit ratio drops near zero, and 20 Tbit/s slams directly into origin storage; validate the signature at the edge and strip the token from the cache key. - Backwards cache TTLs (short on immutable segments, long on errors or mutable aliases). Mutable paths like
/latest/master.m3u8leave viewers stuck on broken encodes, while caching404 Not Foundfor an hour keeps a midnight premiere broken long after 00:00; use immutable/v/{id}/v{ver}/...URLs cached for 1 year and cap404/5xxnegative caching at<= 10 seconds. - Enforcing concurrent-stream limits with read-then-write queries. Checking active stream count in one query and inserting a row in a second lets concurrent requests bypass plan caps; bundle expiry cleanup, count check, and lease insertion into one atomic per-account operation.
- Using
"largest position wins"or"client clock wins"for watch progress."Largest position"breaks whenever a viewer rewinds to rewatch a scene, and"client clock"breaks whenever a tablet's clock is off by a few minutes. - Encoding full movies sequentially on one worker or without aligned GOP keyframes. Sequential encoding makes a 2-hour 4K title take many hours to publish, and unaligned keyframes across bitrate rungs cause playback freezes or decoder crashes whenever the player switches quality.
- Toggling title availability with midnight cron jobs instead of read-time window checks. Cron jobs lag, fail partway through, and race with cached responses; store
(start_at, end_at)per country and evaluatestart_at <= now < end_atat read time while capping rail cache TTLs at the next upcoming release boundary. - Ranking
"Top Ten"by total hours viewed. Raw hours systematically favor 10-hour series over 95-minute movies; rank Films and Series separately by distinct qualified accounts (>= 2 minuteswatched over 7 days, one vote per household account).
Follow-up questions
- How would you prepare the CDN and control plane for a scheduled hit release where millions of subscribers press Play at the exact release second? Treat scheduled premieres like planned traffic events: pre-warm the first 5 minutes of every ABR rung onto CDN edges and ISP caches overnight during off-peak hours, and pre-scale stateless
playback/start, session, and DRM license pods an hour ahead. Replicate the premiere's metadata, rail lists, and DRM key descriptors in local in-memory caches across every API node so no single database partition becomes a hot key, and rely on read-time window checks plus<= 10 snegative-cache TTLs so the title unlocks cleanly at 00:00:00 without a batch flip job. If play-start requests still exceed provisioned control-plane capacity, apply brief jittered admission queuing (a 2–5 second"Starting shortly..."countdown) on new starts while viewers already streaming stay completely unaffected on CDN edges. - What changes are needed to let mobile subscribers download encrypted episodes for offline airplane viewing while still enforcing studio expiration rules and syncing watch progress later? Reuse the exact same encrypted CMAF video/audio segments, pairing them with a persistent offline DRM license whose cryptographic policy enforces studio rules directly on the device (for example, expiring 30 days after download or 48 hours after tapping Play, and capping active downloads per account/plan in a Download Entitlement table). Refuse downloads on titles whose regional licensing window closes within a few days or whose studio contract forbids offline storage, and revoke/refresh licenses whenever the app comes back online. For offline watch progress—where the device could not ask the server for
session_started_at_mswhen starting on an airplane—stamp the offline session usinglast_synced_server_time_ms + elapsed_monotonic_clock_ms(never the user-editable wall clock!) and flush buffered positions viaPOST /v1/progress:flushon reconnect using the same(session_started_at_ms, seq)merge rule. - How would the ingestion, packaging, and edge caching architecture change if the service introduced live sports broadcasts alongside its on-demand catalog? In live streaming, segments are created in real time rather than days ahead, so per-title two-pass VMAF analysis and 1-year immutable manifests disappear: live manifests update every segment and require a tiny CDN TTL of roughly half a segment (~1 second), while individual numbered segments remain immutable once written. Drop segment duration to 2 seconds (or use Low-Latency HLS/DASH with 200–500 ms partial CMAF chunks) to keep viewers within a few seconds of real life, and run dual-redundant live encoders feeding independent packagers and origins so an encoder crash fails over seamlessly without interrupting the broadcast. Finally, because millions of viewers request the exact same newest segment at the exact same second (unlike VOD where viewers are spread across timestamps), request coalescing at the CDN edge and origin shield—holding duplicate in-flight requests for
seg_1042.m4sbehind one upstream fetch—becomes mandatory to prevent a thundering herd on the live packager.
Follow-up questions
- How would you prepare the CDN and control plane for a scheduled hit release where millions of subscribers press Play at the exact release second?
- What changes are needed to let mobile subscribers download encrypted episodes for offline airplane viewing while still enforcing studio expiration rules and syncing watch progress later?
- How would the ingestion, packaging, and edge caching architecture change if the service introduced live sports broadcasts alongside its on-demand catalog?
Similar questions
- Weather Ingestion and Sub-10-Minute Temperature API
- Hourly Weather Data Ingestion Service
- Future-Dated Payment Scheduling and Execution
- Account Ledger with Scheduled Transfers and Merges
- In-Memory Banking Ledger and Pending Transfers
- Target Compensation, Package Mix, and Role Leveling
More HubSpot interview questions
- Target Compensation, Package Mix, and Role Leveling Medium
- In-Memory Banking Ledger and Pending Transfers Medium
- JavaScript Prototype Delegation and Call-Site 'this' Binding Medium Pro
- Framing Your Current Engineering Role, Ownership Scope, and Track Alignment Medium Pro
- Account Ledger with Scheduled Transfers and Merges Medium Pro
- Weather Ingestion and Sub-10-Minute Temperature API Hard Pro
- Hourly Weather Data Ingestion Service Easy Pro
- Locate the Special Guest Using knows(a, b) Easy Pro
- Detect a Spammer Account in Linear Oracle Queries Medium Pro
- Thread-Safe Account Ledger and Transfers Medium Pro