System design interview: design YouTube
Designing YouTube means building two systems that meet at object storage: an upload and transcoding pipeline that turns one raw file into many streamable renditions, and a playback path that serves those segments from a CDN to a huge audience. Interviewers usually probe the pipeline (chunked uploads, parallel encoding, when a video counts as published) and the view counter, because the playback half looks a lot like any streaming design.
By Evin JohnPublished 10 min read
1. Clarify the requirements
"Design YouTube" is too big for 45 minutes, so the first job is to cut it down out loud. Most interviewers are happy with upload, processing, playback and view counts, and will push you toward one of them once the outline exists.
- Functional: a signed-in creator uploads a video with a title and description; the service processes it into formats that play on phones, laptops and TVs; anyone can watch it; the page shows a view count and the creator sees it grow.
- Non-functional: playback starts within a couple of seconds and rarely stalls; an upload survives a dropped connection; a finished video is never lost; view counts may lag by seconds or minutes but must not be wildly wrong.
- Out of scope unless asked: recommendations and the home page, comments, live streaming, monetization and ads, content moderation beyond a hook in the pipeline, search.
2. Estimate the scale
These figures are invented round numbers for the exercise. State them as assumptions and use them to choose components.
| Quantity | Assumption | Result |
|---|---|---|
| Uploads | 500,000 videos a day | about 6 uploads a second on average |
| Raw upload size | about 400 MB per video | about 200 TB of new raw video a day |
| Processed renditions | all renditions together about 1.5x the upload | about 300 TB a day; raw plus renditions about 180 PB a year if originals are kept |
| Views | 2 billion a day | about 23,000 view starts a second; plan for 3x at peak, about 70,000 |
| Bytes per view | 4 minutes watched at an average 2 Mbps | about 60 MB a view, about 120 PB a day |
| Egress bandwidth | 120 PB spread over a day | about 11 Tbps on average, far more at peak |
Three conclusions come straight from the table. Egress at that size can only come from a CDN with servers close to viewers, so the origin's job is to fill caches, not to serve users. Transcoding 200 TB a day is a large batch compute problem that needs a queue and many workers. And storage grows by petabytes a year, so cold videos must move to cheaper tiers.
3. Define the API
POST /v1/uploads
body: { "title": "Fixing a bike chain", "sizeBytes": 412000000, "contentType": "video/mp4" }
returns: 201 { "uploadId": "up_7Qk", "videoId": "v_93a", "chunkSize": 8388608 }
PUT /v1/uploads/{uploadId}/chunks/{index} (raw bytes, with a checksum header)
GET /v1/uploads/{uploadId} returns which chunks have arrived, for resuming
POST /v1/uploads/{uploadId}/complete returns 202 { "status": "processing" }
GET /v1/videos/{videoId}
returns: { "title": ..., "status": "ready", "manifestUrl": "https://cdn.example/v_93a/master.m3u8", "views": 18342 }
POST /v1/videos/{videoId}/view-events batched heartbeats from the player4. Sketch the data model
| Entity | Key fields | Where it lives |
|---|---|---|
video | video_id, owner_id, title, description, status (uploading, processing, ready, failed, removed), duration, created_at | Sharded relational database or a wide-column store, keyed by video_id |
upload_session | upload_id, video_id, chunk size, received chunk bitmap, expiry | Key-value store with a TTL; deleted when the upload completes or expires |
rendition | video_id, resolution, bitrate, codec, segment count, storage prefix, ready_at | Same database as video, one row per output |
| Raw and processed files | raw/{video_id}, out/{video_id}/{rendition}/seg_00042.m4s | Object storage, replicated across zones |
| View counts | video_id, total, per-hour buckets | A counter store fed by the event stream, separate from video |
Keeping view counts out of the video row is deliberate. A popular video gets thousands of views a second, and a single row taking that many updates becomes a hot spot that slows every read of the video page.
5. The core decision: the processing pipeline
Transcoding a long video on one machine can take longer than the video itself. The design that interviewers look for treats processing as a graph of small jobs that run in parallel and can be retried one at a time.
- ValidateCheck the container and codecs, read the duration and resolution, compute a checksum and reject corrupt or unsupported files before spending compute on them.
- SplitCut the source at keyframes into segments of a few seconds. Each segment can now be encoded independently, which is what makes the pipeline fast.
- Encode in parallelFor every segment and every rendition on the ladder (say 240p to 1080p, plus 4K for sources that have it), a worker encodes that piece. One video becomes hundreds of independent tasks on a queue.
- PackageWrite the encoded segments in a streaming format (HLS or DASH) and generate manifests that list the renditions and their segment URLs.
- Side jobsThumbnails, audio normalization, captions from speech recognition and a moderation check run as further nodes of the same graph.
- PublishWhen the lower renditions and the manifest exist, flip
statusto ready. Higher renditions are added to the manifest as they finish.
A workflow coordinator stores the graph for each video: which tasks are done, which are running, which failed. Workers pull tasks from a queue, write their output to object storage under a deterministic path and report back. Because the output path depends only on the video, rendition and segment number, a retried task simply overwrites the same object, so retries are safe.
6. The architecture
- Clients
- Creator app (chunked upload)
- Player (adaptive bitrate)
- Edge
- CDN for segments and manifests
- Load balancer and API gateway
- Services
- Upload service
- Video metadata service
- View event collector
- Processing
- Workflow coordinator
- Task queue
- Encoding worker pool
- Storage
- Object storage: raw and processed buckets
- Metadata database + cache
- View counter store
- UploadThe client creates a session, then sends 8 MB chunks, several in parallel. The upload service writes each chunk to object storage (or hands the client a short-lived signed URL so the bytes skip the service) and marks it in the session's bitmap. A dropped connection resumes from the first missing chunk.
- Process
completeassembles the chunks, emits a video-uploaded event and returns at once. The coordinator builds the task graph and the workers run it. - WatchThe player fetches video metadata (served from cache), then the manifest and segments from the CDN, switching renditions as bandwidth changes. The design of the CDN and the player is covered in more depth in design Netflix.
- CountThe player sends a heartbeat after a few seconds of real playback and periodically after that. The collector drops them on a stream and returns immediately.
7. Scale it
- Autoscale the encoding pool on queue depth. Uploads have daily peaks; the worker pool can grow and shrink with the backlog, and cheaper interruptible machines suit tasks that are small and retryable.
- Prioritize the queue. Low renditions and thumbnails first, so time to publish stays short; 4K and re-encodes of old videos in a lower lane.
- Push popular content to the edge. A new video from a large channel can be pre-warmed in CDN caches; the long tail of old videos is served from regional caches or the origin on a miss.
- Tier storage by age and popularity. Recent and popular renditions stay on standard storage; videos nobody has watched in a year move to a cold tier, and rarely used renditions can be deleted and regenerated from the original if needed.
- Cache metadata aggressively. Title, status and manifest URL change rarely; a cache with a short TTL in front of the sharded metadata store absorbs the video-page traffic. The caching guide covers invalidation choices.
Counting views without melting a row
At 23,000 view starts a second on average, and far more on one viral video, a write per view is the wrong shape. The collector puts heartbeats on a partitioned stream keyed by video_id. Aggregators read a partition, drop events that fail simple validity checks (too short, same session repeating, known bad clients), sum the rest per video for a few seconds and apply one increment per video per window to the counter store. The public number is eventually consistent; the exact, audited number for payouts or analytics can be computed later in a batch job from the same events.
from collections import Counter
def flush_window(events, counter_store):
per_video = Counter()
for e in events:
if e["watched_seconds"] < 5 or e["session_seen"]:
continue # not a view by our rule
per_video[e["video_id"]] += 1
for video_id, n in per_video.items():
counter_store.increment(video_id, n) # one write per video, not per view8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| An encoding worker dies mid-task | One segment of one rendition is missing | Task leases with a timeout; the coordinator re-queues expired tasks and the deterministic output path makes the retry idempotent |
| A poison video crashes the encoder every time | Retries burn compute forever | Cap attempts per task, mark the video failed, keep the raw file and alert; tell the creator what went wrong |
| Upload connection drops at 90% | Creator would start over | Resumable sessions: the client asks which chunks arrived and sends only the rest |
| CDN region outage | Viewers there see stalls | DNS or anycast steers them to the next region; the player retries a segment on an alternate host listed in the manifest |
| Viral video | One video takes a large share of all traffic | Its segments are hot in every edge cache; the counter path batches increments so the hot key gets one write per window |
| Metadata database failover | Status updates and new uploads stall briefly | Playback continues from cached metadata and the CDN; uploads retry with backoff |
9. Trade-offs to discuss
- Upload through the service or straight to storage. Signed URLs remove the upload service from the byte path and save bandwidth, but you lose a place to inspect or throttle traffic as it arrives. Most designs use signed URLs and validate after.
- Encode every rendition up front or on demand. Up front costs compute and storage for videos nobody watches; on demand saves both for the long tail but makes the first viewer of an unusual rendition wait. A common middle ground encodes the core ladder immediately and the rest only for videos that gain views.
- Keep the original or not. Keeping it lets you re-encode with a better codec later, at the cost of storing the largest file forever. Many designs keep it on a cold tier.
- Exact or approximate view counts. Exact counting on the hot path is expensive and fragile. A fast approximate public number plus a slower audited number is the usual answer; say which number pays creators.
- Segment length. Short segments let the player adapt and start faster; long segments mean fewer requests and better compression. A few seconds is a common compromise.
10. How to talk through it in the interview
Fictional example
- Interviewer
- Design YouTube.
- Candidate
- That covers a lot. I would like to do upload, processing, playback and view counts, and leave recommendations, comments and live streaming out. Does that work?
- Interviewer
- Fine. Spend most of your time on what happens after the upload.
- Candidate
- Then my numbers: about 6 uploads a second at 400 MB each, so 200 TB of raw video a day. That rules out encoding on the upload server. I will split each video at keyframes, encode the segments in parallel on a worker pool behind a queue, and publish as soon as the low renditions exist.
A workable split of 45 minutes for this prompt: about 5 minutes cutting scope, 5 on the estimate (the egress figure is what justifies the CDN), 5 on the upload API and data model, 10 on the architecture, then 15 on the processing graph and view counting, and the last 5 on failures and trade-offs. If the interviewer pulls you toward playback, shorten the pipeline and talk about adaptive bitrate and edge caching instead.
- Say why the pipeline is a graph of small tasks: speed through parallelism and cheap retries.
- Explain when a video becomes visible, and what the creator sees while it processes.
- Bring up the view counter's hot key yourself; it is a favorite follow-up.
Practicing this design with Natively
Treat the prompt as a live rehearsal: have someone on a call interrupt you with "what if a worker dies halfway through a 4K encode?" or say both parts yourself. Natively writes down both voices as you go and can offer talking points when a question lands, which makes it easy to see afterwards whether you ever reached view counting or storage tiers. You can also ask it to draw the upload and processing flow as a diagram inside its answer and compare it with your own sketch. The saved transcript and notes let you replay the session and trim the parts where you spent ten minutes on codecs.
Questions people ask
What should I focus on when asked to design YouTube?
Cut the scope first: upload, processing, playback and view counts are a complete answer, with recommendations and comments left out. Then spend the deep dive on the transcoding pipeline, because playback on its own looks like any CDN design. Most follow-ups land on parallel encoding, retries and the view counter.
How does video transcoding work in a system design interview answer?
Split the uploaded file at keyframes into segments of a few seconds, then encode every segment into every rendition as separate tasks on a queue served by a worker pool. A coordinator tracks the task graph per video and re-queues tasks whose workers die. Package the results as HLS or DASH with a manifest per video.
How do you count views for a video service at scale?
Send player heartbeats to a partitioned event stream instead of writing to the database per view. Aggregators filter invalid views, sum per video over a short window and apply one increment per video. The public count lags a little; an exact count for analytics or payouts comes from a batch job over the same events.
Should a video be playable before all resolutions are encoded?
Usually yes. Publish once the lower renditions and the manifest exist, then add higher qualities as their encodes finish. Waiting for the slowest rendition, often 4K, delays every creator for little benefit, and adaptive players pick up new renditions on their next manifest fetch.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
