InterviewDryRun
Lesson 11 · 22 min video · free

Design a Video Streaming Service

Creators upload large video files, and viewers on phones, laptops and TVs expect them to start in a second and never buffer, even on a bad connection. This lesson designs the whole path: resumable uploads, a parallel transcoding pipeline that produces many qualities, adaptive bitrate streaming in small segments, and a CDN that carries almost all of the bytes.

What you will learn

  • Split the system into an upload and processing path and a much larger playback path.
  • Upload directly to object storage in resumable chunks with signed URLs.
  • Transcode in parallel per chunk into a ladder of resolutions and bitrates.
  • Adaptive bitrate streaming: short segments, a manifest, and a player that picks quality.
  • The CDN serves almost all bytes; popular videos are pushed to the edge.
  • View counts and metadata are separate, smaller systems with their own scaling.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The API
  5. Step 4: The high-level design
  6. Step 5: Uploading large files
  7. Step 6: The transcoding pipeline
  8. Step 7: Adaptive bitrate streaming
  9. Step 8: The content delivery network
  10. Step 9: Every device, every network
  11. Step 10: Metadata, search and permissions
  12. Step 11: Counting views
  13. Step 12: Failures and cost
  14. Step 13: The follow-up questions
  15. Recap

Short on time? Read the answer outline for design a Video Streaming Service.

Practice this question with Max

The question

Welcome to lesson eleven of the InterviewDryRun system design course. Today we design a video streaming service: creators upload videos, and viewers watch them on phones, laptops and televisions, anywhere in the world.

Video is a fascinating interview question because it is dominated by one thing: bytes. A single minute of high quality video can be a hundred megabytes. Multiply that by hundreds of millions of viewers and you have one of the largest traffic flows on the internet. The interviewer wants to see that you know where those bytes should flow, which is almost never through your own application servers, and how a player keeps a video smooth when the viewer's connection keeps changing.

Max asks

“Design a service where creators upload videos and viewers stream them on any device.”

That is how Max, our AI interviewer, asks it. Two sides: creators who upload, and viewers who stream. They have very different needs. Uploads are relatively rare, large and can take minutes to process. Playback is constant, enormous and must start instantly. So the first move in this interview is to split the design into those two paths, and to say that playback is where most of the scale lives.

The plan: requirements and numbers, then the API and the high-level design. Then the upload path, the transcoding pipeline, adaptive streaming, the content delivery network, metadata and search, view counts, and failures. And the follow-up questions at the end.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    UploadLarge files, up to many gigabytes, from creators
  2. 02
    ProcessMake the video playable on every device and connection
  3. 03
    WatchStart fast, adapt quality, seek anywhere
  4. 04
    MetadataTitle, description, thumbnail, channel
  5. 05
    CountsViews and likes shown on each video

Start with questions, and set the scope, because this question could include comments, recommendations, live streaming, monetisation and much more. Say you will focus on upload, processing and playback, with metadata and view counts as supporting pieces.

Uploads can be large, several gigabytes for a long high-resolution video, and creators may be on unreliable connections. After upload, the video must be processed into formats that every device can play, at several qualities. Ask how quickly a video must be available after upload. Minutes is a reasonable answer, and it means processing can be asynchronous.

Playback must start quickly, adapt to the viewer's bandwidth, and allow seeking to any point. That last one sounds obvious, but it shapes how we store the video: as many small pieces rather than one big file.

And supporting features: metadata like title and thumbnail, and counts of views and likes. Say live streaming is out of scope, but mention that most of the playback design would carry over.

Non-functional requirements
  1. 01
    Fast startPlayback begins in about a second
  2. 02
    SmoothRebuffering is the number one complaint
  3. 03
    GlobalViewers everywhere, on every kind of network
  4. 04
    DurableAn uploaded original is never lost
  5. 05
    Cost awareBandwidth and storage dominate the bill

Now the qualities. Playback should start in about a second, and rebuffering, the spinning wheel in the middle of a video, should be rare. Viewers judge the whole service by those two things.

It is global: viewers are everywhere, on fibre, on crowded mobile networks, and on hotel Wi-Fi. And durability: once a creator has uploaded a video, losing it would be unforgivable, so originals must be stored very safely.

And cost. Say this one out loud, because it is unusual. In most designs, servers are the main cost. Here, bandwidth and storage dominate. Decisions like how many qualities to store and how much traffic the content delivery network carries are really cost decisions, and interviewers like candidates who notice that.

Step 2: Back-of-the-envelope estimates

Sizing the service
Daily viewers100 millionwatching 30 minutes each
Watch time50 million hours / day100 M x 0.5 hours
Average bitrateabout 3 Mbit/smix of phones and TVs
Egressabout 7 Tbit/s averagepeak two to three times higher
Uploads500 hours / minuteof new video
New storageabout 1 PB / dayoriginal plus all renditions

Let us size both paths.

Playback first. Say a hundred million daily viewers, each watching thirty minutes. That is fifty million hours of video a day.

At an average of three megabits a second, a mix of phone screens and televisions, fifty million hours a day works out to roughly seven terabits a second on average, and two or three times that at the evening peak. That is far beyond what any data centre can serve on its own. So the very first conclusion is: playback must come from a content delivery network, with servers inside internet providers' networks, close to viewers. Our own servers should only carry a tiny fraction of the bytes.

Now uploads. Say five hundred hours of new video every minute. After transcoding into several qualities, an hour of video might take a few gigabytes in total, plus the original. That adds up to around a petabyte of new storage a day. So storage grows very fast, and we will want cheaper storage tiers for old videos that nobody watches.

Notice the asymmetry. Upload and processing is heavy computation on a modest number of videos. Playback is light computation on an enormous number of bytes. The two paths need completely different designs, which is exactly why we split them.

And the processing compute. Encoding one hour of video into five renditions can take tens of CPU hours with good quality settings. Five hundred hours of uploads a minute is thirty thousand hours an hour, so the transcoding fleet needs hundreds of thousands of CPU cores running all the time. That is why encoding efficiency and choosing which videos deserve which renditions matter so much.

Step 3: The API

API
POST /v1/videos                    → { videoId, uploadUrl }
PUT  {uploadUrl}?part=7             // chunks, straight to storage
POST /v1/videos/{id}/complete

GET  /v1/videos/{id}
→ { title, channel, thumbnail, duration, views,
    manifestUrl: "https://cdn.example/v/abc/master.m3u8" }

GET  {manifestUrl}                  // from the CDN
GET  .../720p/segment_00042.ts      // from the CDN

The API makes the split visible. To upload, the creator's app first creates a video record and receives an upload URL. The upload itself goes in chunks directly to object storage, not through our API servers. When all chunks are in, the app calls complete, and processing starts.

To watch, the player fetches the video's metadata, which includes a manifest URL. From then on, the player only talks to the content delivery network: first the manifest, then the video itself, as a stream of small segment files. Our application servers answer one small request per view. The CDN answers everything else.

That is worth saying explicitly: our API never touches video bytes, in either direction. Uploads go to object storage, playback comes from the CDN. The API is about metadata and permissions, which is why it can stay small.

Step 4: The high-level design

Two paths
chunksoriginsegmentsinfoCLIENTCreatorSTORERaw uploadsobject storageWORKERTranscodingpipeline of workersSTORERenditionssegments + manifestsEDGECDNedge cachesCLIENTVieweradaptive playerSERVICEMetadata API

Here is the whole system in one picture. On the top row, the upload path. The creator uploads chunks directly into object storage, into a bucket for raw uploads.

When the upload completes, an event starts the transcoding pipeline: a fleet of workers that turns the original file into many versions, at different resolutions and bitrates, cut into small segments, with manifest files that describe them. These outputs, called renditions, go into another storage bucket.

On the bottom row, the playback path. The rendition bucket is the origin for the content delivery network. Viewers' players fetch manifests and segments from the nearest edge, which fetches from the origin only on a miss.

And the metadata API, which serves titles, thumbnails, permissions and counts. It is a normal web service with a database and caches, tiny in bytes compared with the video traffic, but it has a very high request rate, because every page view and every recommendation needs it.

Step 5: Uploading large files

Resumable uploads
  1. 01
    Signed upload URLTime-limited permission to write one object
  2. 02
    Chunks of 5 to 10 MBUploaded in parallel, each with a checksum
  3. 03
    ResumeAsk which chunks arrived; send only the rest
  4. 04
    CompleteStorage assembles the chunks; we verify and start processing

Uploading a four gigabyte file over a mobile connection will fail partway through more often than not, so uploads must be resumable. The app asks our API for a signed upload URL: a link that grants permission to write exactly one object, for a limited time. Then it sends the file straight to object storage.

The file goes in chunks of a few megabytes, several in parallel, each with a checksum so corruption is detected. Object stores support this pattern natively, as multipart uploads.

If the connection drops, the app asks which chunks have arrived, and sends only the missing ones. A creator on a train can upload a long video across several tunnels without starting over.

When all chunks are in, the app calls complete. The storage service assembles the file, we verify its checksum and basic validity, mark the video as processing, and publish an event to start the pipeline. The original file is stored with high durability, replicated across zones, because it is the one thing we can never recreate.

Two small protections belong at upload time. Limit uploads per creator per day, which stops abuse and runaway scripts from filling our storage. And run quick checks before the expensive pipeline starts: is this a real video file, is it within the length limit, and does it match a known fingerprint of content we are not allowed to host? Rejecting early saves hours of transcoding on files we would delete anyway.

Step 6: The transcoding pipeline

Transcoding as a graph of tasks
QUEUEUpload completeWORKERInspect + splitinto 10 s chunksWORKEREncode chunk1080p, 720p...WORKEREncode chunkin parallelWORKERThumbnails, audiocaptionsWORKERPackagesegments + manifests

Transcoding is the heavy computation in this system, so let us design it carefully. The first step inspects the original: its format, resolution, frame rate and duration, and rejects anything broken or disallowed. Then it splits the video into chunks of a few seconds each, cut at points where the video can be decoded independently.

Why split? Because encoding a one-hour video as a single job, on one machine, could take hours. Encoding several hundred ten-second chunks in parallel, on hundreds of workers, finishes in minutes. Each worker encodes one chunk into every rung of the quality ladder: say four hundred and eighty, seven hundred and twenty, ten-eighty, and higher if the original allows.

In parallel, other tasks extract audio tracks, generate thumbnails at several points, and produce captions from speech recognition if we offer that. The pipeline is a graph of tasks with dependencies, run by a workflow engine that tracks which tasks are done and retries failures.

When every chunk is encoded, the packaging step cuts the output into streaming segments, writes the manifest files, and publishes them to the renditions bucket. Then the video's status changes to ready, and the creator is notified.

A quality ladder
RenditionResolutionBitrate
Low426 x 240about 0.4 Mbit/s
Mobile854 x 480about 1 Mbit/s
HD1280 x 720about 2.5 Mbit/s
Full HD1920 x 1080about 5 Mbit/s
4K3840 x 2160about 15 Mbit/s

This is a typical ladder. Mention two refinements. First, not every video deserves every rung: a video that will get a hundred views does not need a 4K rendition, so encode the top rungs only when a video becomes popular. Second, encoding settings can be tuned per video: a static lecture needs far fewer bits than a fast sports clip at the same quality. Both save a lot of storage and bandwidth, which, as we said, is the main cost.

Transcoding workers are stateless and their work is queued, so they are a perfect fit for cheap, interruptible compute capacity. If a worker disappears mid-chunk, the task times out and is retried elsewhere. Say that, because it is a significant cost saving that interviewers appreciate.

Step 7: Adaptive bitrate streaming

Manifests
master manifest:
  720p  2.5 Mbit/s  → 720p/index.m3u8
  480p  1.0 Mbit/s  → 480p/index.m3u8
  240p  0.4 Mbit/s  → 240p/index.m3u8

720p/index.m3u8:
  segment_00000.ts   4 s
  segment_00001.ts   4 s
  ...

Now the part that makes video feel good: adaptive bitrate streaming. Instead of one big file, each rendition is cut into short segments, a few seconds each. A master manifest lists the available qualities, and each quality has its own list of segments.

The player downloads the master manifest, chooses a starting quality, and begins fetching segments one after another, keeping a buffer of, say, twenty seconds ahead of what is playing. After each segment, it measures how fast that download was and how full its buffer is.

If the network is fast and the buffer is healthy, it switches up to a higher quality for the next segment. If the network slows and the buffer is draining, it switches down before the buffer runs out. Because segments at every quality line up exactly in time, switching is seamless. The viewer sees the picture get slightly sharper or softer, instead of seeing the video stop.

This design gives us several things at once. Fast start: begin with a lower quality segment, which downloads quickly, then step up. Seeking: jump straight to the segment that contains the requested time. And caching: segments are small, ordinary files with fixed names, which content delivery networks are extremely good at caching. All the intelligence lives in the player; the servers just serve files.

A detail worth mentioning: segment length is a trade-off. Short segments, two seconds, let the player adapt quickly and start fast, but mean more requests and slightly less efficient compression. Longer segments, six to ten seconds, are more efficient but adapt slowly. Around four seconds is a common compromise.

Step 8: The content delivery network

Getting bytes close to viewers
  1. 01
    Edges inside networksServers inside internet providers, near viewers
  2. 02
    Popularity follows a power lawA small share of videos is most of the traffic
  3. 03
    Push the hitsPre-position popular videos at the edge overnight
  4. 04
    Pull the long tailFetch on first request, cache by recent use
  5. 05
    Shield the originA middle tier so misses do not all hit storage

With seven terabits a second or more, the content delivery network is the most important part of the playback path. Its edge servers sit inside internet providers' networks and in exchange points around the world, close to viewers. A segment served from inside the viewer's own provider avoids long-distance links, which is faster and much cheaper.

Video popularity follows a steep power law. A small share of videos accounts for most of the views on any given day. That is great news for caching: the edge can hold the popular videos and serve most requests without ever going back to the origin.

For the hits, we can do better than waiting for a miss. Predict what will be popular, from trends and new releases from big channels, and push those videos to the edges during off-peak hours, when bandwidth is cheap. The long tail, videos watched rarely, is pulled on demand: the first viewer in a region causes a fetch, and the edge keeps it for a while.

Between the edges and the origin, put a middle tier of regional caches, an origin shield. Many edge misses for the same segment then become one fetch from the regional cache, and the origin storage sees only a trickle. That protects it when a video suddenly goes viral everywhere at once.

Players also get a choice of edges. The metadata API, or the DNS system, directs each viewer to a nearby, healthy edge, and the player can fall back to another one if segments start failing. Some players even measure several edges at the start and pick the fastest.

Step 9: Every device, every network

Playing well everywhere
  1. 01
    Two packaging formatsDifferent platforms expect different manifest formats
  2. 02
    Package once, serve bothCommon segment format, two small manifests
  3. 03
    Codec per deviceNewer codecs where supported, a universal one as fallback
  4. 04
    Start-up tricksPreload the first segment when a thumbnail is in view

Any device means a surprising amount of variety. Different platforms expect different streaming formats: one family of devices prefers one manifest format, others prefer another. Historically, that meant storing every video twice.

The modern answer is to package segments once, in a common container format, and generate two small manifest files that both point at the same segments. Storage is shared, and the content delivery network caches one set of segments for everyone. Mention this, because it halves a big part of the storage and cache footprint.

Codecs vary too. Newer codecs can deliver the same picture quality at a much lower bitrate, but older devices cannot decode them. So encode popular videos in both a newer codec and a universal one, and let the master manifest offer both; each player picks what it supports. Again, a cost decision: the extra encoding is worth it only for videos that get enough views.

And start-up time can be improved before the user even presses play. When a video's thumbnail scrolls into view, the app can quietly fetch the manifest and the first low-quality segment, so playback starts the instant the user taps. Small tricks like this are what make a service feel fast, and they cost little, because those first segments are tiny.

Finally, poor networks. On a weak mobile connection, the player should start at the lowest rung, keep a longer buffer, and be conservative about switching up, because a switch up followed by a stall is worse than staying at a lower quality. Players also remember the bandwidth they measured last time on this network, so they can choose a good starting quality straight away.

Step 10: Metadata, search and permissions

Metadata
TableKeyHolds
videosvideo_idchannel, title, status, duration, manifest path
channelschannel_idname, owner, subscriber count
renditionsvideo_id, qualitypath, size, codec
countersvideo_idviews, likes (approximate)

The metadata side is a classic web service. A videos table holds the title, channel, status, which moves from uploading to processing to ready, the duration and the manifest path. It is read on every video page view, so cache it heavily: a popular video's metadata may be requested hundreds of thousands of times a second.

Renditions are tracked so we know what exists for each video, which matters for cleanup and for re-encoding later. And counters live separately, as in the news feed lesson, because they change constantly.

Permissions matter for private and unlisted videos, and for paid content. The segment URLs on the content delivery network can be signed: the metadata API, after checking that the viewer may watch, hands out a manifest with time-limited signatures on the segment URLs. The edge checks the signature without calling us. That keeps the edge fast and still enforces access. For premium content, add encryption of the segments with keys issued only to licensed players.

Search over titles and descriptions is fed asynchronously from the metadata database into a search index, the same pattern we have used before. When a video becomes ready, an event updates the index. The upload path never waits for search.

Step 11: Counting views

View counts
  1. 01
    Player sends heartbeatsStarted, watched 30 s, progress, ended
  2. 02
    Event streamMillions of events a second into a log
  3. 03
    ValidateDrop bots and repeated refreshes
  4. 04
    AggregatePer video per minute; batch-update counters

