System Design Interview Crash Course
Vote

0% completed

​

Design YouTube

  1. Problem Definition and Scope
  1. Clarify functional requirements
  1. Clarify non-functional requirements
  1. Back of the envelope estimates
  1. API design
  1. High-level architecture
  1. Data model
  1. Core flows end-to-end

Flow A: Uploading a Video

Flow B: Streaming a Video

  1. Caching and read performance
  1. Storage, indexing and media
  1. Scaling strategies
  1. Reliability, failure handling and backpressure
  1. Security, privacy and abuse
  1. Bottlenecks and next steps

The complete picture

Summary

The decisions that mattered

The numbers that forced them

What breaks first

If the interviewer pushes

Image

This lesson designs YouTube, a website where people upload videos and millions of other people watch them. The design has two very different halves: a small, careful path for uploads, and a very large, very fast path for watching. Every section below belongs to one of those two halves.

1. Problem Definition and Scope

We are designing a video platform where users upload videos and watch them on demand. The system must accept a large, steady flow of new video files, and it must start playback quickly for viewers anywhere in the world.

  • Main User Groups:

    • Creators: People who upload videos and edit the details of their channel, like titles and descriptions.
    • Viewers: People who search for videos and watch them. This is by far the larger group.
  • Scope:

    • In Scope: Video upload (ingestion), video processing (transcoding), streaming (playback), search, and metadata such as likes and view counts.
    • Out of Scope: Live streaming, the recommendation system (the home feed), monetization and ads, and social features such as subscriptions and comments.

Agreeing on scope first matters because each of the out-of-scope features is a full design of its own. Leaving them out lets us spend the time on the two paths that make YouTube hard: getting video in and getting video out.

Image

2. Clarify functional requirements

Functional requirements list what the system must do for its users.

Must Have:

  • Upload Video: Users can upload a video file. The system then converts it so that it plays on any device.
  • Stream Video: Users can watch a video with little or no pausing to load (buffering).
  • Adaptive Quality: The picture quality, for example 360p, 720p or 4K, changes automatically to match the viewer's internet speed.
  • Search: Users can find videos by title or tags.
  • Stats: Users can like a video and see how many views and likes it has.

Nice to Have:

  • Resumable Uploads: If an upload stops halfway, it continues from where it stopped instead of starting again.
  • Watch History: A viewer can return to a video and continue from where they left off.

Notice that the two most important requirements have opposite needs. Uploads can be slow as long as they are reliable, while streaming must be fast every time.

Image

3. Clarify non-functional requirements

Non-functional requirements describe how well the system must work: how big, how fast, and how reliable.

  • Scale: The system must support 1 billion daily active users (DAU), meaning 1 billion different people use it on a normal day.
  • Read vs. Write: The system is extremely read-heavy. There is roughly 1 upload for every 1,000 views, a ratio of 1:1000.
  • Latency: Latency is the time a user waits for a response.
    • Uploads: A delay of several minutes is acceptable. Processing happens in the background (asynchronously), so the creator does not have to wait on the page.
    • Streaming: Playback must start quickly. The time to first byte (TTFB), which is the time until the first piece of video data arrives, should be under 200 ms.
  • Availability: 99.99%. Playback is the core product, so it must almost never be down. For reference, 99.99% still allows about 52 minutes of downtime a year, so the design must contain failures rather than assume none.
  • Consistency:
    • Metadata: The creator must see their own new video and its title as soon as they save it. This is called read-your-own-writes consistency. Other viewers can see the change a moment later.
    • View Counts: Eventual consistency is fine. If a view count is a few minutes behind, nobody is harmed.
  • Data Retention: Videos are kept forever unless the creator deletes them.

The 1:1000 ratio is the most important number on this list. It tells us that any expensive work should happen once, when a video is uploaded, and not again each time someone watches it.

Image

4. Back of the envelope estimates

