Video Streaming (Netflix)
A codec rollout publishes a manifest that points to incomplete renditions.
Topic tools
Layout updated
Problem statement
Design an on-demand video service like Netflix. Viewers can browse, play, seek, and resume videos across devices, with video quality adapting to their connection.
Functional requirements
- Upload videos and prepare playback versions.
- Browse titles and stream authorized videos.
- Save and resume playback progress.
Non-functional requirements
- Aim for startup under 2 s on supported broadband.
- Never publish incomplete media or bypass playback rights.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 10M concurrent viewers × 5 Mb/s mean bitrate = 50 Tb/s |
| 4-second segments × 10M viewers = 2.5M video segment requests/s |
| 5 Mb/s × 4 s / 8 = 2.5 MB per video segment |
| 100k titles × 2 hours × 15 Mb/s aggregate bitrate ladder / 8 ≈ 1.35 PB |
| 100M playback starts/day ≈ 1,157/s average; 10× peak ≈ 11.6k/s |
Entities
| Entity / logical owner |
|---|
| Playback telemetry {sessionId, eventId, startupMs, stalls, bitrate} |
API design
| Operation / input | Response and retry contract |
|---|---|
POST/uploads → signed multipart upload; POST /uploads/{id}/complete | Object storage holds masters. PostgreSQL owns Asset(assetId, sourceVersion, state, checksum), rendition jobs, publication version and transactional . Completion verifies checksums and size. |
GET/catalog?cursor=...; Title(titleId, assetVersion, territories, rightsWindow) | PostgreSQL is catalog/rights authority; search and Redis catalog caches are derived. Catalog pagination is bounded. Entitlement checks use current policy or a deliberately bounded signed policy . |
POST/playback-sessions {titleId, deviceCapabilities, requestId} | Playback service checks rights and returns sessionId, URL, expiry, candidates and license endpoint. key prevents duplicate session allocation on retry. |
GET/media/{assetVersion}/{rendition}/{segment} | cache key includes immutable asset/rendition/segment identity. Origin object storage is private; edge validates scoped tokens without including each user's signature in the shared byte-cache key. |
POST/licenses {sessionId, deviceProof, challenge} | /license service uses managed keys/HSM and authenticated rights checks. Content keys never appear in URLs, logs or the public metadata DB. |
PUT/progress/{profile}/{title} {sessionId, sequence, positionMs} | Distributed stores resume state; accept increasing sequence within a session and arbitrate concurrent sessions using server-issued session . A seek backwards is valid: do not use maximum playback position as the update rule. |
High-level design
How to draw this design
- Ingest source videoPublisher, Upload Service, and object storage
- Prepare playable renditionsProcessing queue and transcoding workers
- Publish and servePostgreSQL video metadata, Playback , , and player
- Resume playbackDynamoDB watch progress and viewer devices
Upload the source, produce renditions, publish a playable version, then stream segments through the .
- State ownership
- PostgreSQL owns catalog and publication metadata. Object storage holds video bytes. DynamoDB owns progress.
- Scale
- Scale transcoding and bandwidth independently.
- Correctness
- Validate required renditions before publishing the and check playback access.
- Failure and recovery
- Keep a verified version published during transcode failure and limit origin load during failover.
Netflix / Video Streaming
Follow the A steps across the top to publish a title, then the B steps to start playback and stream it. The Playback authorizes the session. The player fetches the video bytes from the , which reads object storage on a cache miss. licensing and playback telemetry are follow-ups.
- Edge
- Compute
- Messaging
- State
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 13 flow steps
High-level design component walkthrough
Content Publisher
Submit a source video and its title metadata.
Why, tradeoff and connected operations
The publishing flow prepares titles before viewers can play them.
Tradeoff: Large uploads may need to resume after interruption.
Connected operations: A1. Start upload
Upload Service
Issue upload credentials and enqueue processing after verifying the source.
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Large files; orphaned uploads
Connected operations: A1. Start upload; A2. Store original; A3. Queue processing
Processing Queue
Replay committed processing jobs
Why, tradeoff and connected operations
Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.
Tradeoff: At-least-once job delivery
Connected operations: A3. Queue processing; A4. Consume job
Transcoding Workers
Validate all outputs before READY
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Encoding CPU and retry control
Connected operations: A4. Consume job; A5. Write renditions; A6. Mark title ready
Object Storage · Originals + Outputs
Masters and packaged renditions
Why, tradeoff and connected operations
Object storage retains video masters and packaged renditions. It handles large immutable files and separates storage bandwidth from catalog transactions. holds metadata and publication state, while object storage holds the actual video bytes.
Tradeoff: Replication and storage cost
Connected operations: A2. Store original; A5. Write renditions; B5. Read on cache miss
CDN
Cache immutable video segments
Why, tradeoff and connected operations
and regional shield caches serve immutable video segments close to viewers. They reduce origin load and repeated long-distance transfers. These are byte-delivery caches, not another authoritative database.
Tradeoff: Miss storms and egress cost
Connected operations: B4. Fetch segments; B5. Read on cache miss
Viewer / Player
Adaptive segment requests
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Bandwidth and device variability
Connected operations: B1. Start playback; B3. Signed URL; B4. Fetch segments; B6. Save watch position
Playback API · Access Checks
Check identity and viewing rights, then return a signed playback URL and read or save watch progress.
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Rights dependency on startup
Connected operations: B1. Start playback; B2. Check title + rights; B3. Signed URL; B6. Save watch position; B7. Read or save progress
Watch Progress · DynamoDB
Resume using session sequence
Why, tradeoff and connected operations
DynamoDB stores playback progress by viewer and title with direct key lookups. Conditional version updates reject an older device update. A key-value model fits independent progress items; remains useful for the related catalog and rights records.
Tradeoff: Concurrent device conflicts
Connected operations: B7. Read or save progress
Video Metadata · PostgreSQL
Catalog, rights and job authority
Why, tradeoff and connected operations
PostgreSQL stores catalog rights, readiness and processing intent together. Transactions ensure only a fully prepared video version becomes publishable. fits related control records; video bytes and per-viewer playback progress use different stores.
Tradeoff: Primary contention; replica lag
Connected operations: A6. Mark title ready; B2. Check title + rights
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Additional technical detail
1 · Requirements and interview contract
Design on-demand video streaming: browse a catalog, start an authorized playback session, seek, adapt quality to bandwidth, and resume playback across devices. Publishers upload titles that become playable only after processing succeeds. Exclude live broadcasts, recommendations training, ad insertion and offline downloads from the baseline.
All numbers here are interview assumptions, not Netflix production measurements. This is a proposed architecture; the accessible prep-chat excerpt did not include the earlier Netflix walkthrough. Drive 5 minutes of scope, 5 of scale/APIs, 10 of architecture, 15 of deep dives, then failures and a final synthesis.
- Targets: playback startup below 2 seconds on supported broadband, playback-session below 200 ms regionally, and rebuffering below 1% of viewing time. Measure by device, ISP and region; averages conceal bad cohorts. Aim for 99.99% segment delivery availability and 99.95% session creation.
- Correctness: never expose a partially packaged title; authorize playback by account, territory, rights window and device. Bytes are immutable after publication. Catalog visibility and resume position can converge eventually; entitlement changes have an explicit bounded revocation interval.
- Availability: existing sessions can continue fetching cached authorized segments during a control-plane incident. New sessions may fail when rights or authority is unavailable. Cached bytes alone do not confer permission to decrypt.
2 · Scale and capacity
| Assumption / calculation | Consequence |
|---|---|
| 10M concurrent viewers × 5 Mb/s mean bitrate = 50 Tb/s | bandwidth dominates; application servers must never proxy all video bytes. Capacity needs ISP/region distribution and failover headroom. |
| 4-second segments × 10M viewers = 2.5M video segment requests/s | Audio and requests add overhead. Smaller segments improve adaptation but increase request overhead. |
| 5 Mb/s × 4 s / 8 = 2.5 MB per video segment | At 98% byte cache hit, origin traffic is still about 1 Tb/s. A small hit-rate regression can overload origin. |
| 100k titles × 2 hours × 15 Mb/s aggregate bitrate ladder / 8 ≈ 1.35 PB | Packaged renditions only; add source masters, audio, subtitles, replication and alternate codecs. Do not multiply one rendition's bitrate by number of viewers when estimating stored catalog size. |
| 100M playback starts/day ≈ 1,157/s average; 10× peak ≈ 11.6k/s | Session metadata is much smaller than segment delivery. Progress every 30 s for 10M viewers ≈ 333k updates/s; separately. |
3 · APIs, entities and state ownership
| / entity | Storage and semantics |
|---|---|
| POST /uploads → signed multipart upload; POST /uploads/{id}/complete | Object storage holds masters. PostgreSQL owns Asset(assetId, sourceVersion, state, checksum), rendition jobs, publication version and transactional . Completion verifies checksums and size. |
| GET /catalog?cursor=...; Title(titleId, assetVersion, territories, rightsWindow) | PostgreSQL is catalog/rights authority; search and Redis catalog caches are derived. Catalog pagination is bounded. Entitlement checks use current policy or a deliberately bounded signed policy . |
| POST /playback-sessions {titleId, deviceCapabilities, requestId} | Playback service checks rights and returns sessionId, URL, expiry, candidates and license endpoint. key prevents duplicate session allocation on retry. |
| GET /media/{assetVersion}/{rendition}/{segment} | cache key includes immutable asset/rendition/segment identity. Origin object storage is private; edge validates scoped tokens without including each user's signature in the shared byte-cache key. |
| POST /licenses {sessionId, deviceProof, challenge} | /license service uses managed keys/HSM and authenticated rights checks. Content keys never appear in URLs, logs or the public metadata DB. |
| PUT /progress/{profile}/{title} {sessionId, sequence, positionMs} | Distributed stores resume state; accept increasing sequence within a session and arbitrate concurrent sessions using server-issued session . A seek backwards is valid: do not use maximum playback position as the update rule. |
| Playback telemetry {sessionId, eventId, startupMs, stalls, bitrate} | Kafka → streaming analytics → quality metrics. Loss of some telemetry is tolerable; player delivery does not depend on the analytics sink. Bound and remove unnecessary personal data. |
4 · Deep dive 1 — Ingestion, transcoding and atomic publication
The ingest service finalizes a verified master, then commits asset state and an job in one PostgreSQL transaction. A relay publishes to Kafka; workers claim idempotent (assetVersion, codec, rendition, segmentRange) jobs. Duplicate delivery is expected. Outputs use deterministic immutable names or attempt namespaces followed by a winning .
Workers produce aligned video/audio segments, captions and manifests for HLS/DASH. Validate decodeability, duration, checksums, timestamp alignment and required device profiles. A coordinator checks that every required object exists, writes an immutable , then atomically changes the catalog pointer to READY/version N. Optional renditions can be published in a later complete version. Readers pin a version; no in-place replacement of an object already cached worldwide.
Tradeoff: pre-encoding a bitrate ladder costs storage and CPU but removes transcoding from the interactive path. Per-title encoding can save bandwidth at extra analysis cost. Recovery: jobs have leases and attempt IDs; retries cannot publish conflicting partial results. Garbage-collect abandoned output only after the maximum session/reference grace period. A failed publish leaves the previous version active.
5 · Deep dive 2 — Adaptive bitrate and CDN behavior
The player obtains a and license, starts with a conservative rendition, and requests segments directly from an edge. Its adaptation loop uses measured throughput and buffer occupancy, with hysteresis to avoid oscillating between qualities. Renditions align at segment/keyframe boundaries so a switch does not introduce a discontinuity. Seeking requests the appropriate segment and decoder entry point.
- Hot release: prewarm predicted popular titles at regional shields/edges, origin misses, and isolate origin fetch concurrency. One unavailable edge must not trigger millions of simultaneous origin reads. Spread initial refresh and retry timing.
- selection: use health, latency, capacity and ISP measurements. On repeated timeouts, retry a compatible alternate with the same asset version and authorization. Bound attempts and retain enough player buffer to cover the switch.
- Tradeoff: short segments improve startup and adaptation; longer segments reduce requests and encoding overhead. Multiple codecs improve efficiency but multiply encoding/storage and device compatibility testing.
- Recovery: immutable objects let caches survive app-server failures. Shields fetch missing segments from a replicated origin. Return an explicit failure if the references a missing object; fix publication and roll back the version instead of retrying forever.
6 · Deep dive 3 — Authorization, keys and progress consistency
Use a short-lived token scoped to title/version, session, territory policy and expiry. Edge authorization precedes serving bytes, even on a cache hit. license validation gates decryption and can enforce device/account concurrency. Concurrent session limits require an authoritative /transaction, not a stale Redis counter alone. Keep license validation regional where possible and prevent thundering-herd renewals.
Revocation is bounded by token/license lifetime; instant global revocation would require online checks or revocation distribution on every request and reduces availability. State that guarantee explicitly. Already decrypted content cannot be recalled. Rate-limit license attempts, protect signing keys, rotate versions and reject malformed manifests.
Progress is softer state: an offline device may reconnect with old positions. Within a session, sequence rejects late packets while allowing backwards seeks. Across sessions, choose a product rule such as latest server-issued active-session ; expose conflict recovery rather than asserting a globally perfect last-writer clock. Recovery: reconnect sends recent progress and session sequence; batching limits write cost. Tradeoff: occasional stale resume is preferable to coupling segment delivery to synchronous progress writes.
7 · Deep dive 4 — Multi-region and degraded operation
Replicate immutable masters, packaged segments and manifests into a second region before declaring a title eligible for regional failover. Track replication completeness per asset version. Catalog/rights has one fenced writer with synchronous protection and asynchronous remote replication in the baseline; remote replication has nonzero . Local catalog caches and read replicas support browsing but cannot invent new rights.
Failover: route segment requests to healthy edges/origins with the same version; shift session traffic only to a region with usable rights, key and asset state. Fence the old metadata writer before promoting a replacement and reconcile lagged updates. If zero loss of rights/publication writes across permanent region loss is required, use a synchronous cross-region commit design and accept added write latency. Multi- does not eliminate a shared or DNS dependency.
Guarantee relaxed: trend recommendations, telemetry and resume freshness can degrade; entitlement correctness does not silently relax. Existing licenses may remain usable until expiry. Cost: cross-region video egress, replicated catalog size and idle failover capacity are deliberate availability costs.
8 · Failures, operations and pressure tests
| Scenario | Response and observability |
|---|---|
| Transcoder dies after writing half a rendition | expires; idempotent retry validates existing chunks. No READY pointer until the completeness gate succeeds. Alert on oldest job and retry loops. |
| Kafka / analytics outage | Retain ingest jobs; bound local telemetry buffers and sample/drop telemetry by policy. Segment serving continues. Monitor age and pipeline lag. |
| Origin or miss storm | Request coalescing, shield cache, per-origin concurrency caps and admission control. Track byte hit rate, origin egress and miss latency by title/ISP. |
| service unavailable | Existing valid licenses continue subject to policy; new/expired licenses fail explicitly. Do not send plaintext keys as a fallback. |
| Bad codec/ rollout | Canary by device cohort and title; rollback immutable publication pointer. Track startup errors, decode failures, rebuffer ratio and abandonment. |
| Regional isolation | Continue cached authorized delivery, route eligible starts elsewhere, refuse conflicting metadata writes. Measure failover time and replicated asset/metadata watermarks. |
Use synthetic start/seek/quality-switch probes and real-player QoE, not only server HTTP success. Compare / startup, stall seconds per viewing hour, rendition changes, license latency, transcode cost per title and egress per viewing hour. Trace session IDs with short ; protect viewing history and publisher credentials. Pressure test a blockbuster release, an ISP outage, a corrupt and a rights revocation during a regional partition.
9 · Final architecture and repeat queue
I separate the playback from the video data path. A verified upload triggers idempotent transcoding jobs; a completeness check publishes an immutable and catalog version. Playback APIs authorize a session and issue scoped references plus a license flow. The player fetches aligned segments from CDNs and adapts bitrate using throughput and buffer state. Regional shields protect replicated object origins. Progress and telemetry are asynchronous. I keep rights and publication authoritative, use explicit bounded revocation, and fence metadata failover. Existing playback can survive control-plane disruption, while missing authorization blocks new sessions. I monitor player experience, origin load and recovery headroom.
Background reading
The proposed interview design above is not a description of Netflix's private implementation. Netflix Open Connect provides primary background on distributing streaming content near viewers.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Publish only a playable video version | Keep previous immutable versions and make transcode jobs safe to repeat. This costs storage but makes partial failures and rollback manageable. |
| Keep video bytes off the application servers | Share upstream fetches on cache misses and use an authorized alternative delivery path when available. More cache layers require capacity and freshness monitoring. |
| Authorize playback even when the bytes are cached | Short-lived access limits revocation delay. Existing licenses may continue during an outage only under the rights policy; fresh sessions may need to fail. |
| What happens if a region fails? | Remote synchronous metadata durability reduces lost publication/rights updates but adds write latency; regional caching improves playback resilience within authorization limits. |
| miss storms and rollout isolation | Prewarming and retained generations cost storage/egress; too-aggressive purges can erase the protection caches provide. |
Production scars & failure modes
A codec rollout publishes a manifest that points to incomplete renditions.
Look for: Watch generation, segment readiness and startup errors by codec/device.
Recovery and invariant: Publish only complete validated generations, retain a known-good and roll back the pointer. Origin shielding cannot repair missing media.
| Component / failure | Required behavior / recovery | Operational implication |
|---|---|---|
| Transcoder dies after writing half a rendition | expires; idempotent retry validates existing chunks. | No READY pointer until the completeness gate succeeds Alert on oldest job and retry loops. |
| Kafka / analytics outage | Retain ingest jobs; bound local telemetry buffers and sample/drop telemetry by policy. | Segment serving continues Monitor age and pipeline lag. |
| Origin or miss storm | Request coalescing, shield cache, per-origin concurrency caps and admission control. | Track byte hit rate, origin egress and miss latency by title/ISP. |
| service unavailable | Existing valid licenses continue subject to policy; new/expired licenses fail explicitly. | Do not send plaintext keys as a fallback. |
| Bad codec/ rollout | Canary by device cohort and title; rollback immutable publication pointer. | Track startup errors, decode failures, rebuffer ratio and abandonment. |
| Regional isolation | Continue cached authorized delivery, route eligible starts elsewhere, refuse conflicting metadata writes. | Measure failover time and replicated asset/metadata watermarks. |
90-second interview summary
I would separate video publication, byte delivery and authorization. Publishers upload immutable masters, and transcode workers produce complete segment/ generations. PostgreSQL records catalog readiness and dispatch intent; a title becomes ready only after required artifacts are verified, not merely because one worker finished.
Players fetch aligned segments through CDNs and regional shields, selecting bitrate from measured throughput and buffer health. The application handles catalog/session decisions rather than proxying every video byte. Shields, prewarming and bounded origin concurrency protect against simultaneous misses.
Playback rights and licenses remain a separate boundary. A cached segment does not itself authorize playback, and analytics failure should not stop delivery. Bad codec or releases roll back by changing a verified generation pointer while active cached artifacts remain immutable.
Regional failover requires complete media assets plus usable catalog, rights and key-service state. I would fence metadata promotion, state the asynchronous replication loss window and avoid claiming that multi- fixes a shared dependency. Metrics include startup delay, rebuffering, origin misses and generation-specific failures. The tradeoff is storage/egress amplification and more publication controls in exchange for predictable playback and recoverable releases.
Explain it without looking
Explain publish only a playable video version
Reveal answer
Verify the required segments and before marking a title ready.
Retries cannot repair a that points to files which were never successfully published.
Keep previous immutable versions and make transcode jobs safe to repeat. This costs storage but makes partial failures and rollback manageable.
Explain keep video bytes off the application servers
Reveal answer
Let players fetch segments through CDNs and regional shields.
Proxying every segment through catalog servers adds enormous bandwidth to a service that should handle metadata.
Share upstream fetches on cache misses and use an authorized alternative delivery path when available. More cache layers require capacity and freshness monitoring.
Explain authorize playback even when the bytes are cached
Reveal answer
Check the session's rights and license before granting protected playback.
Possessing a cached segment does not give a viewer permission or the key needed to decrypt it.
Short-lived access limits revocation delay. Existing licenses may continue during an outage only under the rights policy; fresh sessions may need to fail.
Explain what happens if a region fails?
Reveal answer
Check media files, playback rights and licenses before moving sessions.
Playback recovery spans byte delivery and access rights, which have different owners.
Remote synchronous metadata durability reduces lost publication/rights updates but adds write latency; regional caching improves playback resilience within authorization limits.
Explain miss storms and rollout isolation
Reveal answer
Protect the origin against simultaneous cache misses and bad client-specific releases.
Steady-state cache hit ratio hides cold-start and rollout behavior, which often defines the actual origin budget.
Prewarming and retained generations cost storage/egress; too-aggressive purges can erase the protection caches provide.
Revision checklist
Revision checklist
- Reconstruct publish only a playable video version: Verify the required segments and before marking a title ready.
- Reconstruct keep video bytes off the application servers: Let players fetch segments through CDNs and regional shields.
- Reconstruct authorize playback even when the bytes are cached: Check the session's rights and license before granting protected playback.
- Reconstruct what happens if a region fails?: Check media files, playback rights and licenses before moving sessions.
- Reconstruct miss storms and rollout isolation: Protect the origin against simultaneous cache misses and bad client-specific releases.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope ingest and video playback. Estimate peak bandwidth and set a playback-start or buffering target. |
| 15–30 min | High-level design | Draw upload, transcoding, publication, and the playback path. Show catalog and license checks separately from segment delivery. |
| 30–45 min | Deep dives | Explain publication and adaptive bitrate. Discuss what the client does when a rendition is slow. |
| 45–55 min | Failure and recovery | Walk through a outage or incomplete transcode. Keep serving a verified version and explain origin protection. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 90-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough