Case study: design a video streaming service
A senior-level walkthrough of video streaming in the YouTube and Netflix style: resumable uploads, chunked parallel transcoding with backups for stragglers, bitrate ladders and manifests, adaptive players and CDN delivery, with tested C#.
Case studyApplied42 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 2 data models
- 2 API designs
- 8 code samples
- 10 interviewer follow-ups
- 5 self-checks
On this page15 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Caching, DNS, CDNs and the edge
- Egress dominates the cost of video, so the design is a delivery network. Segments are static files, caches sit close to viewers (inside ISPs), and the control plane stays small.
- Upload in checksummed chunks that can be resumed. A whole-file upload on a flaky link sent more than 280 times the file in the simulation, and a resumable one sent 258 chunks for 250.
- Transcode as a graph of small idempotent tasks on keyframe-aligned chunks of 10 to 30 seconds, with backup copies for stragglers. Chunks of 300 seconds without backups took 127 minutes against about 18.
- A player adapts with a ladder, a manifest and a rule on throughput or buffer. In the simulation a buffer-based rule gave 43% more bitrate than a smoothed throughput rule at the same near-zero stall rate.
- Pre-position what is predictable, coalesce what is simultaneous, and prepare the senior answers on new releases, view counts, codecs, cost and live streaming.
8 code samples (346 lines), collapsed so the explanation stays in focus.
Video streaming looks like one feature, play a file, and it is three systems joined end to end. An ingest system takes in large files from unreliable networks. A processing system turns each file into dozens of copies that every phone, television and connection can play. A delivery system moves exabytes a day to viewers who must see the first frame in a second or two and must not stall. The interesting engineering is in the seams: how an upload survives a dropped connection, how a two-hour film is encoded in minutes, and how a player decides every four seconds what to ask for next.
This lesson builds the design in that order and tests the main ideas in C#: a resumable upload session, a chunked transcoding scheduler with stragglers, an HLS playlist reader, and an adaptive bitrate player simulation. Delivery leans on DNS, CDNs and the edge, and the stored objects are the kind of data covered in designing object storage.
Spend the first minutes on questions. Each answer changes the design.
| Ask | Why it matters |
|---|---|
| User-generated uploads (YouTube) or a licensed catalogue (Netflix)? | A catalogue is small and its popularity is predictable, so content can be pushed to caches in advance. User uploads are huge, unpredictable and mostly never watched |
| On demand only, or live as well? | Live removes the time to retry anything. Scope it out, then say how you would extend |
| Which devices and networks? | They decide the ladder of qualities, the codecs and the container formats |
| What counts as good? | Time to first frame, rebuffering ratio and quality, in that order for most users |
| DRM and regions? | Protected content needs licence servers and encrypted segments, and regional rights need geo checks |
| Is search, recommendation or comments in scope? | Usually not. Name them as separate services this design links to |
| Cost? | Egress is the biggest bill, then encoding compute, then storage. Interviewers like candidates who say so |
A good scope for 45 minutes: creators upload, the system processes the video, viewers play it anywhere with adaptive quality, and the system counts views and remembers the playback position. Mention live, DRM and recommendations as extensions.
State assumptions out loud. They are illustrative and the interviewer may change them.
uploads: 500 hours of video a minute (assumed) = 720,000 hours a day
originals: ~1 GB an hour (about 2.2 Mbit/s) = ~720 TB a day
ladder: six renditions, about 2.2x the original in total = ~1.6 PB
stored: ~2.3 PB a day, ~840 PB a year
watching: 1B hours a day (assumed) at an average 2.5 Mbit/s
per hour: 2.5 Mbit/s x 3,600 s / 8 = ~1.1 GB
egress: 1B x 1.1 GB = ~1.1 EB a day = ~13 TB/s on average
peak (x2): ~26 TB/s, about 210 Tbit/s
viewers: 1B hours / 24 h = ~42M watching at any moment
requests: 42M viewers / 4 s per segment = ~10M a second
heartbeats: 42M / 30 s = ~1.4M events a secondFive conclusions:
- Egress dominates. About 1.1 exabytes leave every day against 2.3 petabytes stored, nearly 500 times more bytes out than in. No data centre can serve 26 TB/s, so delivery is a network of caches inside and next to the ISPs, and the origin only sees misses. For video the CDN is the system.
- Storage is large and boring. About 840 PB a year goes into object storage with tiering. The multipliers matter: every extra rendition and every extra codec multiplies it, so the long tail of videos that are watched twice should not be encoded into every format.
- The data plane is static files, and the control plane is small but not free. Ten million segment requests a second are reads of immutable objects that caches absorb. What reaches your own servers is the dynamic traffic: metadata, licences, and a heartbeat every 30 seconds from about 42 million viewers, 1.4 million tiny events a second that belong in a partitioned log and not in a database.
- Uploads are rare and heavy. 500 hours a minute is 8.3 hours of video arriving every second, and each hour needs many machine-hours of encoding. A software encoder at a quarter of real time spends 4 machine-hours per rendition for each hour of video, 24 for a six-rung ladder, which is why large services build or buy hardware encoders.
- The user feels startup time and stalls. A view is judged by how fast the first frame appears, how often playback freezes and how sharp the picture is. The player's adaptation logic and the cache hit ratio decide all three.
| Call | Who calls it | Meaning |
|---|---|---|
POST /v1/uploads | Creator app | Start a resumable upload with the size, the chunk size and the hash algorithm |
PUT /v1/uploads/{id}/chunks/{n} | Creator app | Upload one chunk with its checksum. Repeating it is harmless |
GET /v1/uploads/{id} | Creator app | Which chunks are still missing, used after a dropped connection |
POST /v1/uploads/{id}/complete | Creator app | Verify the whole file and start processing |
GET /v1/videos/{id} | Player | Metadata, the manifest URL and a licence token |
GET /v1/videos/{id}/master.m3u8 | Player, through the CDN | The master playlist: the renditions that exist |
POST /v1/videos/{id}/progress | Player | A heartbeat with the position, for continue-watching and view counts |
- auth
- creator token
- idempotency
- Idempotency-Key header, so a retried create returns the same session
- body
- { "size": 2147483648, "chunk_size": 8388608, "sha256_of_chunks": true, "title": "Trip to the coast" }
- note
- the chunks go straight to object storage through the presigned URLs, so the API servers never carry the bytes
- 201created, returns { "upload_id": "u_5c1", "chunk_count": 256, "urls": "presigned, one per chunk, valid for 24 hours" }
- 400a size above the limit, or a chunk size outside the allowed range
- auth
- the presigned URL carries it
- body
- the chunk bytes, with the SHA-256 in a header
- note
- a client that reconnects asks GET /v1/uploads/{id} for the missing chunks and sends only those
- 200stored, or already stored with the same checksum
- 409a different chunk is already stored for this index
- 422the length or the checksum does not match
idbigint
PKSHARD KEYowner_idbigint
INDEXstatetext
uploading, processing, published, failed or removed
originaltext
object key of the uploaded file
duration_sdouble
known after the probe step
NULLtitletext
visibilitytext
public, unlisted or private
created_attimestamptz
published_attimestamptz
NULL
Views, likes and watch positions are NOT columns here. They are counters and per-user state in their own stores.
video_idbigint
PKSHARD KEYnametext
for example h264-720p or av1-1080p
PKcodectext
bitrate_kbpsint
widthint
heightint
playlisttext
object key of the media playlist, written last
NULLstatetext
pending, ready or failed
A rendition becomes visible to players only when its playlist exists and every segment it lists is in place.
Read it as three pipelines that touch only at the storage layer. The ingest path ends when the original is safe in object storage and the orchestrator has been told. The processing path turns that original into segments and playlists and records the state, and nothing in it is visible to viewers until a rendition is complete. The playback path is almost entirely static files: the player asks the Playback API once for metadata, a licence and a manifest URL, then fetches playlists and segments from the nearest cache and adapts as it goes. Because the three paths share only immutable objects and a small metadata store, each scales and fails on its own.
A creator on a phone uploads 2 GB over a connection that moves between Wi-Fi and mobile data, passes through a tunnel and is put in the background by the operating system. One HTTP request for the whole file will not survive that. The design is a resumable, chunked upload: the client splits the file, hashes each chunk, sends chunks independently (a few in parallel), and after any failure asks the server what it already has and sends only the rest. The open tus protocol, Google's resumable uploads and S3 multipart upload (up to 10,000 parts) are variants of the same idea.
The session below knows the file's size and the chunk size. Put accepts a chunk only if its index, length and SHA-256 are right, and putting the same chunk again changes nothing, which makes a retry after a lost reply safe (the idempotency idea from API design). Missing is the call a client makes after reconnecting. Complete checks that nothing is missing and that the hash of all the chunk hashes matches the client's, a cheap whole-file integrity check, much as S3 derives a multipart ETag from the part hashes.
C# · The server side of a resumable upload: a session that knows the file's size and chunk…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
// The server side of a resumable upload: a session that knows the file's size and chunk size, stores each chunk once after
// checking its length and checksum, and can say which chunks are still missing.
public sealed class UploadSession
{
private readonly long _size;
private readonly int _chunkSize;
private readonly Dictionary<int, string> _stored = new(); // chunk index -> checksum of the chunk that was stored
public UploadSession(long size, int chunkSize) { _size = size; _chunkSize = chunkSize; }
public int ChunkCount => (int)((_size + _chunkSize - 1) / _chunkSize);
// A chunk is accepted only if its length and its SHA-256 are right. Sending the same chunk again is harmless, which makes a
// retry after a lost reply safe. A different payload for an index that is already stored is refused.
public bool Put(int index, byte[] data, string sha256)
{
if (index < 0 || index >= ChunkCount) return false;
long expected = index == ChunkCount - 1 ? _size - (long)index * _chunkSize : _chunkSize;
if (data.Length != expected) return false;
string actual = Convert.ToHexString(SHA256.HashData(data));
if (!string.Equals(actual, sha256, StringComparison.OrdinalIgnoreCase)) return false;
if (_stored.TryGetValue(index, out var existing)) return existing == actual;
_stored[index] = actual;
return true;
}
// What a client asks for after a dropped connection: the chunks that are still needed.
public List<int> Missing() => Enumerable.Range(0, ChunkCount).Where(i => !_stored.ContainsKey(i)).ToList();
// The upload is complete when no chunk is missing and the hash of all the chunk hashes matches what the client computed.
public bool Complete(string hashOfHashes)
{
if (Missing().Count > 0) return false;
var all = string.Concat(Enumerable.Range(0, ChunkCount).Select(i => _stored[i]));
return Convert.ToHexString(SHA256.HashData(Encoding.ASCII.GetBytes(all))) == hashOfHashes;
}
}C# · A 2 MB file in 64 KB chunks: 32 chunks of real bytes, pushed through a connection that…
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
// A 2 MB file in 64 KB chunks: 32 chunks of real bytes, pushed through a connection that drops now and then.
var fileRandom = new Random(2);
var file = new byte[2 * 1024 * 1024];
fileRandom.NextBytes(file);
const int UploadChunk = 64 * 1024;
var session = new UploadSession(file.Length, UploadChunk);
byte[] Chunk(int i) => file.Skip(i * UploadChunk).Take(UploadChunk).ToArray();
string Hash(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes));
// The first connection dies after 10 chunks, and a lost reply makes the client send chunk 9 twice.
for (int i = 0; i < 10; i++) Debug.Assert(session.Put(i, Chunk(i), Hash(Chunk(i))));
Debug.Assert(session.Put(9, Chunk(9), Hash(Chunk(9)))); // the retry is accepted and changes nothing
Debug.Assert(session.Missing().Count == 22);
// A flipped bit is caught by the checksum, and so is a chunk of the wrong length.
var damaged = Chunk(10); damaged[100] ^= 1;
Debug.Assert(!session.Put(10, damaged, Hash(Chunk(10))));
Debug.Assert(!session.Put(10, Chunk(10).Take(1000).ToArray(), Hash(Chunk(10).Take(1000).ToArray())));
// After reconnecting, the client asks what is missing and sends only that.
foreach (int i in session.Missing()) Debug.Assert(session.Put(i, Chunk(i), Hash(Chunk(i))));
string hashOfHashes = Convert.ToHexString(SHA256.HashData(Encoding.ASCII.GetBytes(string.Concat(Enumerable.Range(0, 32).Select(i => Hash(Chunk(i)))))));
Debug.Assert(session.Missing().Count == 0 && session.Complete(hashOfHashes) && !session.Complete("00"));
Console.WriteLine($"resumed: {session.ChunkCount} chunks stored, upload complete");
// The cost of not resuming: a 2 GB file in 8 MB chunks is 250 chunks, and every chunk transfer fails with probability 3%.
var link = new Random(12);
bool Fails() => link.NextDouble() < 0.03;
double wholeSends = 0, resumableSends = 0;
const int UploadTrials = 1_000, UploadChunks = 250;
for (int trial = 0; trial < UploadTrials; trial++)
{
while (true) // one request for the whole file: any failure starts over
{
bool completed = true;
for (int c = 0; c < UploadChunks && completed; c++) { wholeSends++; if (Fails()) completed = false; }
if (completed) break;
}
for (int c = 0; c < UploadChunks; c++) { do resumableSends++; while (Fails()); } // resumable: only the failed chunk is sent again
}
Console.WriteLine($"chunk sends for a {UploadChunks}-chunk file: whole-file {wholeSends / UploadTrials:F0} on average, resumable {resumableSends / UploadTrials:F0}");
Debug.Assert(resumableSends / UploadTrials is > 245 and < 275);
Debug.Assert(wholeSends / UploadTrials > 50 * UploadChunks);The first half of the sample pushes 32 chunks of real bytes through a connection that dies after 10, sends chunk 9 twice because a reply was lost, flips a bit and truncates a chunk to see both rejected, then resumes with only the missing chunks and completes. The second half shows why it matters. A 2 GB file in 8 MB chunks is 250 chunks, and each chunk transfer fails with probability 3%. A single request for the whole file succeeds only if all 250 transfers succeed in a row, which has a probability of 0.97 to the power 250, about 0.05%. The expected number of chunk sends is (q^-N - 1) / p with q = 0.97, N = 250 and p = 0.03, about 67,600, and the simulation averaged 71,313 over 1,000 uploads, against 258 for the resumable upload (the formula N / q gives 257.7). Not resuming costs more than 280 times the file.
How it works in a real service:
- The bytes bypass your servers. The API creates the session and hands out presigned URLs, and the client sends chunks straight to object storage. The API only records state and verifies the result, so no application server carries 2 GB.
- Chunk size is a dial. Larger chunks mean fewer requests and more to repeat after a failure. Commonly they are 5 to 16 MB, smaller on a poor network, with three to six in flight at once.
- Hash on the client. It lets the server verify each chunk, and it allows a server to skip a file it already has (a content-hash lookup before the upload starts). Be careful with that shortcut, because "this hash already exists" also tells an attacker the file is on the service.
- Abandoned sessions cost storage. Expire them. Object stores offer a lifecycle rule that aborts incomplete multipart uploads after a number of days.
- Complete is the commit point. Only then does the video row move from
uploadingtoprocessing, and the event for the orchestrator is written in the same transaction (a transactional outbox, see queues and async work).
The original file is rarely what a viewer should receive. Phones, televisions and browsers support different codecs, networks differ by a factor of a hundred, and one bitrate cannot suit all. So each video is encoded into a ladder of renditions (a codec, a resolution and a bitrate each), and the player chooses among them. A fixed ladder is simple. A per-title ladder, which Netflix described in 2015, tailors the rungs to how hard the content is to compress: a cartoon needs far fewer bits for the same quality than a football match.
Processing is a graph of stages, and almost every stage can run in parallel:
- Probe and validate. Read the streams, the duration and the codecs, and reject corrupt, hostile or unsupported files early. Content-safety and copyright checks run here or in parallel.
- Split at keyframes into chunks of 10 to 30 seconds. A chunk boundary must be a keyframe, so that each chunk can be decoded alone.
- Encode each chunk for each rendition. This is the bulk of the compute and the tasks are independent.
- Everything else in parallel: audio renditions, captions (speech to text), thumbnails and the preview sprites used when scrubbing.
- Package the encoded chunks into segments of two to six seconds and write the playlists (HLS) or the manifest (DASH).
- Quality gate. Check for black frames, audio and video sync, bitrate conformance, and a perceptual quality score (Netflix's open VMAF is the usual one).
- Publish. Make the playlists visible and record the state.
How long should a chunk be? The simulation below encodes a two-hour film in 6 renditions on 200 machines. Encoding runs at a quarter of real time (a chunk takes four times its length), every task also pays 3 seconds to fetch its input and start, and each attempt has a 2% chance of landing on a slow machine that runs it six times slower. It compares plain scheduling with backups: once every task has started, a free machine takes a second copy of any task that has run longer than 1.5 times its nominal time, and the first copy to finish wins. This is the "backup tasks" idea from MapReduce and the hedging idea from The Tail at Scale.
C# · EncodeRun, Transcoding
using System;
using System.Collections.Generic;
using System.Linq;
public sealed record EncodeRun(double Makespan, double MachineSeconds, int Backups);
public static class Transcoding
{
// Event-driven scheduling of independent encode tasks on identical machines. Each attempt has a 2% chance of landing on a
// slow machine (6 times slower). With backups on, once every task has started, a free machine takes a second copy of any
// task that has run longer than `threshold` times its nominal time, and the first copy to finish wins.
public static EncodeRun Run(double[] work, int machines, Random random, bool backups, double threshold = 1.5)
{
int n = work.Length, free = machines, next = 0, finished = 0, attempts = 0, copies = 0;
double now = 0, busy = 0;
var done = new bool[n];
var running = new Dictionary<int, double>[n]; // per task: attempt id -> start time
var events = new PriorityQueue<(bool Finish, int Task, int Attempt), double>();
var cancelled = new HashSet<int>();
void Start(int task)
{
int attempt = attempts++;
(running[task] ??= new Dictionary<int, double>())[attempt] = now;
events.Enqueue((true, task, attempt), now + work[task] * (random.NextDouble() < 0.02 ? 6 : 1));
if (backups) events.Enqueue((false, task, attempt), now + threshold * work[task]); // a moment to check on this attempt
free--;
}
while (finished < n)
{
while (free > 0 && next < n) Start(next++);
if (backups && next == n)
for (int t = 0; t < n && free > 0; t++)
if (!done[t] && running[t].Count == 1 && now - running[t].Values.Single() >= threshold * work[t]) { Start(t); copies++; }
events.TryDequeue(out var e, out double time);
now = time;
if (!e.Finish || done[e.Task] || cancelled.Contains(e.Attempt)) continue;
done[e.Task] = true;
finished++;
foreach (var (attempt, started) in running[e.Task]) // the winner and any copy still running free their machines
{
busy += now - started;
free++;
if (attempt != e.Attempt) cancelled.Add(attempt);
}
running[e.Task].Clear();
}
return new EncodeRun(now, busy, copies);
}
}C# · A 2-hour film in 6 renditions. Encoding runs at a quarter of real time (a chunk takes 4…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// A 2-hour film in 6 renditions. Encoding runs at a quarter of real time (a chunk takes 4 times its length), every task also pays
// 3 s to fetch its chunk and start, and 200 machines share the work. How long should a chunk be?
var encodeRandom = new Random(8);
var finishPlain = new Dictionary<int, double>();
var finishBacked = new Dictionary<int, double>();
foreach (int chunk in new[] { 2, 10, 30, 60, 300 })
{
int tasks = 7_200 / chunk * 6;
var work = Enumerable.Range(0, tasks).Select(_ => (chunk * 4 + 3) * (0.9 + 0.2 * encodeRandom.NextDouble())).ToArray();
var plain = Transcoding.Run(work, 200, new Random(1), backups: false);
var backed = Transcoding.Run(work, 200, new Random(1), backups: true);
finishPlain[chunk] = plain.Makespan;
finishBacked[chunk] = backed.Makespan;
Console.WriteLine($"{chunk,3} s chunks: {tasks,6} tasks, ideal {work.Sum() / 200 / 60:F1} min, finished in {plain.Makespan / 60:F1} min, with backups {backed.Makespan / 60:F1} min ({backed.Backups} backups, machine time {backed.MachineSeconds / plain.MachineSeconds - 1:+0.0%;-0.0%})");
}
int best = finishBacked.OrderBy(f => f.Value).First().Key;
Debug.Assert(best is 10 or 30); // neither tiny nor huge chunks win
Debug.Assert(finishBacked[2] > finishBacked[best] && finishBacked[300] > 2 * finishBacked[best]);
Debug.Assert(finishPlain[300] > 5 * finishBacked[best]); // huge chunks without backups are far worse
Debug.Assert(new[] { 10, 30, 60, 300 }.All(c => finishBacked[c] < finishPlain[c])); // backups help once tasks are long enough to straggle| Chunk length | Tasks | Ideal | Plain scheduling | With backups |
|---|---|---|---|---|
| 2 s | 21,600 | 19.8 min | 22.8 min | 22.8 min |
| 10 s | 4,320 | 15.5 min | 20.8 min | 18.3 min |
| 30 s | 1,440 | 14.7 min | 24.6 min | 17.6 min |
| 60 s | 720 | 14.6 min | 36.5 min | 22.2 min |
| 300 s | 144 | 14.5 min | 127.4 min | 53.1 min |
"Ideal" is the total work divided by 200 machines. Read the table from both ends:
- Tiny chunks drown in overhead. With 2-second chunks the fixed 3 seconds per task makes the total work larger (19.8 minutes ideal against 14.5), and 21,600 tasks need a lot of bookkeeping and produce many small files.
- Huge chunks starve the cluster and amplify stragglers. With 300-second chunks there are only 144 tasks for 200 machines, so 56 sit idle, and one slow attempt (a 1,200-second task that runs six times slower takes two hours) decides the finish: 127 minutes.
- Backups cut the tail. At 300 seconds they brought 127 minutes down to 53, at 60 seconds 36.5 to 22.2, and at 10 seconds 20.8 to 18.3. They did not cost extra machine time here, which came out 0.1% to 4.7% lower, because the copy that loses is cancelled and the slow attempt would otherwise have run to its end.
- The best chunk was 10 to 30 seconds (18.3 and 17.6 minutes with backups), within a few minutes of the ideal.
Rules that make a graph like this reliable:
- Tasks are idempotent. The same input and encoder version produce the same output key, so a retry or a backup that finishes second writes identical bytes over the same object.
- Commit by writing the playlist last. A rendition exists for players only when its playlist is present, and every segment it lists was written first. A half-finished rendition is invisible.
- Publish in stages. When the lowest rungs are ready the video can play at low quality, and higher rungs appear as they finish.
- Prioritize and isolate. A new upload from a large channel goes before a back-catalogue re-encode, backfill runs on preemptible machines, and quotas keep one customer from filling the queue.
- Quarantine poison inputs. A file that crashes the encoder gets a retry limit, then a quarantine and an alert, instead of blocking the queue.
- Choose codecs by expected value. Newer codecs need substantially fewer bits for the same quality at several times the encoding cost, so they pay off only for videos that will be watched many times. Encode everything in a universally supported codec first, and re-encode the videos that become popular.
- Specialized hardware. At this volume software encoding is expensive. Google described custom video-coding silicon for YouTube in a 2021 paper, and cloud providers sell hardware encoders.
Streaming over HTTP works because a video is cut into segments, each a small file of two to six seconds, and described by a playlist that lists them. HLS (HTTP Live Streaming, RFC 8216) uses text playlists, and MPEG-DASH uses an XML manifest. Both can point at the same fragmented MP4 segments (the CMAF format), so one set of media files can serve every device. A master playlist lists the renditions, and a media playlist for each rendition lists its segments. Every segment starts with a keyframe, so that the player can switch rendition at any boundary.
The reader below parses a master playlist, picks a rendition for a measured bandwidth with a safety margin, and finds the segment that holds a seek position. The last part is worth noticing: seeking is arithmetic on a static file. Add up the #EXTINF durations until the position falls inside a segment, and fetch that segment. No server has to do anything.
C# · Rendition, Hls
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public sealed record Rendition(int Bandwidth, int Width, int Height, string Uri);
public static class Hls
{
// A master playlist lists the renditions: each #EXT-X-STREAM-INF line describes the playlist named on the line after it.
public static List<Rendition> ParseMaster(string text)
{
var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var renditions = new List<Rendition>();
for (int i = 0; i + 1 < lines.Length; i++)
{
if (!lines[i].StartsWith("#EXT-X-STREAM-INF:")) continue;
var attributes = lines[i]["#EXT-X-STREAM-INF:".Length..].Split(',').Select(a => a.Split('=', 2)).Where(a => a.Length == 2).ToDictionary(a => a[0], a => a[1]);
var size = attributes["RESOLUTION"].Split('x');
renditions.Add(new Rendition(int.Parse(attributes["BANDWIDTH"]), int.Parse(size[0]), int.Parse(size[1]), lines[i + 1]));
}
return renditions.OrderBy(r => r.Bandwidth).ToList();
}
// The best rendition whose declared bandwidth fits inside a safety margin of the measured throughput.
public static Rendition Pick(List<Rendition> renditions, double measuredBitsPerSecond) =>
renditions.LastOrDefault(r => r.Bandwidth <= 0.8 * measuredBitsPerSecond) ?? renditions[0];
// Seeking is arithmetic on a static file: add up the #EXTINF durations until the position falls inside a segment.
public static (int Index, double Offset) SegmentAt(string mediaPlaylist, double seconds)
{
var durations = mediaPlaylist.Split('\n').Select(l => l.Trim()).Where(l => l.StartsWith("#EXTINF:"))
.Select(l => double.Parse(l["#EXTINF:".Length..].TrimEnd(','), CultureInfo.InvariantCulture)).ToList();
double start = 0;
for (int i = 0; i < durations.Count; i++)
{
if (seconds < start + durations[i]) return (i, seconds - start);
start += durations[i];
}
return (durations.Count - 1, durations[^1]);
}
}C#
using System;
using System.Diagnostics;
string master = """
#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=6000000,RESOLUTION=1920x1080
1080p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360
360p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=2400000,RESOLUTION=1280x720
720p/index.m3u8
""";
var ladder = Hls.ParseMaster(master);
Debug.Assert(ladder.Count == 3 && ladder[0].Height == 360 && ladder[2].Uri == "1080p/index.m3u8");
Debug.Assert(Hls.Pick(ladder, 3_500_000).Height == 720); // 2.4 Mbit/s fits inside 80% of 3.5 Mbit/s, 6 Mbit/s does not
Debug.Assert(Hls.Pick(ladder, 500_000).Height == 360); // nothing fits: take the lowest
string media = """
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:4
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:4.000,
seg0.ts
#EXTINF:4.000,
seg1.ts
#EXTINF:3.200,
seg2.ts
#EXT-X-ENDLIST
""";
var (segmentIndex, segmentOffset) = Hls.SegmentAt(media, 9.0);
Console.WriteLine($"position 9.0 s is in segment {segmentIndex}, {segmentOffset:F1} s into it");
Debug.Assert(segmentIndex == 2 && Math.Abs(segmentOffset - 1.0) < 1e-9);
Debug.Assert(Hls.SegmentAt(media, 0).Index == 0 && Hls.SegmentAt(media, 4.0).Index == 1);The player's loop is a decision at every segment boundary: which rendition should the next four seconds come from? The inputs are the throughput of recent downloads and the buffer level (how many seconds of video are downloaded and not yet played). Two families of rule exist. A throughput rule estimates the bandwidth and asks for the highest rendition that fits inside a safety margin, the Pick function above. A buffer-based rule ignores the estimate and maps the buffer level to a rendition: lowest while the buffer is small, highest when it is large, a ramp in between (the approach of the 2014 SIGCOMM paper from a large streaming service). Hybrids such as MPC and BOLA combine the two. The simulation compares them on 200 random networks, each about 3 Mbit/s on average with occasional deep dips, each streaming a 10-minute video of 150 four-second segments.
C# · Playback, Abr
using System;
using System.Linq;
public sealed record Playback(double MeanKbps, double StallRatio, int Stalls, double SwitchesPerMinute, double StartupSeconds);
public static class Abr
{
public static readonly int[] Ladder = { 300, 750, 1_200, 2_400, 4_800, 8_000 }; // kbps, one entry per rendition
public const double SegmentSeconds = 4, MaxBuffer = 30, PlayAt = 4;
// Available bandwidth for each second: a mean-reverting random walk (about 3 Mbit/s) with a deep dip now and then.
public static double[] Trace(Random random, int seconds)
{
var trace = new double[seconds];
double x = Math.Log(3_000);
int dipLeft = 0;
for (int s = 0; s < seconds; s++)
{
x += 0.03 * (Math.Log(3_000) - x) + 0.15 * Gauss(random);
if (dipLeft == 0 && random.NextDouble() < 1 / 90.0) dipLeft = 5 + random.Next(11);
double dip = dipLeft > 0 ? 0.15 : 1;
if (dipLeft > 0) dipLeft--;
trace[s] = Math.Exp(x) * dip;
}
return trace;
}
private static double Gauss(Random random) => Math.Sqrt(-2 * Math.Log(1 - random.NextDouble())) * Math.Cos(2 * Math.PI * random.NextDouble());
// A policy sees the buffer, the throughput of the last download and the current rendition, and returns the next rendition.
public delegate int Policy(double bufferSeconds, double lastKbps, int current);
public static int Highest(double kbps) { int best = 0; for (int i = 0; i < Ladder.Length; i++) if (Ladder[i] <= kbps) best = i; return best; }
public static Playback Play(double[] trace, Policy choose, int segments = 150)
{
double time = 0, buffer = 0, stall = 0, started = -1, kbps = Ladder[0], bitSum = 0;
int stalls = 0, switches = 0, current = 0;
bool playing = false;
for (int i = 0; i < segments; i++)
{
if (playing && buffer > MaxBuffer - SegmentSeconds) { double wait = buffer - (MaxBuffer - SegmentSeconds); time += wait; buffer -= wait; }
int next = choose(buffer, kbps, current);
if (i > 0 && next != current) switches++;
current = next;
double remaining = Ladder[current] * SegmentSeconds, t = time; // kilobits still to download
while (remaining > 0)
{
int sec = (int)Math.Floor(t);
double bandwidth = trace[Math.Min(sec, trace.Length - 1)];
double untilNextSecond = sec >= trace.Length ? double.MaxValue : sec + 1 - t; // past the trace, the last second repeats
if (bandwidth * untilNextSecond >= remaining) { t += remaining / bandwidth; remaining = 0; }
else { remaining -= bandwidth * untilNextSecond; t = sec + 1; }
}
double took = t - time;
if (playing)
{
buffer -= took;
if (buffer < 0) { stall += -buffer; stalls++; buffer = 0; playing = false; }
}
else if (started >= 0) stall += took; // playback had started, so this wait is a stall
buffer += SegmentSeconds;
kbps = Ladder[current] * SegmentSeconds / took;
bitSum += Ladder[current];
time = t;
if (!playing && buffer >= PlayAt) { playing = true; if (started < 0) started = time; }
}
double watched = segments * SegmentSeconds;
return new Playback(bitSum / segments, stall / (watched + stall), stalls, switches / (watched / 60), started);
}
}C# · 200 random networks (about 3 Mbit/s on average, with dips), each streaming a 10-minute…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// 200 random networks (about 3 Mbit/s on average, with dips), each streaming a 10-minute video of 150 segments of 4 seconds.
double smoothed = 0; // the smoothed throughput estimate used by one of the policies
var policies = new (string Name, Abr.Policy Choose)[]
{
("fixed lowest (300 kbps)", (buffer, last, current) => 0),
("fixed highest (8,000 kbps)", (buffer, last, current) => Abr.Ladder.Length - 1),
("throughput, last segment", (buffer, last, current) => Abr.Highest(0.8 * last)),
("throughput, smoothed", (buffer, last, current) => { smoothed = smoothed == 0 ? last : 0.7 * smoothed + 0.3 * last; return Abr.Highest(0.8 * smoothed); }),
("buffer-based, reservoir 8 s", (buffer, last, current) => buffer < 8 ? 0 : buffer >= 24 ? Abr.Ladder.Length - 1 : Abr.Highest(Abr.Ladder[0] + (Abr.Ladder[^1] - Abr.Ladder[0]) * (buffer - 8) / 16)),
("buffer-based, reservoir 14 s", (buffer, last, current) => buffer < 14 ? 0 : buffer >= 28 ? Abr.Ladder.Length - 1 : Abr.Highest(Abr.Ladder[0] + (Abr.Ladder[^1] - Abr.Ladder[0]) * (buffer - 14) / 14)),
};
var traceRandom = new Random(4);
var traces = Enumerable.Range(0, 200).Select(_ => Abr.Trace(traceRandom, 3_000)).ToArray();
var averages = new Dictionary<string, (double Kbps, double Stall, double Stalls, double Switches, double Start)>();
foreach (var (name, choose) in policies)
{
var runs = traces.Select(t => { smoothed = 0; return Abr.Play(t, choose); }).ToList();
averages[name] = (runs.Average(r => r.MeanKbps), runs.Average(r => r.StallRatio), runs.Average(r => r.Stalls), runs.Average(r => r.SwitchesPerMinute), runs.Average(r => r.StartupSeconds));
var a = averages[name];
Console.WriteLine($"{name,-29} mean {a.Kbps,5:F0} kbps, stalled {a.Stall:P1} of the time, {a.Stalls:F1} stalls, {a.Switches:F1} switches a minute, start {a.Start:F1} s");
}
Debug.Assert(averages["fixed lowest (300 kbps)"].Stall == 0 && Math.Abs(averages["fixed lowest (300 kbps)"].Kbps - 300) < 1e-9);
Debug.Assert(averages["fixed highest (8,000 kbps)"].Stall > 0.3 && averages["fixed highest (8,000 kbps)"].Start > 5);
Debug.Assert(averages["buffer-based, reservoir 14 s"].Kbps > 1.3 * averages["throughput, smoothed"].Kbps && averages["buffer-based, reservoir 14 s"].Stall < 0.01);
Debug.Assert(averages["throughput, smoothed"].Switches < averages["throughput, last segment"].Switches);
Debug.Assert(averages["buffer-based, reservoir 8 s"].Kbps > averages["buffer-based, reservoir 14 s"].Kbps && averages["buffer-based, reservoir 8 s"].Stalls > averages["buffer-based, reservoir 14 s"].Stalls);| Policy | Mean bitrate | Time stalled | Stalls per view | Switches a minute | Start |
|---|---|---|---|---|---|
| Fixed lowest (300 kbps) | 300 kbps | 0.0% | 0.0 | 0.0 | 0.4 s |
| Fixed highest (8,000 kbps) | 8,000 kbps | 57.4% | 118.5 | 0.0 | 12.6 s |
| Throughput rule, last segment | 1,993 kbps | 0.1% | 0.1 | 5.2 | 0.4 s |
| Throughput rule, smoothed | 2,001 kbps | 0.1% | 0.3 | 2.3 | 0.4 s |
| Buffer-based, reservoir 8 s | 3,165 kbps | 0.5% | 1.3 | 6.2 | 0.4 s |
| Buffer-based, reservoir 14 s | 2,868 kbps | 0.0% | 0.1 | 5.8 | 0.4 s |
These are synthetic networks, so read the mechanisms and not the exact numbers:
- Fixed policies fail in opposite directions. The lowest rung never stalls and wastes the network: every viewer sees 300 kbps on a 3 Mbit/s connection. The highest rung stalls 57.4% of the time and takes 12.6 seconds to start, because the first segment alone is 32 megabits. Real players start low and climb.
- The throughput rule is safe and conservative. It believes the last download, which is often taken in a dip, and keeps a 20% margin, so it averages about 2 Mbit/s on 3 Mbit/s networks. Smoothing the estimate halved the switching (5.2 to 2.3 a minute), which matters because frequent switches are visible to viewers.
- The buffer-based rule uses the buffer as the signal. The buffer is the integral of everything that happened on the network, so it needs no estimate. With a 14-second reservoir it delivered 2,868 kbps, 43% more than the smoothed throughput rule, with the same near-zero stalls. A smaller reservoir (8 seconds) took more quality, 3,165 kbps, and paid in stalls (1.3 a view). The reservoir is the dial between quality and safety.
- Real players add more: hysteresis against switching, a cap on rendition by screen size, a rule that starts by throughput and moves to the buffer once it has built up, and a different policy for live, where the buffer must stay small.
Segments are immutable files with versioned URLs, so a cache can keep them for as long as it likes (the Cache-Control and versioned-URL rules from the CDN lesson apply directly). Four ideas shape the delivery network:
- Popularity is skewed. A small head of videos draws most views and a long tail draws few. Cache the head at the edge and send tail requests to a mid-tier cache and then the origin. Most viewers do not finish a video, so within a video only the early segments are hot, and caching by segment (each its own object) keeps the hit ratio high.
- Put caches inside the networks that viewers use. Large services place cache servers in internet providers' networks and at exchange points (Netflix's Open Connect appliances and Google Global Cache are the public examples). Bytes then never cross the provider's transit links, which is cheaper for both sides and removes a bottleneck.
- Fill predictably or on demand. A catalogue service knows what will be popular and pushes titles to caches in the quiet hours. A user-upload service cannot, so caches fill on first request, with request coalescing so that a thousand simultaneous first requests for one segment cause one fetch from the layer above. Hashing a video to one cache in a cluster stores each segment once and enlarges the effective cache.
- Steer clients to a healthy cache. The Playback API or DNS picks one by proximity, load and health, the manifest can list more than one host, and the player drops to a lower rendition when a host slows instead of stalling.
A new release is the stress test. Millions of viewers start in the same minute on caches that are still cold, and each asks for the first segments. The defences are the ones above and a few more: pre-position the opening minutes in every region before the release, coalesce requests at every layer, protect the origin with a rate-limited fill, and add jitter to client retries so a failure does not become a synchronized second wave.
- Heartbeats and continue-watching. The player sends a heartbeat with its position every 30 seconds or so. Events go to a partitioned log. "Continue watching" is the latest position for each user and video in a key-value store, overwritten in place with a time to live.
- View counts. Count a view only after a threshold (30 seconds watched, say), deduplicate by session, filter bots, and aggregate in a stream processor into counters per video per minute. Show approximate counts quickly and settle them later. A viral video must never be one hot row that every event updates: shard the counter, or aggregate in memory first and write the totals (see probabilistic data structures for approximate heavy-hitter counting).
- Live streaming removes all slack. The pipeline is ingest (RTMP, SRT or WebRTC), a real-time transcode, segments of about 2 seconds (or sub-segment parts in low-latency HLS), and a playlist that slides forward. A late chunk is a visible glitch, so there is no time to retry. Every viewer requests the newest segment at the same moment, so edges must coalesce requests. Latency is a trade: a smaller buffer means less delay and more stalls, and a few seconds of delay is typical for low-latency HLS and DASH, with WebRTC for under a second at a higher cost per viewer.
| Case | What goes wrong | Handle it |
|---|---|---|
| The upload connection drops | The creator starts over, or the file is damaged | Resumable chunks with checksums, a missing-chunks call, a hash of hashes at the end |
| An abandoned upload | Orphaned chunks fill storage | Expire sessions, and abort incomplete multipart uploads by lifecycle rule |
| An encoder crashes or one machine is slow | The video is late for hours | Idempotent tasks, retries, backup copies for stragglers, chunks of 10 to 30 seconds |
| A poison file | It crashes every worker that touches it and blocks the queue | A retry limit, a quarantine and an alert |
| A half-processed video | Some renditions exist and others do not | Write the playlist last, publish by rung, gate on the quality check |
| A bad rendition (green frames, wrong audio sync) | Viewers see it on every replay | Automated quality checks, and the ability to re-point a playlist to the previous version through versioned paths |
| A new release on cold caches | A thundering herd hits the origin | Pre-position, request coalescing, a shield tier, rate-limited fills, retry jitter |
| A cache server or provider box fails | Viewers on it stall | Steering away from unhealthy caches, several hosts in the manifest, the player drops quality instead of stalling |
| The origin region fails | Misses fail | Replicated segment storage (see multi-region design) and caches that serve stale content while the origin is down |
| Takedowns and copyright | Illegal content stays cached | Fingerprint checks before publish, versioned URLs, purge by path on takedown |
| A DRM licence service outage | Protected videos will not start | A separate failure domain, cached licences with expiry, and licences issued ahead of time for offline use |
| Hot-linking and scraping | Someone else's site streams from your CDN | Signed, expiring URLs checked at the edge (with the token out of the cache key) and rate limits (see rate limiting) |
Interviewer follow-upL5Why transcode a video into many renditions, and how do you choose them?How to answer
Devices support different codecs and networks differ by a factor of a hundred, so the player needs a ladder to choose from. Choose rungs by the screens you serve and the bitrates your viewers can sustain, usually from a few hundred kbps to several Mbit/s. A fixed ladder is simple, and a per-title ladder spends bits where the content needs them: cartoons compress far better than sport. Fewer rungs cost less to store and encode, and more rungs let the player match the network more closely.
Interviewer follow-upL5How does adaptive bitrate streaming work?How to answer
The video is cut into short segments in several renditions, and a playlist lists them. The player downloads a segment, measures the throughput and watches its buffer, and picks the rendition for the next segment. Throughput rules estimate the bandwidth, buffer-based rules map the buffer level to a rendition, and hybrids combine them. In the simulation the fixed rungs failed in opposite directions, and a buffer-based rule delivered 43% more bitrate than a smoothed throughput rule at near-zero stalls.
Interviewer follow-upL5How do you upload a 10 GB file from a phone?How to answer
A resumable, chunked upload: split the file, hash each chunk, send chunks straight to object storage through presigned URLs with a few in flight, and after any failure ask which chunks are missing and send only those. Each chunk is idempotent and verified by its checksum, and a hash of hashes checks the whole file at the end. Without resuming, a 250-chunk upload at 3% chunk failures sent more than 280 times the file in the simulation.
Interviewer follow-upL6How do you make transcoding fast and reliable?How to answer
Split at keyframes into chunks of 10 to 30 seconds and encode every chunk of every rendition as an independent, idempotent task. Chunks that are too short drown in overhead and ones that are too long starve the cluster and amplify stragglers: 300-second chunks took 127 minutes in the simulation against about 18 for 10 to 30 seconds with backups. Run backup copies of slow tasks, write playlists last, publish rung by rung, and quarantine inputs that keep crashing workers.
Interviewer follow-upL6How do you reduce the time to first frame?How to answer
Start at a low rendition and climb, use a small first segment and a small initial buffer, and make the first requests cheap: connection reuse, a manifest served from the edge, DNS and TLS set up early, the first segments of popular videos always cached. A fixed 8 Mbit/s start took 12.6 seconds in the simulation, against 0.4 seconds for a start at the lowest rung. Prefetch the next segments while the buffer is low, and not far ahead, which wastes data when the viewer leaves.
Interviewer follow-upL6A blockbuster releases and millions press play in the same minute. What happens?How to answer
Cold caches, a synchronized wave of identical requests and a risk to the origin. Pre-position the opening segments in every region before release, coalesce requests at each layer so a thousand misses become one fetch, put a shield tier in front of the origin, rate-limit fills, and add jitter to retries. If you cannot pre-position (user uploads), you rely on coalescing and the shield. The player's rendition drop keeps a slow edge from becoming a stall.
Interviewer follow-upL6How do you count views without a hot row, and show them quickly?How to answer
Count from heartbeat events, not from page loads: a view qualifies after a threshold, is deduplicated by session and filtered for bots. Events go to a partitioned log, a stream processor aggregates per video per minute, and the totals are written to a counter store, sharded for a viral video or aggregated in memory first. Show an approximate count immediately and reconcile later. Approximate structures such as count-min sketches work for trending lists.
Interviewer follow-upL6How do you choose codecs, and when do you re-encode?How to answer
Encode everything first in a codec every device plays, so that a video is available quickly. Newer codecs need substantially fewer bits at the same quality and cost several times more to encode and may not play on older devices, so spend that compute only on videos whose expected views repay it, and re-encode when a video's popularity crosses a threshold. Weigh licensing and device support too.
Interviewer follow-upL7How would you cut the delivery bill by 30%?How to answer
Egress is the bill, so attack bytes and distance. Raise the cache hit ratio (a shield tier, consistent hashing in a cluster, coalescing), place caches inside providers' networks, move popular videos to a more efficient codec, tune ladders per title so no rung is wasted, cap the default quality on small screens and mobile data, and avoid over-delivery (prefetch limits, stop downloading when the viewer pauses). Measure cost per delivered hour by region and codec before and after.
Interviewer follow-upL7How would you add live streaming?How to answer
Ingest over RTMP, SRT or WebRTC, a real-time transcoder, segments of about 2 seconds or low-latency parts, and a sliding playlist. There is no slack to retry, so the chain is provisioned for the peak with redundancy at ingest. Edges must coalesce requests for the newest segment. The trade is latency against stability: a smaller buffer cuts delay and raises stalls. Use WebRTC only where sub-second latency is worth a higher cost per viewer.
- Clarify: user uploads or a catalogue, on demand or live, devices, what a good experience means, DRM.
- Estimate: bytes in against bytes out (a few petabytes a day stored against about an exabyte a day delivered), and the request and heartbeat rates.
- Say what dominates: egress, so the design is a delivery network and the origin sees misses.
- Draw three pipelines that meet only at storage: ingest, processing, playback.
- Go deep on upload: resumable chunks with checksums, presigned URLs, complete as the commit point.
- Go deep on processing: a graph of idempotent tasks on keyframe-aligned chunks, backups for stragglers, playlist last, staged publish.
- Explain playback: ladder, manifests, segments, and an adaptive rule on throughput or buffer, with startup at a low rung.
- Deliver it: immutable segments, caches inside providers, coalescing, a shield, pre-positioning for predictable releases.
- Close with views, live and failure modes: counters from heartbeats, the new-release stampede, bad renditions, takedowns.
Video streaming is a delivery problem. About 1.1 exabytes a day leave against a few petabytes that arrive, so segments are immutable static files served by caches placed close to, and inside, the networks of viewers, with a small control plane for metadata, licences and heartbeats. Uploads are resumable chunks verified by checksum (258 chunk sends for a 250-chunk file, against more than 71,000 for a whole-file upload on a flaky link). Processing is a graph of idempotent tasks on keyframe-aligned chunks of 10 to 30 seconds with backup copies for stragglers (about 18 minutes for a two-hour film in six renditions on 200 machines, against 127 for 300-second chunks without backups), committed by writing playlists last. Players read a master playlist, fetch segments, seek by arithmetic and adapt with a throughput or buffer rule (a buffer-based rule gave 43% more bitrate at near-zero stalls in the simulation), starting low and climbing. Pre-positioning, request coalescing and a shield tier handle new releases, counters come from heartbeat events, and live streaming trades latency against stability.
Try answering out loud before you reveal each answer.
QuestionWhy is a resumable, chunked upload better than one request for the whole file?Reveal answer
Because the whole-file request succeeds only if every part of it does, and on a flaky link that almost never happens: with 250 chunks and a 3% failure rate per chunk the chance is about 0.05%, and the simulation sent 71,313 chunk sends on average against 258 for the resumable upload. A resumable upload verifies each chunk by checksum, accepts a repeated chunk harmlessly, lets the client ask which chunks are missing, and ends with a hash of hashes. The bytes go straight to object storage through presigned URLs.
QuestionWhat goes wrong with 2-second chunks and with 300-second chunks when transcoding a film in parallel?Reveal answer
Tiny chunks pay the fixed cost of each task again and again: the ideal time grew from 14.5 to 19.8 minutes, and 21,600 tasks are a lot to manage. Huge chunks leave machines idle (144 tasks for 200 machines) and make one slow attempt decide the finish: 127 minutes without backups. Chunks of 10 to 30 seconds finished in about 18 minutes with backups. Backups cut the tail without extra machine time, because the losing copy is cancelled.
QuestionA player has a 3 Mbit/s connection with occasional dips and a six-rung ladder. Compare a throughput rule with a buffer-based rule.Reveal answer
The throughput rule estimates the bandwidth from the last downloads and keeps a margin, so it is safe and conservative (about 2 Mbit/s here, with almost no stalls), and smoothing the estimate reduces switching. The buffer-based rule maps the buffer level to a rendition, so it needs no estimate and uses the buffer as a summary of the network's past: with a 14-second reservoir it delivered 43% more bitrate (2,868 against 2,001 kbps) at the same near-zero stalls. A smaller reservoir gives more quality and more stalls. Both should start at a low rung and climb.
QuestionWhy does a master playlist plus segments make seeking cheap, and where must the work happen instead?Reveal answer
A playlist is a static file that lists each segment's duration, so the segment for a position is found by adding up durations, with no server logic. The work moves to the player (choosing renditions, buffering) and to the caches that serve immutable segments. What stays on the server side is publishing: a rendition becomes visible only when its playlist is written last, after all its segments exist.
QuestionMillions of people press play on a new release at the same moment. What protects the origin?Reveal answer
Pre-positioning the opening segments in caches in every region, request coalescing at each cache layer so that many simultaneous misses cause one fetch, a shield tier in front of the origin, rate-limited cache fills and retry jitter on the client. The player also lowers the rendition rather than stalling when an edge slows down.
- R. Pantos and W. May, RFC 8216: HTTP Live Streaming (opens in a new tab): the playlist tags used above (
EXT-X-STREAM-INF,EXTINF,EXT-X-ENDLIST). - ISO/IEC 23009-1, MPEG-DASH, and the DASH Industry Forum (opens in a new tab) guidelines.
- Netflix Technology Blog, Per-Title Encode Optimization (opens in a new tab) (2015) and Dynamic Optimizer (opens in a new tab) (2018).
- Netflix, Open Connect (opens in a new tab): caches inside provider networks and how they are filled.
- Te-Yuan Huang et al., A Buffer-Based Approach to Rate Adaptation: Evidence from a Large Video Streaming Service, SIGCOMM 2014.
- Kevin Spiteri, Rahul Urgaonkar and Ramesh Sitaraman, BOLA: Near-Optimal Bitrate Adaptation for Online Videos, INFOCOM 2016, and Xiaoqi Yin et al., A Control-Theoretic Approach for Dynamic Adaptive Video Streaming over HTTP, SIGCOMM 2015.
- Jeffrey Dean and Sanjay Ghemawat, MapReduce: Simplified Data Processing on Large Clusters, OSDI 2004 (backup tasks), and Jeffrey Dean and Luiz Barroso, The Tail at Scale, CACM 2013.
- Parthasarathy Ranganathan et al., Warehouse-Scale Video Acceleration: Co-design and Deployment in the Wild, ASPLOS 2021: custom silicon for video transcoding.
- The tus resumable upload protocol (opens in a new tab) and the Amazon S3 multipart upload overview (opens in a new tab).
- Alex Xu, System Design Interview, Volume 1 (2020): the "Design YouTube" chapter.