These estimates are rough on purpose. Their job is to show which part of the system needs the most attention.

  • Storage (Writes):

    • Starting figure: 500 hours of video are uploaded every minute.
    • Per day: 500 hours × 60 minutes × 24 hours = 720,000 hours of new video a day.
    • Assume one hour of uploaded video is about 1 GB. This is a simple average for the estimate; a phone recording at 1080p is often 3 to 5 GB per hour, so real numbers can be several times higher.
    • Raw storage: 720,000 hours × 1 GB = 720 TB per day.
    • Transcoding: We keep several versions of each video (360p, 480p, 720p, 1080p and 4K). Together with the original, they take about 3 times the raw size.
    • Total new storage: 720 TB × 3 ≈ 2 PB (petabytes) per day.
  • Bandwidth (Reads):

    • Starting figure: 5 billion views per day, which is about 5 views for each of the 1 billion daily users.
    • Assume an average view downloads 100 MB, a mix of short mobile views and longer desktop views.
    • Total data sent to viewers (egress): 5 billion × 100 MB = 500 PB per day.
    • Throughput: 500 PB ÷ 86,400 seconds ≈ 5.8 TB per second, which is about 46 terabits per second. Busy evening hours run higher than this average.
  • Checking the ratio: If an average upload is about 7 minutes long, 720,000 hours a day is about 6 million videos. Against 5 billion views, that is close to the 1:1000 ratio from section 3.

  • Conclusion: No single data center can send 5.8 TB every second to viewers spread across the world. Video must be served from a global Content Delivery Network (CDN), which is a large set of cache servers placed close to viewers in many cities.

Image

5. API design

The API is the set of requests the app sends to our servers. We use a REST API, which means plain HTTP requests on named URLs. One rule shapes the whole design: the video file itself never passes through the API servers. The API only handles small text requests.

1. Initiate Upload

  • POST /videos/init
  • Request: {"title": "My Cat", "size": 1073741824, "format": "mp4"} (the size is in bytes, here 1 GB)
  • Response:
{ "video_id": "vid_123", "upload_url": "https://s3-upload-signed-url..." }
  • Note: The response contains a presigned URL. This is a temporary link, signed by our server, that lets the app upload this one file straight into cloud storage.

2. Stream Video

  • GET /videos/{video_id}
  • Response:
{ "title": "My Cat", "stream_url": "https://cdn.youtube.com/vid_123/master.m3u8", "views": 10500, "likes": 200 }
  • Note: stream_url points to a manifest file, a small text file that lists every available quality and where its pieces are stored. It does not point to one large video file. Section 8 explains how the player uses it.

3. Search

  • GET /search?q=cat&page=1
  • Response: A list of short video summaries: ID, title, thumbnail, and view count.

4. Like Video

  • POST /videos/{video_id}/like
  • Response: 200 OK
  • Note: The server records each like as one pair of user and video. If the user taps twice, the second request finds the pair already there and changes nothing, so a like is never counted twice.

6. High-level architecture

We split the system into two parts. The control plane handles small text requests: video details, users, search and likes. The data plane moves the video bytes themselves: uploading, processing, storing and streaming them. The two parts have very different traffic, so we scale them separately.

Architecture Flow:

  1. Client (the mobile app or web browser)
  2. Load Balancer, which spreads requests across many API servers
  3. API Gateway, which checks who the user is (authentication) and limits how many requests one user can send (rate limiting)
  4. Microservices, small services that each own one job:
    • Video Metadata Service
    • User Service
    • Search Service
  5. Databases & Cache:
    • SQL database for video details
    • Redis, an in-memory cache for the most requested details
    • Elasticsearch, a search engine that holds the search index
  6. Async Processing:
    • Message Queue (Kafka), which holds processing jobs until a worker is free
    • Transcoding Workers, servers that convert videos, often with GPUs or dedicated video chips
  7. Storage:
    • Object Storage (such as Amazon S3), the permanent home of every video file
    • CDN, the edge servers that stream video to viewers

Component Roles:

  • CDN: Serves about 99% of all video traffic. Most viewers never reach our own storage.
  • Object Storage (S3): Stores very large video files cheaply and safely. It is the source of truth, meaning that if any copy disagrees, this one is correct.
  • Transcoding Workers: Convert each uploaded video into the formats and sizes that players can stream (HLS or DASH, explained in section 8).
  • Metadata DB: Stores the text about each video: title, description, uploader and processing status.
Image

7. Data model

We use three kinds of storage, because the data has three different patterns of use.