View counts look simple and are not. What is a view? Usually something like watched for at least thirty seconds. So the player sends small events: started, reached thirty seconds, progress, ended.

That is millions of events a second, so they go into an event log, not a database. Stream processors consume them.

Validation matters, because view counts are worth money to creators and therefore attract fraud. Drop events from known bots, cap repeated views from the same viewer, and look for unnatural patterns. Then aggregate per video per minute and update the counters in batches. The count on the page is approximate and a little behind, and the authoritative numbers for payments are computed later, more carefully, from the full log. The same events also feed recommendations and creator analytics.

Step 12: Failures and cost

What breaks
  1. 01
    Transcode worker diesTask retried; chunks make retries cheap
  2. 02
    Bad outputAutomated quality checks before publishing
  3. 03
    Edge overloadedPlayers switch edge; DNS steers traffic away
  4. 04
    Viral videoOrigin shield and pre-positioning
  5. 05
    Storage costMove cold videos to cheaper tiers

Let us walk through failures. A transcoding worker dying only loses one chunk's work, which is retried. That is another benefit of chunking: a failure costs seconds, not hours.

A subtle risk is bad output: an encoder bug that produces green frames or silent audio. Run automated checks on renditions, comparing them with the original, before publishing. It is much easier to catch a bad encode before millions of people watch it.

On the playback side, an overloaded or failing edge is handled by players retrying segments from another edge, and by steering new viewers elsewhere. A viral video is handled by the origin shield and by pushing it out to edges proactively once its growth is detected.

And cost, which is a kind of failure if ignored. Most videos are watched heavily in their first weeks and rarely after. Move old renditions to cheaper storage tiers, delete rarely used rungs and regenerate them on demand from the original, and keep the original in the most durable, cheapest archive class. These choices can halve the storage bill without any viewer noticing.

Step 13: The follow-up questions

Max asks

“How would you make a newly uploaded video playable faster?”

Prioritise. Encode a low and a medium rendition first, publish the video as soon as those exist, and add higher qualities as they finish. Because chunks encode in parallel, even a long video can have its first rendition ready in a minute or two. The player only offers the qualities that exist, so viewers never see a broken option.

Max asks

“How would you support live streaming?”

The playback side barely changes: the stream is still segments and a manifest, but the manifest keeps growing as new segments are produced. The upload side changes completely: the broadcaster sends a continuous stream to an ingest server, which transcodes it in real time into the ladder, a few seconds behind live. Latency becomes the key metric, so segments get shorter, and edges are pre-warmed for big events.

Max asks

“What happens when a viewer seeks to the middle of a two-hour video?”

The player looks up which segment contains that time in the manifest, and fetches that segment directly, starting at a lower quality to resume quickly. No other part of the video is downloaded. If that segment is not cached at the edge, the edge fetches it from the shield or the origin. Seeking costs one or two small requests, which is the payoff of storing video as segments.

Max asks

“How would you reduce bandwidth costs by a third?”

Several levers. Use more efficient codecs for devices that support them, which can cut bitrates substantially at the same quality. Tune encoding per video and per scene, rather than one fixed bitrate per rung. Cap the quality to the screen size, so a phone never downloads 4K. Increase the share of traffic served from edges inside internet providers, which is far cheaper than transit. Each is a few percent to tens of percent, and together a third is realistic.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsUpload, process, watch; fast start, smooth, global
  2. 02
    5 to 10: estimatesTerabits a second out; a petabyte a day in
  3. 03
    10 to 15: API and the two pathsNo video bytes through our servers
  4. 04
    15 to 35: deep divesResumable upload, chunked transcoding, ABR segments, CDN
  5. 05
    35 to 45: the restMetadata, signed URLs, view counts, failures, cost

On the clock: five minutes of requirements, ending with fast start, smooth playback and global reach. Five minutes of numbers, which make it obvious that playback must come from a content delivery network.

Five minutes on the API and the two paths, with the key point that our servers never carry video bytes.

Twenty minutes on the deep dives: resumable uploads, transcoding in parallel chunks into a quality ladder, adaptive bitrate streaming with segments and manifests, and the content delivery network with push for hits and pull for the long tail. And the last ten on metadata, signed URLs, view counts, failures and cost. If you keep coming back to where the bytes flow, you will give an answer that sounds like it comes from experience.

There is a lot to cover in this question, and the danger is spending twenty minutes on uploads and never reaching adaptive streaming. Practicing out loud is how you learn the pacing. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson twelve.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.