System-design interview · Core interviews
Design a video streaming service
Turn an uploaded original into a verified playable video, then separate playback authorization from adaptive segment delivery.
You will learn to
- Trace upload, processing, publication and playback as different completion stages.
- Derive delivery capacity from watch duration and bitrate rather than upload count.
- Explain safe output publication, adaptive playback and bounded private-media grants.
Practice in this chapter
8 interview questions with model answers and follow-ups.
Go to interview practiceUseful foundations: Message queues, event logs, delivery guarantees, and backpressure · Proxies: forward proxy, reverse proxy and API gateway · Replication and durability
Workload and timing examples are interview assumptions.
Dotted concept links open the relevant explanation in a new tab.
01Choose on-demand upload and playback
Design a service for user-uploaded videos that viewers can play, pause, seek and resume on another device. Include titles, thumbnails, basic search, comments and reactions. The running example is a two-minute bicycle-repair video, v42. Its uploader wants reliable progress; its viewer wants playback that continues when Wi-Fi becomes a slower mobile connection.
Uploading the original is not the same as publishing a playable video. The service first accepts durable source bytes, then prepares a compatible output, then marks v42 READY. A failed encode must leave a useful processing or failure status instead of pretending that upload success means playback success.
Choose on-demand video for this interview. Live broadcasting, recommendation ranking and licensed subscription rights are separate extensions. For private videos, new playback sessions check current access. The worked delivery policy uses grants valid for up to five minutes; revocation stops new grants, while an already issued grant can remain usable until expiry. Agree to that limitation before designing a cache-heavy media path.
Clarify on-demand versus live video, the expected upload formats and sizes, acceptable startup delay, and how quickly private playback must stop after access changes. This design selects on-demand playback and an explicit five-minute existing-grant limit.
02Functional requirements
Agree on these supported actions before selecting components.
Upload and publish video. Authenticated creators upload resumable originals, inspect processing status and publish playable video only after its required rendition, thumbnail and manifest exist.
Play across supported devices. Viewers start, pause, seek and resume a video, selecting compatible prepared renditions as network conditions change.
Manage content and interaction. Provide titles, basic search, comments, reactions and owner deletion. These supporting features do not block segment delivery.
Authorize private playback. New private sessions require current access and receive an expiring delivery grant. The media edge validates that grant on manifest and segment requests.
03Non-functional requirements
Use these as illustrative interview assumptions to agree with the interviewer. Numerical targets require measurement; they are not claims about an existing product or a proven implementation. p95 (the 95th percentile) means 95% of measured operations finish within the stated time.
Workload. Use twenty million two-minute uploads/day and four billion playback starts/day. The worked average is approximately 2.78 million concurrent viewers and 13.9 Tb/s of delivered media; provision peak headroom from measured traffic rather than treating these averages as ceilings.
Playback experience. Target p95 time to first frame within two seconds for a ready video on a tested supported device/network profile, and aggregate rebuffered time below 1% of watched time on that profile. Report the profile and failures; neither target promises performance on every connection.
Processing delay. For the example two-minute, 20 MB clip within accepted codec/resolution limits, target p95 upload-complete-to-minimum-READY within 60 seconds at admitted load. Optional higher-quality outputs can follow later.
Durability and completeness. Accepted originals and published metadata must survive a worker restart or one storage-node failure within the region. A selected manifest must name complete immutable required outputs; a cache is not the durable archive.
Private-access lifetime. Stop issuing new grants after access is removed. An existing grant remains usable for at most its five-minute validity for new requests; already downloaded bytes and admitted transfers cannot be recalled.
Resource isolation. Bound upload and encode work independently of playback. Origin misses and retries must remain within storage capacity so a cache failure cannot create an unlimited request backlog.
04Make one uploaded video playable
Start with an application, a SQL metadata database, durable object storage and a background encoder. Object storage holds large files independently of database rows. The uploader creates upload up42, transfers the original and asks the API to complete it. The API verifies the expected length and checksum, then records PROCESSING and a durable encoding job in one database transaction.
The encoder reads that original and creates one broadly compatible rendition: a prepared version of the video at a particular quality and bitrate. It also creates a thumbnail and a manifest describing the playable output. Once required files are verified, the application updates v42 to READY with the selected manifest pointer. The viewer requests v42, receives the manifest and fetches its media from an origin server backed by object storage.
The job can initially be a database row polled by one worker; a separate queue service is unnecessary for a small library. If a worker dies, the source file and job remain available for retry. If the upload-completion response disappears, querying up42 returns its existing status.
This system already works. Its limitations are encoding throughput, one rendition’s suitability for changing networks and the origin’s delivery bandwidth. Those limits motivate more encoder workers, several prepared qualities and delivery caches.
The worker prepares files before selecting the manifest that the playback API returns.
Read each connection in order
- syncUpload and playback controlUploader / viewer → Video API
- syncSave state / read READYVideo API → Metadata and jobs
- syncVerify original / serve originVideo API → Originals and outputs
- asyncPending encode jobMetadata and jobs → Encoder
- syncRead original; write outputsEncoder → Originals and outputs
- syncPublish verified manifestEncoder → Metadata and jobs
05Count watched seconds and transferred bytes
Assume 800 million daily viewers watch five videos each: four billion starts/day, or about 46,296 starts/s. One upload per 200 views gives twenty million uploads/day, approximately 231/s. Each two-minute original averages 20 MB. Use decimal bytes; eight bits make one byte.
| Resource | Calculation | Implication |
|---|---|---|
| Original ingress | 20 million × 20 MB = 400 TB/day | About 4.63 GB/s average upload traffic. |
| Concurrent viewers | 46,296 starts/s × 60 watched seconds | About 2.78 million simultaneous viewers. |
| Delivery throughput | 2.78 million × 5 Mb/s | About 13.9 Tb/s, or 1.74 TB/s. |
| Four-second segment | 5 Mb/s × 4 / 8 | 2.5 MB at that rendition. |
| Segment requests | 2.78 million / 4 | About 694,444 requests/s. |
| Thirty-day originals | 400 TB × 30 | 12 PB, before additional copies. |
Delivery is governed by actual watched duration and selected bitrate, not merely the number of uploads. A 95% CDN byte-hit ratio would still leave approximately 87 GB/s of origin demand at this average. A hit ratio measures reuse at the cache; it does not remove the bytes sent to viewers.
Benchmark encoding on the chosen codec, resolution and hardware. If an illustrative clip requires twelve worker-seconds, 231 clips/s need about 2,772 continuously busy slots before reserve. Do not present that assumed benchmark as a universal encoder performance figure.
06Expose the lifecycle in the API
The client must distinguish incomplete upload from processing and ready-to-play status. A request key identifies one upload intent; changed content needs a new identity.
| API | Contract |
|---|---|
POST /v1/video-uploads |
Allocate video/upload IDs and scoped part-upload targets. |
PUT a permitted upload part |
Retry a missing part with its integrity metadata. |
POST /uploads/up42/complete |
Verify the assembled original; return 202 PROCESSING. |
GET /videos/v42/status |
Return UPLOADING, PROCESSING, READY or a failure reason. |
POST /videos/v42/playback |
Check access and return a compatible manifest plus expiring grant. |
PUT /me/progress/v42 |
Save a session identity, event sequence and media-time offset. |
The upload API derives the owner from authentication and enforces size and duration limits. Direct upload authorization is restricted to the assigned object or part; it must not permit replacing another user’s files. Completion checks the final original, not only the existence of several uploaded parts.
Playback request
POST /videos/v42/playback
| Request information | Purpose |
|---|---|
| Supported codecs | Select an output the device can decode. A codec is the format used to encode and decode audio/video. |
| Desired resume time | Select the saved media timestamp, such as 75 seconds in the example below. |
The phone can resume at the television’s saved media timestamp while selecting a different compatible rendition. It does not need the television’s exact encoded bytes.
07Separate source bytes, attempts and published outputs
The database records which stored files belong to each upload, processing attempt and published video. A file’s presence in storage alone does not make it public.
| Record | Responsibility |
|---|---|
| Video | Owner, title, visibility, lifecycle state, source identity and accepted manifest. |
| Upload | Request key, expected bytes/checksum, verified parts and transfer status. |
| EncodeJob | Video/source identity, current attempt number and processing status. |
| Manifest | Immutable version naming required renditions and segment objects. |
| Outbox or job table | Work saved durably with the metadata change that requires it. |
| Progress and interactions | Per-user resume state, comments and unique user/video reactions. |
Partition metadata by video ID as traffic grows; add owner/time and title-search access paths for the uploader’s library and discovery. Store media bytes in private object storage. A popular v42 remains a hot key even with good partitioning, so repeated byte delivery needs cache copies rather than a different hash function.
Use immutable source and output identities. Enforce create-only writes or pin exact object versions; a filename convention alone does not prevent an accidental overwrite. Search and view counts may lag. Neither decides whether v42 is READY or whether a private playback session is permitted.
08Publish a complete output, not a work directory
An encoder writes its files under an attempt-specific path, such as v42/source1/attempt7. A segment is a short interval of encoded media; the manifest names the available renditions and their segment locations. Publishing a manifest before all required segments exist creates a deceptive failure: playback starts successfully, then encounters a missing file halfway through.
Define a minimum playable set, such as one compatible audio/video rendition and its thumbnail. Validate that set before publication. Optional higher-quality renditions can arrive later through a new immutable manifest version; they need not delay every initial viewer.
A replacement worker receives a new attempt number. The database accepts READY only if the submitted number is still current, the source matches and the video is not deleted. If old worker seven resumes after worker eight wins, its update is rejected. Their separate output paths also prevent seven from overwriting eight’s files. The database check protects the pointer; immutable storage protects the referenced bytes.
Cleanup must first mark an abandoned attempt ineligible to publish, using the same metadata state that publication checks. It can then delete unreferenced output files. Merely observing “old files” and deleting them risks removing an output that a slow worker is about to publish.
Only the current attempt may select immutable outputs for viewers.
Read each connection in order
- syncClaim attempt 7Encoder 7 → Video metadata
- syncReclaim job as attempt 8Encoder 8 → Video metadata
- syncPublish verified attempt 8Encoder 8 → Video metadata
- blockedLate publish of attempt 7 rejectedEncoder 7 → Video metadata
09Adapt future segments to the connection
Prepare several renditions at different bitrates, with segment boundaries at matching media times; this set is the bitrate ladder. Bitrate is encoded data per second of playback. The player downloads ahead into a buffer, which absorbs brief interruptions. If that buffer empties, playback stalls while more data arrives.
Compare two renditions over the same ideal 2 Mb/s connection:
| Rendition | Bytes for four seconds of video | Download time | Buffer consequence |
|---|---|---|---|
| 5 Mb/s | 2.5 MB | Ten seconds | The player consumes four seconds of video while waiting ten seconds for its replacement. |
| 1 Mb/s | 0.5 MB | About two seconds | Four seconds of content arrive in two seconds, allowing the buffer to recover. |
The player measures recent throughput and buffer depth, then chooses a suitable rendition for subsequent segments. It does not ask the metadata API to transcode on every quality change. HTTP Live Streaming, or HLS, is one established manifest-and-segment format for this request pattern. The application still owns readiness and access policy.
Seeking to 75 seconds selects the appropriate segment and decoding boundary near that media time. Saved progress is advisory. Choose a latest-session policy: the server assigns a generation to a new resumable session and accepts increasing event sequences only from that generation. A late event from an older device cannot replace a newer deliberate seek merely because its offset is larger.
10Separate control requests from media delivery
Place a content delivery network, or CDN, between players and private media storage. An authorized edge serves cached immutable segments or fetches them from origin on a miss. The API handles upload management, metadata and playback authorization; it does not relay every media byte. This isolates upload sockets and encoder CPU from existing playback.
Use the selected five-minute grant at the delivery edge for manifest and segment access. A cache hit must still validate the grant. Its expiry is the explicit stale-access bound for new requests using that grant, rather than a claim that deleting a database row immediately removes every cached byte. Private grants should not appear in logs or public shared links.
An origin shield is a shared cache behind several edges. It can fetch a missing segment once for several waiting edges, reducing a viral clip’s load on storage. Add bounded origin retries and reserve playback capacity when uploads or encoding queues surge.
Scale encoder workers from measured queue age and processing cost, with per-account admission and bounded retries. More renditions improve network/device coverage but multiply compute and retained bytes. Cold videos may initially receive only the minimum playable set; optional encodes follow measured demand.
Use durable majority commits across three metadata replicas in independent regional failure domains, and media storage whose acknowledged writes survive one storage-node loss. Satisfy that policy before reporting original acceptance or publishing required outputs. The two-second startup and rebuffering targets still need playback tests, including origin misses; replication does not establish them.
Upload targets send original bytes to private storage; the API verifies completion and records durable encode work. Encoders publish a verified manifest. A player then obtains a five-minute playback grant and requests segments through the edge and origin shield, without sending media bytes through the metadata API.
Read each connection in order
- syncUpload control / playback grantUploader or player → Video control API
- mediaPermitted upload partsUploader or player → Originals + immutable outputs
- syncVerify accepted originalVideo control API → Originals + immutable outputs
- syncSave job / authorize READY videoVideo control API → Video metadata + encode jobs
- asyncClaim durable encode jobVideo metadata + encode jobs → Encoder workers
- mediaRead original; write renditionsEncoder workers → Originals + immutable outputs
- syncPublish verified manifestEncoder workers → Video metadata + encode jobs
- mediaGrant + manifest / segment requestUploader or player → Grant-checking CDN edge
- mediaCache missGrant-checking CDN edge → Origin shield
- mediaCoalesced origin fetchOrigin shield → Originals + immutable outputs
11Explain what survives each failure
| Failure | User-visible result and recovery |
|---|---|
| Upload interruption | Reuse the session and retry unverified parts, not the entire accepted video. |
| Encoder crash | Status remains processing; another attempt reads the durable original. |
| Invalid or hostile media | Bounded retries end in a reasoned failure; sandbox the decoder and limit resources. |
| Metadata unavailable | New private sessions fail; existing valid grants may keep cached playback working. |
| Origin outage | Cache hits continue; misses use bounded retry or fail visibly. A lower bitrate helps only if usable segments exist. |
| Telemetry outage | Playback continues; statistics are delayed or partially lost under the measurement policy. |
Deletion prevents new playback grants and schedules reclamation after the retained-grant/manifest window. It cannot recall already downloaded video. Back up original identities and publication metadata; caches are not the archive. Derivatives can be regenerated, but that takes time and compute, so restoring metadata alone does not instantly restore every rendition.
Comments, title search and approximate view counts have independent pagination and failure behavior. A slow counter must not block a segment. For a view metric, define what counts as a view before discussing deduplication; a request for the first segment is not proof that the person watched the clip.
12Check the design against the requirements
Use the agreed lists to check the finished design. The tests below still need to establish the targets; a proposed mechanism is not a measured result. FR refers to the numbered functional requirements above; NFR refers to the numbered non-functional requirements.
| Requirement | Design mechanism | Validation and remaining limit |
|---|---|---|
| FR1 + NFR3–4: playable publication | Verified original, durable job, immutable attempt outputs and guarded manifest selection. | Crash or resume an old encoder and inspect every required segment. Benchmark 60-second readiness for the declared clip profile. |
| FR2 + NFR1–2: actual playback | Aligned rendition ladder, client buffer control, CDN and origin shield. | Use real/synthetic players to measure first frame and rebuffering on the declared profile; a 200 manifest response proves neither. |
| FR4 + NFR5: private media | Current session authorization and grant checks even on cache hits. | Revoke access and test a new session versus an existing unexpired grant; report the intentional expiry-bound difference. |
| FR3 + NFR6: noncritical work stays separate | Independent comments/search/telemetry and bounded upload/encoder capacity. | Overload encoding or telemetry while playing cached and uncached segments; test origin-miss limits. |
| NFR4: one-node survival | Replicated metadata and durable original/output storage. | Fail a storage node after acceptance and restore metadata with referenced objects; complete region loss is a separate recovery design. |
13Rapid revision
Remember: The player needs the next segment before its buffer empties. Lower bitrate buys playback time with fewer bytes.
Measure time to first frame, rebuffered time as a fraction of watched time, errors by device/codec and upload-to-READY delay. A successful manifest response alone proves none of these outcomes. Use synthetic players plus privacy-conscious playback telemetry to test real segments.
| Decision | Reason | Limit or cost |
|---|---|---|
| Durable original before processing | Workers can recover without another upload. | Originals require retention and replication. |
| Verified manifest publication | Name only complete, verified media files. | Processing delays readiness. |
| Several bitrates with aligned segment boundaries | Adapt to bandwidth and device support. | More encoding and storage. |
| Deliver segments through a CDN | Reuse hot segments near viewers. | Misses load origin; delivered bytes still cost money. |
| Five-minute private playback grant | Avoid a database check for every segment. | Existing grants work until expiry, delaying revocation. |
| Separate telemetry | Statistics cannot stall playback. | Counts may lag or be approximate. |
In the interview, finish by tracing v42 from verified original through accepted manifest to one adaptive playback session. Name the largest cost drivers: retained originals, useful rendition sets and watched bytes. Licensed catalogs would add entitlement and possibly digital rights management; live video would add moving manifests and a different latency budget. Those are deliberate extensions, not capabilities implied by this on-demand design.
Practise the interview questions
Say your answer aloud before opening the model answer. Then answer the follow-up and compare the reasoning.
Why is upload completion different from READY?
Reveal a model answer
The original can be durable while no compatible playback output exists. READY requires a verified selected manifest and required files.
Interviewer follow-up
What should the upload completion API return?
Reveal the follow-up answer
A processing status and stable queryable identity, not a false playback promise.
What the answer must demonstrate: Distinguishes durable bytes from verified playable outputs.
How do you estimate concurrent viewers?
Reveal a model answer
Multiply playback starts per second by average watched seconds, then multiply concurrency by average selected bitrate for delivery throughput.
Interviewer follow-up
Why is segment QPS higher than start QPS?
Reveal the follow-up answer
Each session fetches many segments, so concurrency divided by segment duration estimates ongoing segment requests.
What the answer must demonstrate: Keeps starts, concurrency, bits and bytes in correct units.
Why does a lower rendition help on a slow connection?
Reveal a model answer
It needs fewer bytes for the same media duration, allowing downloads to replenish the buffer faster than playback consumes it.
Interviewer follow-up
Does the service transcode for every switch?
Reveal the follow-up answer
No. The player requests a subsequent aligned segment from an already prepared rendition.
What the answer must demonstrate: Explains buffer supply versus consumption causally.
How can a successfully loaded manifest still produce broken playback?
Reveal a model answer
It may name segments that were never written or were overwritten. Verify all required immutable outputs before selecting the manifest.
Interviewer follow-up
How does a stale worker lose publication rights?
Reveal the follow-up answer
The database checks the current attempt and source identity during the READY transition.
What the answer must demonstrate: Protects both manifest selection and the referenced bytes.
What does a CDN solve and not solve?
Reveal a model answer
It reuses bytes near viewers and reduces origin load. It does not create source durability or authorize private content by itself.
Interviewer follow-up
What does a 95% byte-hit ratio imply?
Reveal the follow-up answer
About 5% of requested media bytes still need origin service under the assumed workload.
What the answer must demonstrate: Separates cache reuse from durability and authorization.
Can a five-minute playback grant support immediate revocation?
Reveal a model answer
No. An already issued grant can remain usable until expiry; current authorization is required for a new one.
Interviewer follow-up
What would a stricter product require?
Reveal the follow-up answer
Current revocation checks at request admission and a precise in-flight transfer policy.
What the answer must demonstrate: States the actual grant-expiry limitation.
Why not save the largest playback offset ever received?
Reveal a model answer
A person may intentionally seek backward, and old devices may send late updates. Larger time is not necessarily newer intent.
Interviewer follow-up
What ordering policy does this design choose?
Reveal the follow-up answer
The latest server-assigned session generation controls shared progress, with increasing event sequences within it.
What the answer must demonstrate: Orders user intent by session/events rather than maximum offset.
Which metrics reveal whether playback works?
Reveal a model answer
First-frame delay, rebuffered fraction, device/codec errors and actual decoded segment checks reveal user experience better than metadata response codes.
Interviewer follow-up
Which cost tradeoff follows?
Reveal the follow-up answer
Additional encoding may reduce watched bytes, but only if quality and device compatibility remain acceptable.
What the answer must demonstrate: Measures decoded user experience and explicit cost tradeoffs.
Blank-page exercise · 45 minutes
Build the answer yourself
Design user-uploaded on-demand video. Explain one interrupted upload, a stale encoder and a player switching from Wi-Fi to a slower connection.
- 0–5 min: agree numbered functional and non-functional requirements for on-demand playback, upload/READY, device-network performance, durability and private-grant lifetime.
- 5–12 min: trace the smallest playable pipeline and delivery estimates.
- 12–20 min: define upload, metadata, jobs and manifest records.
- 20–30 min: explain adaptive segments, CDN and control/media separation.
- 30–38 min: handle stale encoders, origin failure and private grant expiry.
- 38–45 min: check the final architecture against the numbered FR/NFR lists, identify the playback/readiness tests still needed, and state retention, cost and live-video exclusions.
Check that each component and design decision follows from your requirements and workload.
Recall the key ideas
Answer from memory before opening each card. Explain why the choice works and what it costs. Revisit missed cards tomorrow.
Design a video streaming serviceWhat must happen between an upload and a playable video?Recall first, then reveal
Verify and save the original, save processing work that survives crashes, then publish a complete verified manifest.
Source, job, playable output.
Return to lessonDesign a video streaming serviceOn the example 2 Mb/s link, a four-second 5 Mb/s segment takes ten seconds to download. What changes at 1 Mb/s?Recall first, then reveal
The four-second segment needs 0.5 MB and downloads in about two seconds, so the buffer can recover. The player selects a prepared lower-bitrate segment at the next aligned boundary.
Download faster than playback consumes.
Return to lessonDesign a video streaming serviceHow do we stop an obsolete processing worker from publishing broken playback?Recall first, then reveal
Check that its attempt is still current before accepting its manifest, and keep the immutable files it references protected from deletion.
Guard the pointer and its files.
Return to lessonFinal revision
Summary and interview notes
Save the original and publish complete prepared renditions. During playback, authorize access and deliver cached segments; the player chooses a bitrate that its connection can download in time.
Remember these points
- Keep original durability separate from playable readiness.
- Select verified outputs with a current-attempt database check.
- Use aligned renditions to adapt future segment requests.
- Make private grant lifetime an explicit revocation tradeoff.
Interview tips
- Calculate delivery from watched seconds and bitrate.
- Use the slow-link segment example to explain buffering.
Important qualifications
- Live streaming and licensed entitlement require additional mechanisms.
- Downloaded bytes cannot be recalled.
Continue after the core interview
Explore the advanced version
The advanced lesson keeps the full detailed design. Use these sections when you want to examine the stronger requirements and failure cases.
- Publication and garbage-collection races
Prove stale-worker rejection and cleanup safety through detailed interleavings.
- Regional recovery and storage ownership
Specify stronger recovery promises and partition transfer behavior.
- Deduplication and visual similarity
Separate byte equality, perceptual similarity and rights to reuse media.
- Licensed catalog and DRM extension
Add entitlement, regional windows and key-service requirements when the product changes.
Technical references
- RFC 8216: HTTP Live StreamingDefines manifests, media segments, variant streams, and playback behavior.
- AWS Elemental MediaConvert overviewOfficial description of file-based video conversion and output preparation.
- Amazon S3 multipart upload overviewDocuments resumable multipart completion and cleanup considerations.
- Amazon S3 conditional writesDocuments create-if-absent output writes; immutable media publication remains an application protocol.
Practice marks stay in this browser.