1. Relational Database (MySQL/PostgreSQL) This holds the important details that must stay correct. The Videos table is split across many machines (sharded) by video_id, and the Users table is sharded by user id.

  • Videos Table: id (primary key), uploader_id, title, description, storage_path, status (processing, active or failed).
  • Users Table: id, email, name.
  • A channel page needs "all videos by this uploader". Because videos are sharded by video_id, we keep a second small table keyed by uploader_id that lists that creator's video IDs, so the page reads one shard instead of all of them.

2. NoSQL (Cassandra) This holds counters that change constantly. Cassandra is a wide-column database built to accept a very high rate of writes.

  • VideoStats: video_id (primary key), view_count, like_count.
  • Likes: (video_id, user_id), one row per like, which is how a repeated like is ignored.
  • Why not SQL? A viral video can receive thousands of views per second. In SQL, every view would lock and update the same row, and that single row would become a write hotspot that slows the whole database. Cassandra's counter columns accept increments without row locks. We also collect view events for a few seconds and write one combined increment per video, which cuts the writes further.

3. Search Index (Elasticsearch)

  • Stores video titles and tags so that users can search by words. It also supports fuzzy matching, so a search for "cats" still finds "cat".

8. Core flows end-to-end

This section follows the two most important journeys through the system: uploading a video and watching one. For each step, we describe what happens, why the step is needed, and what it produces.

Flow A: Uploading a Video

Goal: Turn one large file from a creator's camera into many small, streamable files that viewers anywhere can load quickly.

The upload flow is asynchronous. The creator's part ends when the file is stored. Everything after that happens in the background, and the creator is free to leave the page.

Step 1: Uploading Directly to Storage (Presigned URLs)

What happens:

  1. Request: The app asks the API: "I want to upload a file named cat.mp4."
  2. Permission check: The API confirms that the user is logged in and allowed to upload.
  3. Presigned URL: The API creates a presigned URL for object storage and returns it. This URL allows exactly one action, uploading this one file to this one location, and it expires after a short time.
  4. Direct upload: The app uploads the file straight to object storage, such as Amazon S3 or Google Cloud Storage. Large files are sent in parts (a multipart upload), so if the connection drops, only the unfinished part is sent again. This is how resumable uploads work.

Why: If a 1 GB file went through our API servers, each server would be busy for minutes receiving it. A thousand uploads at the same time would use up the API fleet, and normal requests like search would slow down for everyone.

Outcome: The raw file is safely in object storage, and our API servers only handled two small requests.

Step 2: Starting the Job (Message Queue)

What happens:

  • When the upload finishes, object storage sends an "upload complete" event to the upload service.
  • The service does not start processing right away. Instead, it creates a job, a small record holding the video ID and the file's location.
  • It places the job on a message queue such as Apache Kafka or RabbitMQ. A message queue is a list of jobs that waits safely until a worker is ready to take the next one.

Why: Uploads arrive unevenly. If a major event causes 10,000 uploads in one minute, starting all of that processing at once would overload the workers. The queue holds the extra jobs, and the workers take them at the rate they can handle. It also means the creator gets an answer at once instead of waiting for processing.

Outcome: Every upload becomes one job in the queue, and no job is lost if the workers are busy.

Step 3: Processing the Video (Transcoding & Chunking)

A large group of worker servers keeps taking jobs from the queue.

What happens:

  1. Pickup: A worker takes the next job from the queue.
  2. Validation: It checks the file: resolution, aspect ratio and audio format. A broken or unreadable file stops here.
  3. Transcoding: Transcoding means converting a video from one format to another. Uploaded files come in many formats, like .mov or a very high quality .mp4. The worker converts each one into standard streaming formats: H.264 for the widest device support, and newer formats like VP9 or AV1, which make smaller files at the same quality.
    • It produces several renditions, meaning versions of the same video at different qualities: 360p, 480p, 720p, 1080p and 4K.
  4. Segmentation (Chunking): The worker cuts every rendition into short pieces called segments or chunks, usually 2 to 10 seconds long.
    • Example: A 1 minute video cut into 5 second segments becomes 12 segments for each rendition.
  5. Manifest Generation: The worker writes the manifest file: .m3u8 for HLS (HTTP Live Streaming) or .mpd for DASH (Dynamic Adaptive Streaming over HTTP). The manifest is an index. It lists every rendition and the URL of each of its segments, for example "1080p: segments A, B, C" and "360p: segments X, Y, Z".

Why: One large file in one format cannot play well on every device and every connection. Small segments in several qualities let the player change quality every few seconds, and they let the CDN cache small pieces instead of whole files.

Outcome: Each video now exists as several renditions, each cut into segments, plus one manifest that ties them together.

Step 4: Distribution & Indexing

What happens:

  1. Storage: All segments and manifest files are saved to object storage.
  2. CDN: Most videos are not copied to the CDN in advance. An edge server fetches a segment the first time a nearby viewer asks for it. For a video we expect to be popular right away, such as a new release from a very large channel, the system may copy it to edge servers ahead of time.
  3. Database update: The video's status changes from "processing" to "active", and from then on viewers can see it.
  4. Search indexing: The title and tags are sent to Elasticsearch, so the video appears in search results.

Why: Each step makes the video available to one part of the system: storage holds it, the database lets the API return it, and the search index lets people find it.

Outcome: The video is playable and searchable worldwide, usually a few minutes after the upload finished.

Image

Flow B: Streaming a Video

Goal: Start playback quickly and keep it playing without pauses, whether the viewer is on fast home WiFi or a weak mobile signal.

YouTube uses Adaptive Bitrate Streaming (ABR) over normal HTTP, with the HLS or DASH formats. Bitrate is the amount of data per second of video. Adaptive means the player changes the bitrate during playback to match the connection.

Step 1: Getting the Video Details (Metadata & Security)

What happens:

  1. The click: A viewer clicks on a video.
  2. Metadata check: The app asks the API for the video's details. The API checks:
    • Does the video exist, and is it active?
    • Is it private or deleted?
    • Is this viewer allowed to watch it, for example because of an age limit?
  3. The response: The API returns the title, the counts, and the URL of the manifest file on the CDN.

Why: The permission checks must happen on our servers, before the viewer receives any address for the video.

Outcome: The player knows where the manifest is, and the viewer has been checked.

Step 2: The List of Versions (The Manifest)

What happens: The player downloads the manifest file first. It does not download any video yet. The manifest works like a menu of choices:

  • Option A: 4K quality, which needs a fast connection.
  • Option B: 1080p quality, which needs a medium connection.
  • Option C: 360p quality, which works on a slow connection.

Why: The player cannot choose a quality until it knows which qualities exist and where their segments are.

Outcome: The player has the full list of renditions and segment URLs.

Step 3: Choosing the Quality (Client-Side Logic)

The decision about quality is made on the viewer's device, not on our servers.

What happens:

  1. Measuring speed: The player times how long its downloads take to estimate the current connection speed. It often starts with a medium quality, so the first picture appears quickly, and then adjusts.
  2. Decision: On fast home WiFi, the player selects the 1080p rendition from the manifest.
  3. Fetching segments: The player requests the first 3 segments (15 seconds of video) from the nearest CDN edge server. The downloaded video waiting to be played is called the buffer.

Why: Only the device knows its own connection speed second by second. If our servers made this choice, every player would have to report its speed to us constantly, which adds traffic and delay.

Outcome: Video starts playing at a quality the connection can sustain, with a few seconds already stored in the buffer.

Step 4: Adaptive Switching

This is what happens when the connection gets worse, for example when the viewer walks out of WiFi range.

What happens:

  1. Monitoring: While playing 1080p, the player sees that each segment is taking longer to download.
  2. Calculation: The player works out that at this speed, the buffer will be empty in about 2 seconds, and the video would freeze.
  3. The switch: For the next segment, the player reads the 360p URL from the manifest instead of the 1080p one.
  4. The result for the viewer:
    • The picture becomes less sharp for a while.
    • The sound continues and the video does not stop.
    • When the connection improves, the player switches back up the same way.

Why: A short drop in picture quality is far less annoying for a viewer than a frozen video.

Outcome: Playback continues without pausing, using whichever quality the connection can handle at that moment.

Step 5: Latency & CDN

What happens:

  • Edge caching: Each segment request goes to the nearest CDN edge server, for example a server in London.
  • Cache miss: If the London server does not have the segment yet, because nobody nearby has watched this video, it fetches the segment from the origin (our object storage), keeps a copy, and sends it to the viewer.
  • Cache hit: The next viewer in London gets the segment straight from the London server, well within the 200 ms target.

Why: Sending data across an ocean adds delay to every request, and sending all 5.8 TB per second from one origin is not possible.

Outcome: Popular segments are served from a server close to the viewer, and the origin only serves the first request in each area.

Image

9. Caching and read performance

With 500 PB of video sent every day, caching is not an optional speedup. It is the only way the system can serve this traffic at all.

  • CDN (Content Delivery Network):

    • We keep copies of video segments on thousands of edge servers around the world.
    • A viewer in London downloads segments from a server in London, not from a data center in the US.
    • Why it works: Views are very uneven. A small share of videos receives most of the views, so the edge servers can hold those popular videos and answer most requests themselves.
    • Eviction: When an edge server is full, it removes the segments that were used least recently (LRU, least recently used). Popular videos stay; rarely watched ones are fetched from object storage again when someone asks.
  • Metadata Cache (Redis):

    • We cache video details such as title, uploader and like count.
    • Key: video_meta:{id}.
    • Strategy: Cache-aside. The service checks Redis first. On a miss, it reads the database and then saves the result in Redis for the next request.
    • Counts in the cache can be a few minutes old, which the eventual consistency requirement allows.

10. Storage, indexing and media

  • Blob Storage (S3): Blob storage means storage for large files (binary large objects).

    • We use storage tiers, which are classes of storage with different price and speed.
    • Hot: New and popular videos stay in standard storage, which is fast to read.
    • Cold (for example, S3 Glacier): The original uploaded files of old videos that nobody watches move to slower, much cheaper storage. This is safe because playback never reads the original file; it reads only the transcoded segments.
  • Search Indexing:

    • When a video becomes active, a background service copies its title and tags into Elasticsearch.
    • Elasticsearch keeps an inverted index, which maps each word to the list of videos that contain it. That makes word search fast, which a SQL database does not do efficiently at this size.

11. Scaling strategies

  • Database Sharding:

    • We split the metadata database across many machines by video_id.
    • A simple rule is shard_id = hash(video_id) % total_shards, which spreads videos evenly.
    • The weakness of this rule is that changing the number of shards moves almost every row. Real systems use consistent hashing or a fixed set of logical shards, so adding machines moves only a small part of the data.
  • Parallel Transcoding (Split & Merge):

    • Converting a long 4K video on one server can take hours.
    • Split: We cut the uploaded video into pieces of about a minute each. Each cut is made at a keyframe, a frame that does not depend on earlier frames, so every piece can be converted on its own.
    • Fan-out: We send the pieces to many workers, for example 50, which convert them at the same time.
    • Merge: A final step joins the results and writes the manifest. Processing time drops from hours to minutes, and if one piece fails, only that piece is redone.
  • Edge Servers Inside Internet Providers:

    • We place CDN servers inside the networks of internet service providers (ISPs), and we connect our network directly to theirs (peering). Video then travels a much shorter path to the viewer, which lowers both delay and our cost of sending data.

12. Reliability, failure handling and backpressure

Backpressure means slowing down the intake of work when the parts that process it are full. The message queue from section 8 is our main form of backpressure.

  • Dead Letter Queues (DLQ): If a video makes a worker crash, for example a corrupted file, we retry it 3 times. If it still fails, we move the job to a separate queue (a dead letter queue) for an engineer to inspect. This way one bad file cannot block every video behind it.

  • Thundering Herd Protection: A thundering herd is a large number of requests for the same thing at the same moment. When a very popular creator publishes a video, a million viewers may request it before any edge server has it. Each edge server uses request coalescing: the first request fetches the segment from the origin, and all other requests for that segment wait for that one response. A middle layer of regional caches (an origin shield) does the same between the edge servers and the origin, so the origin receives one request per region, not one per viewer.

  • Circuit Breakers: A circuit breaker stops calling a service that is failing and returns a fallback instead. If the view and like counter service is slow or down, the watch page still loads and plays the video, just without the counts. The core watching feature does not depend on it.

13. Security, privacy and abuse

  • Presigned URLs: Users never get general write access to our storage. Each upload receives a presigned URL that works for one file at one location and expires after a short time.

  • Signed Playback URLs: For private and age-restricted videos, the manifest and segment URLs carry a signed token that expires. A copied link stops working after a short time, so the permission check in Flow B cannot be skipped by sharing a URL.

  • Digital Rights Management (DRM): For paid content, the segments are encrypted. The player must request a decryption key from a license server, and only approved players receive it.

  • Content ID: During processing, we create audio and video fingerprints, which are short summaries of the content, and compare them against a database of copyrighted material. A match can block the upload or apply the rights owner's policy.

14. Bottlenecks and next steps

  • Bottleneck: Bandwidth cost. Sending video is the largest cost of the whole system.

  • Next Step: Use per-title encoding. Analyze each video's complexity and choose its bitrates to match. A simple cartoon needs fewer bits than a fast action scene for the same visible quality. Netflix reported savings of about 20% in bandwidth from this approach.

  • Bottleneck: Search freshness. A new video can take minutes to appear in the main search index.

  • Next Step: Keep a small real-time index for videos uploaded in the last hour, search both indexes together, and merge the small one into the main one later.

The complete picture

Every diagram above shows one part of the system. This one shows all of them together: the upload path, the background processing, the metadata path and the streaming path, with the caches, queues and scaling strategy of each one marked. Notice that the upload path and the streaming path meet in only one place, object storage.

The complete architecture, with caches, queues and scaling strategies marked
The complete architecture, with caches, queues and scaling strategies marked

Summary

Say this first. YouTube is two systems behind one website. The control plane handles small text requests, like titles, likes and search, and it works like a normal read-heavy web service. The data plane moves the video itself, about 5.8 terabytes a second, and that traffic never passes through our application servers. Once you separate those two, every other decision follows from it.

The decisions that mattered

DecisionWhyWhat it costs
Presigned upload straight to object storageA 1 GB upload would keep a web server busy for minutesThe app has to manage the upload itself, including resuming it
Transcode in the background behind a queueThe creator should not wait, and a burst of uploads must not overload the workersA video is not watchable the moment the upload ends
Split each video and transcode the pieces in parallelA long 4K video on one machine takes hoursA final step has to join the pieces and write the manifest
Adaptive bitrate with a manifest fileOnly the device knows its own connection speedWe store every rendition, roughly tripling storage
Counters in a wide-column store, not SQLOne SQL row per viral video becomes a write hotspotView counts are eventually consistent

The numbers that forced them

NumberWhat it decided
5.8 TB per second of egressA CDN is not an optimization here; it is the only way to serve the traffic at all
1 upload for every 1,000 viewsDo the expensive work once, at upload time, and spend the engineering effort on the read path
720 TB of raw video a dayObject storage, and cold tiering for originals nobody watches
Roughly 3x storage after transcodingPer-title encoding is worth a lot of money

What breaks first

  1. Bandwidth cost. This is a money problem, not an outage. Better codecs and per-title encoding are the main tools, and both are worth mentioning before the interviewer asks.
  2. A corrupted upload blocking the pipeline. Three retries and then a dead letter queue, so one bad file cannot stop every other video behind it.
  3. A very popular new upload. A million people request a video that no edge server has yet. Request coalescing and an origin shield mean the origin serves each segment once per region, not a million times.

If the interviewer pushes

  • "Why not store one high-quality file and convert it to lower quality as people watch?" Converting on demand costs computing power for every view. Converting once costs it for every upload. At 1,000 views for every upload, converting once is far cheaper.
  • "How does the player know when to switch quality?" It does not ask our servers. It downloads a manifest that lists every rendition, measures its own download speed between segments, and chooses the quality of the next segment itself.
  • "What happens when the search index falls behind?" A new video cannot be found for a few minutes. The fix is a small real-time index for the last hour, searched together with the main index and merged into it later.
  • "Where would this design stop working?" Live streaming. Everything here assumes the whole file exists before anyone watches it, while live video has to be processed and delivered seconds after it is recorded.

Reading Progress

0%


Vote for new content

On This Page

  1. Problem Definition and Scope
  1. Clarify functional requirements
  1. Clarify non-functional requirements
  1. Back of the envelope estimates
  1. API design
  1. High-level architecture
  1. Data model
  1. Core flows end-to-end

Flow A: Uploading a Video

Flow B: Streaming a Video

  1. Caching and read performance
  1. Storage, indexing and media
  1. Scaling strategies
  1. Reliability, failure handling and backpressure
  1. Security, privacy and abuse
  1. Bottlenecks and next steps

The complete picture

Summary

The decisions that mattered

The numbers that forced them

What breaks first

If the interviewer pushes