Courses / System Design Interview / Chapter 26
Module 6 · Design Problems I: Video, Q&A and Location · Chapter 26 of 49
Design a Video Platform like YouTube
Builds on Back-of-the-Envelope Estimates, Content Delivery Networks, Distributed Message Queues, Blob Stores and Sharded Counters. Next up: Design a Q&A Platform like Quora.
Part 1 · Requirements and estimates
What the platform must do
A video platform lets anyone upload a clip and lets millions of people watch it on phones, computers and televisions over networks of very different speeds. The hard parts are the size of the files and the size of the audience.
A functional requirement says what the system does. Here the scope is: a creator uploads a video, the platform prepares it for playback, viewers watch it with a title page and a view count, and the home page suggests more videos. Live streaming, comments, ads and search are left out so that the design stays about video itself.
A non-functional requirement says how well it must do that. Playback matters more than upload, because far more people watch than upload. A video that has been accepted must never be lost. Playback should start in about two seconds and should not stall on a slow connection. The cost of storing and sending bytes must stay in proportion to the number of viewers.
| Question to ask first | Answer we assume |
|---|---|
| Live or recorded video? | Recorded only |
| Longest allowed video? | Ten hours, with files up to a few gigabytes |
| Which devices? | Phones, computers and televisions, with mixed network speeds |
| Which regions? | India first, with viewers in other countries too |
| How fresh must a new video be? | Playable within minutes of the upload finishing |
Asking these before drawing anything is the habit to keep. Each answer changes the design: recorded-only lets us prepare every video ahead of time, and mixed networks mean one copy of each video is not enough.
Storage: what one day of uploads costs
Storage is the first number to estimate. A viewer on a slow phone connection needs a small, low-bitrate copy of the video, and a viewer on a television needs a large one, so the platform stores several renditions of each video. The list of renditions is called a bitrate ladder. The bitrates below are round numbers chosen for this course, not figures from any service.
# Assumptions are ours, not measured from any service. LADDER = [ # name, video+audio bitrate in kilobits per second ("240p", 400), ("360p", 800), ("480p", 1200), ("720p", 2500), ("1080p", 5000), ] def mb_per_minute(kbps): return kbps * 1000 / 8 * 60 / 1e6 total_kbps = sum(k for _, k in LADDER) for name, k in LADDER: mb = mb_per_minute(k) print(f"{name:>6} {k:>5} kbps = {mb:6.1f} MB per minute") mb = mb_per_minute(total_kbps) print(f"ladder {total_kbps:>5} kbps = {mb:6.1f} MB per minute")
Python 3.12.10. The ladder is an assumption.
240p 400 kbps = 3.0 MB per minute 360p 800 kbps = 6.0 MB per minute 480p 1200 kbps = 9.0 MB per minute 720p 2500 kbps = 18.8 MB per minute 1080p 5000 kbps = 37.5 MB per minute ladder 9900 kbps = 74.2 MB per minute
Output of the first part of the script.
The five renditions together take 9,900 kilobits per second of video, which is about 74 MB for each minute and 4.5 GB for each hour. The rest of the script scales that to an assumed two lakh hours of new video a day.
hours_per_day = 2_00_000 # hours of new video uploaded daily per_hour_gb = mb_per_minute(total_kbps) * 60 / 1000 print(f"one hour of video, all renditions: {per_hour_gb:.1f} GB") day_tb = hours_per_day * per_hour_gb / 1000 print(f"per day: {day_tb:,.0f} TB") print(f"per year: {day_tb * 365 / 1000:,.0f} PB")
Same script, second half.
one hour of video, all renditions: 4.5 GB per day: 891 TB per year: 325 PB
Last three lines of the same run.
That is about 890 TB of new renditions a day and about 325 PB a year. The original upload is also kept so that a better ladder can be produced later, and that is not counted here. Even before replication, storage is a large and steadily growing bill.
Delivery: what watching costs
New storage per day: ≈ 890 TB (the original files are not counted)
Read it as steps
Five renditions of every hour of video add up to about 4.5 GB, and two lakh hours a day make it a large number.
The scene repeats the arithmetic in the order a person would do it on paper: add the ladder, turn seconds into bytes, then multiply by the daily uploads. Each step is easy to say aloud, and that is the point of estimating this way.
Now the other side. Suppose five crore people watch each day for 40 minutes at an average of 1,500 kilobits per second. That average sits below the top rendition because most sessions run on the lower rungs.
viewers = 5_00_00_000 # daily viewers (assumption) minutes_each = 40 avg_kbps = 1500 # average bitrate actually streamed bits_per_day = viewers * minutes_each * 60 * avg_kbps * 1000 pb_day = bits_per_day / 8 / 1e15 avg_tbps = bits_per_day / 86_400 / 1e12 print(f"watched per day: {pb_day:.1f} PB") print(f"average egress: {avg_tbps:.2f} Tbps") print(f"peak at 3x: {avg_tbps * 3:.2f} Tbps")
watched per day: 22.5 PB average egress: 2.08 Tbps peak at 3x: 6.25 Tbps
Output of the egress script.
Viewers pull about 22.5 PB a day, which is an average of 2.08 Tbps and 6.25 Tbps at three times the average. The daily watched volume is about 25 times the volume of new storage. Delivery, not storage, is the largest and most expensive flow in this system, and that is why the design leans on a CDN, as the cdn chapter explains, so that most bytes travel from a server near the viewer.
Part 2 · API and data model
Why uploads must resume
A video file can be several gigabytes, and the upload often runs on a mobile network that drops. If one failed request means starting over, many uploads would never finish. A resumable upload splits the file into chunks, tracks how many bytes the server holds, and lets the client carry on from that point after a break.
The design needs three operations. The client first creates an upload and receives an id. It then sends chunks, each labelled with the byte range it carries in a Content-Range header. After a lost connection it asks the server for its current offset and resumes from there. The server accepts a chunk only if it starts exactly at the offset it holds, so a repeated or skipped chunk cannot corrupt the file.
| Operation | Request | Meaning |
|---|---|---|
| Start | POST /uploads with the size and title | Returns an upload id and offset 0 |
| Send a chunk | PUT /uploads/{id} with Content-Range | 200 with the new offset, or 409 with the offset the server expects |
| Ask the offset | HEAD /uploads/{id} | Returns the bytes held in an Upload-Offset header |
| Publish | POST /videos with the upload id | Moves the video to processing |
| Watch | GET /videos/{id}, then the playlist URL | Returns metadata and where to stream from |
The names are our own. The behaviour worth copying is that every chunk request is safe to repeat: sending the same range twice either is accepted once or is refused with the true offset, and the client simply continues from the offset it is given.
A resumable upload you can run
The server below keeps uploads in memory, which is enough to show the protocol. A real one would write each chunk to the blob store (the blob store chapter) as it arrives. It runs on port 55502 of this machine. Save the three blocks, in order, as v2_upload_server.py.
import json, re, uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer uploads = {} # id -> {"size": int, "data": bytearray} class H(BaseHTTPRequestHandler): def send_json(self, code, obj, extra=None): body = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) for k, v in (extra or {}).items(): self.send_header(k, v) self.end_headers() self.wfile.write(body) def do_POST(self): if self.path != "/uploads": return self.send_json(404, {"error": "not found"}) n = int(self.headers.get("Content-Length", 0)) meta = json.loads(self.rfile.read(n)) uid = "up_" + uuid.uuid4().hex[:6] uploads[uid] = {"size": meta["size"], "data": bytearray()} self.send_json(201, {"upload_id": uid, "offset": 0}, {"Location": f"/uploads/{uid}"})
Part 1: create an upload.
def do_HEAD(self): u = uploads.get(self.path.rsplit("/", 1)[-1]) self.send_response(200 if u else 404) offset = len(u["data"]) if u else 0 self.send_header("Upload-Offset", str(offset)) self.send_header("Content-Length", "0") self.end_headers()
Part 2: report the offset.
def do_PUT(self): u = uploads.get(self.path.rsplit("/", 1)[-1]) if not u: return self.send_json(404, {"error": "unknown upload"}) m = re.fullmatch(r"bytes (\d+)-(\d+)/(\d+)", self.headers.get("Content-Range", "")) n = int(self.headers.get("Content-Length", 0)) chunk = self.rfile.read(n) if not m: return self.send_json(400, {"error": "bad Content-Range"}) start = int(m.group(1)) if start != len(u["data"]): return self.send_json(409, {"error": "wrong offset", "offset": len(u["data"])}) u["data"] += chunk done = len(u["data"]) == u["size"] self.send_json(200, {"offset": len(u["data"]), "complete": done}) def log_message(self, *a): pass ThreadingHTTPServer(("127.0.0.1", 55502), H).serve_forever()
Part 3: accept a chunk only at the current offset.
A shell script then uploads a 1,000-byte file in three chunks. It sends the first chunk, then tries to send the last chunk too early, asks where the upload stands as a client would after a dropped connection, and finishes in order.
The video record and its states
The bytes live in the blob store, but the platform also needs a small, queryable record for each video. The metadata holds the id, the channel, the title, the duration and the state. The state tells every other part of the system what may happen next: a video in uploading cannot be watched, and one in processing is waiting for its renditions.
import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE video ( id TEXT PRIMARY KEY, channel_id TEXT NOT NULL, title TEXT NOT NULL, state TEXT NOT NULL CHECK (state IN ('uploading','processing','ready','failed','removed')), duration_s REAL, created_at TEXT NOT NULL ); CREATE TABLE rendition ( video_id TEXT NOT NULL REFERENCES video(id), name TEXT NOT NULL, bitrate_kbps INTEGER NOT NULL, playlist TEXT NOT NULL, PRIMARY KEY (video_id, name) ); CREATE INDEX video_by_channel ON video (channel_id, created_at DESC); """)
SQLite stands in for any relational database.
db.execute("INSERT INTO video VALUES ('v1', 'c1', 'Dal tadka'," " 'ready', 612.4, '2026-11-01T10:00:00Z')") db.executemany("INSERT INTO rendition VALUES ('v1',?,?,?)", [("360p", 800, "v1/360p.m3u8"), ("720p", 2500, "v1/720p.m3u8")]) for r in db.execute("""SELECT v.title, v.state, r.name, r.bitrate_kbps FROM video v JOIN rendition r ON r.video_id = v.id ORDER BY r.bitrate_kbps"""): print(r) try: db.execute("UPDATE video SET state='done' WHERE id='v1'") except sqlite3.IntegrityError as e: print("rejected:", e)
Insert two rows, then try an invalid state.
('Dal tadka', 'ready', '360p', 800) ('Dal tadka', 'ready', '720p', 2500) rejected: CHECK constraint failed: state IN ('uploading','processing','ready','failed','removed')
The CHECK message is printed over two lines.
A CHECK constraint limits state to five values, so a bug that writes done is refused by the database and not stored. The rendition table has one row per rung, keyed by video and name, and points at a playlist in the blob store. The index on channel and creation time serves a channel page that lists recent videos.
| State | Set when | Next states |
|---|
Part 3 · High-level design: upload, transcode, store, deliver
Four paths through one system
The platform is easiest to draw as four paths that share a few stores. The upload path carries bytes from the creator into the blob store. The processing path turns the raw file into renditions. The delivery path carries renditions to viewers through a CDN. The metadata path keeps the video record that ties the others together.
The upload path ends in the blob store, not in a database. An object store is built for large, rarely changed objects, and it keeps several copies for durability. The API server writes each chunk there as it arrives and keeps only the offset. When the last chunk lands, the API sets the video's state to processing and puts a job on a message queue. The job holds the video id and little else, because a message should be small and the bytes already sit in the blob store.
The processing path is a pool of transcoders, workers that read the raw file and produce every rung of the ladder, plus a thumbnail and a playlist. Because a queue decouples producers from consumers, a rush of uploads makes the queue longer and the videos wait a little, rather than overloading the API. Adding workers drains it faster. The queue also gives retry for free: if a worker dies mid-job, the message becomes visible again after its timeout and another worker takes it, as the message queue chapter describes.
The whole flow
Watch for the file reaching the blob store before any job is queued
Read it as steps
A creator's file is stored, a job is queued, workers write renditions, and viewers read them through the CDN.
The scene shows the property that makes the design easy to scale: the services never pass big files to each other, only ids and object keys. The blob store is the shared place where bytes rest, and the CDN is the only thing viewers talk to.
Because the queue delivers a job at least once, a worker may sometimes run a job twice. That is harmless here because the output keys are fixed. A rerun writes the same renditions to the same keys, and the video's state moves to ready again. Designing steps so that repeating them is safe is what lets a simple retry rule work.
Where each kind of data lives
Matching each kind of data to a store is the main design decision of this chapter. The table sums it up, with the reason in the last column.
| Data | Where | Why |
|---|---|---|
| Raw upload | Blob store, private bucket | Large and kept for re-encoding; viewers never read it |
| Renditions and playlists | Blob store, public through the CDN | Immutable once written, so they cache well |
| Video record and state | Relational database with replicas | Small, queried by id and by channel |
| Processing jobs | Message queue | Absorbs spikes and retries failed work |
| Hot video pages | In-memory cache | Many reads of the same few thousand records |
| View counts | Counter shards | One viral video must not become a hot row |
The last two rows come from the building blocks already covered, and the next lessons dig into the two parts that are specific to video: how the renditions are made, and how a player uses them.
Two failures are worth naming now. If transcoding fails after its retries, the video moves to failed and the creator sees an error, so a stuck job never leaves a video in processing forever. If the CDN loses an edge location, viewers are routed to another one and the blob store absorbs a burst of misses, which is why it must be sized for more than the average miss rate.
Why does the queued job carry only the video id and not the file?
Part 4 · Deep dive: transcoding and adaptive streaming
Why one file is not enough
A raw upload is a poor thing to send to a viewer. It may use a codec the viewer's device cannot decode, its bitrate may be far above what a mobile connection carries, and its resolution may be wasted on a small screen. Transcoding converts the file into versions that suit different devices and networks. A codec is the method that compresses video, and a bitrate is how many bits describe each second of it.
The remedy for a changing network is adaptive bitrate streaming. Each rendition is cut into short segments, a few seconds long. A text file called a playlist lists the segments in order. The player downloads one segment at a time and, before each download, picks the rendition that its measured throughput can sustain. If the network slows down, the next segment comes from a lower rung and playback continues at lower quality instead of freezing.
HTTP Live Streaming, specified in RFC 8216, is one way to do this, and MPEG-DASH, with guidelines from the DASH Industry Forum, is another. This lesson uses HLS because its playlists are plain text. A master playlist lists the renditions, each with its peak bandwidth and resolution. A media playlist lists the segments of one rendition, each with its duration, and ends with a tag that says no more segments will come.
Keyframes decide where you can switch
A player can only join a new rendition at a point where it can start decoding from scratch. Video codecs store most frames as differences from earlier frames, and only a keyframe is complete in itself. A segment that starts with a keyframe can be decoded alone, and if every rendition has its keyframes at the same moments, a player can leave one rendition at a segment boundary and enter another without a glitch.
So the transcoder must place keyframes on a fixed schedule instead of letting the encoder choose them by scene changes. At 30 frames per second, a segment of four seconds is 120 frames, so the keyframe interval is 120 and scene-change keyframes are turned off. The command below makes three renditions of a 20 second test pattern in one pass and writes HLS output. The picture is a generated test pattern with a sine tone, so no real footage is involved.
ffmpeg -hide_banner -loglevel error -y \ -f lavfi -i testsrc2=size=1280x720:rate=30:duration=20 \ -f lavfi -i sine=frequency=440:duration=20 \ -filter_complex \ "[0:v]split=3[a][b][c];[a]scale=426:240[v0];\ [b]scale=854:480[v1];[c]scale=1280:720[v2]" \ -map "[v0]" -map "[v1]" -map "[v2]" -map 1:a -map 1:a -map 1:a \ -c:v libx264 -preset veryfast -g 120 -keyint_min 120 -sc_threshold 0 \ -b:v:0 400k -maxrate:v:0 400k -bufsize:v:0 800k \ -b:v:1 1200k -maxrate:v:1 1200k -bufsize:v:1 2400k \ -b:v:2 2500k -maxrate:v:2 2500k -bufsize:v:2 5000k \ -c:a aac -b:a 64k \ -f hls -hls_time 4 -hls_playlist_type vod \ -hls_segment_filename "hls/%v_%03d.ts" \ -master_pl_name master.m3u8 \ -var_stream_map \ "v:0,a:0,name:240p v:1,a:1,name:480p v:2,a:2,name:720p" \ "hls/%v.m3u8"
ffmpeg 9.0.1. -g sets the keyframe interval, -sc_threshold 0 turns off scene-change keyframes.
The encode of this 20 second clip took between 1.3 and 1.7 seconds in two runs on this machine, which is more than ten times faster than playing it. Real footage is harder to compress than a test pattern, so treat that ratio as a best case and not a promise.
What the output says
The run produced a master playlist, three media playlists and five segments for each rendition. The command below prints the master playlist and one media playlist, with the codec attribute removed to keep the lines short.
$ cat hls/master.m3u8 (CODECS and AVERAGE-BANDWIDTH removed) #EXTM3U #EXT-X-VERSION:3 #EXT-X-STREAM-INF:BANDWIDTH=533920,RESOLUTION=426x240 240p.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=1419776,RESOLUTION=854x480 480p.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=2774880,RESOLUTION=1280x720 720p.m3u8 $ cat hls/480p.m3u8 #EXTM3U #EXT-X-VERSION:3 #EXT-X-TARGETDURATION:4 #EXT-X-MEDIA-SEQUENCE:0 #EXT-X-PLAYLIST-TYPE:VOD #EXTINF:4.000000, 480p_000.ts #EXTINF:4.000000, 480p_001.ts #EXTINF:4.000000, 480p_002.ts #EXTINF:4.000000, 480p_003.ts #EXTINF:4.000000, 480p_004.ts #EXT-X-ENDLIST
Files from this run. Encoders are not deterministic, so sizes change between runs.
The master playlist lists three variants with their BANDWIDTH and RESOLUTION. The 240p variant says 533920 bits per second, which is above the 400 kbps video target because it includes 64 kbps of audio and is a peak, not an average. RFC 8216 defines the attribute as the peak segment bit rate, and here it matches the largest 240p segment: 266960 bytes times 8 bits, divided by four seconds, is 533920.
The media playlist has #EXT-X-TARGETDURATION:4, one #EXTINF line per segment and #EXT-X-ENDLIST. Since the playlist type is VOD, a player knows the list is complete and can show a seek bar for the whole video. The check below asks ffprobe for the flags of every video packet in each 480p segment. Each segment holds exactly one keyframe, and it is the first packet.
for f in hls/480p_00*.ts; do ffprobe -v error -select_streams v:0 -show_entries packet=flags \ -of csv=p=0 "$f" > flags.txt echo "$(basename $f) keyframes=$(grep -c K flags.txt)" \ "first=$(head -1 flags.txt | cut -c1)" done
Counts packets flagged K, and shows the flag of the first packet.
480p_000.ts keyframes=1 first=K 480p_001.ts keyframes=1 first=K 480p_002.ts keyframes=1 first=K 480p_003.ts keyframes=1 first=K 480p_004.ts keyframes=1 first=K
Real output: one keyframe per segment, at the start.
Long videos are processed by cutting the raw file at keyframes, encoding the pieces on many workers at once, and joining the pieces' segments in one playlist. Because segments are independent, the work parallelises well. That is how a long upload can be ready much sooner than its running time.
Part 5 · Deep dive: delivery and the player
How a player plays
The player does most of the thinking in adaptive streaming. The server only hands out files, and every file is a plain HTTP response, so any web server or CDN can serve it. The player downloads the master playlist, picks a variant, downloads that variant's media playlist and then fetches the segments in order. It keeps a buffer, the seconds of video already downloaded but not yet played, and it tries to keep that buffer from running dry.
The rule used here is simple. Start on the lowest rung so playback begins quickly. After each segment, estimate throughput as the segment's bytes divided by the time it took. Then choose the highest variant whose declared bandwidth is no more than 80 percent of that estimate. The margin leaves room for the estimate being optimistic. Real players add smoothing and look at the buffer level too, but the idea is the same.
The cache rules follow from how the files behave. A segment never changes once written, so its response can say it is cacheable for a year and immutable. A playlist for a finished video also never changes, but a short lifetime lets the platform replace it if a video is re-encoded. Every viewer asks for the same URLs, so the CDN's cache key, which is the URL, matches across viewers and each segment is fetched from the origin about once per edge location, or about once in all when a shield sits in front of the origin, as the cdn chapter describes.
Serving it and reading the headers
The server below sends the files with those cache headers and can throttle its speed, which the next script uses to imitate a bad network. Everything runs on this machine with curl 8.21.0 and Python 3.12.10, on ports 55503 and 55504.
import os, sys, time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer ROOT = "hls" state = {"kbps": None} # None means no throttle TYPES = {".m3u8": "application/vnd.apple.mpegurl", ".ts": "video/mp2t"}
Save the three blocks as hls_server.py. State and content types.
class H(BaseHTTPRequestHandler): def do_GET(self): name = os.path.basename(self.path) path = os.path.join(ROOT, name) if not os.path.isfile(path): self.send_response(404) self.send_header("Content-Length", "0") return self.end_headers() data = open(path, "rb").read() ext = os.path.splitext(name)[1] self.send_response(200) self.send_header("Content-Type", TYPES[ext]) self.send_header("Content-Length", str(len(data))) if ext == ".ts": # a segment never changes once written cc = "public, max-age=31536000, immutable" else: cc = "public, max-age=60" self.send_header("Cache-Control", cc) self.end_headers() step = 16384 for i in range(0, len(data), step): self.wfile.write(data[i:i + step]) if state["kbps"]: time.sleep(step * 8 / (state["kbps"] * 1000)) def log_message(self, *a): pass def serve(port): return ThreadingHTTPServer(("127.0.0.1", port), H)
Playlists get 60 seconds; segments get a year and immutable.
if __name__ == "__main__": serve(int(sys.argv[1])).serve_forever()
Lets the shell script start it on a port.
python hls_server.py 55503 & PID=$! sleep 1 B=http://127.0.0.1:55503 show() { grep -E "HTTP|Content-Type|Cache-Control|Content-Length"; } echo '$ curl -D - 480p.m3u8' curl -s -D - -o /dev/null $B/480p.m3u8 | tr -d '\r' | show echo '$ curl -D - 480p_001.ts' curl -s -D - -o /dev/null $B/480p_001.ts | tr -d '\r' | show echo '$ fetch the playlist, then every segment it names' for s in $(curl -s $B/480p.m3u8 | grep '\.ts'); do curl -s -o /dev/null -w "$s %{http_code} %{size_download} bytes\n" \ $B/$s done kill $PID
show prints only the headers of interest.
$ curl -D - 480p.m3u8 HTTP/1.0 200 OK Server: BaseHTTP/0.6 Python/3.12.10 Content-Type: application/vnd.apple.mpegurl Content-Length: 263 Cache-Control: public, max-age=60 $ curl -D - 480p_001.ts HTTP/1.0 200 OK Server: BaseHTTP/0.6 Python/3.12.10 Content-Type: video/mp2t Content-Length: 663264 Cache-Control: public, max-age=31536000, immutable $ fetch the playlist, then every segment it names 480p_000.ts 200 709888 bytes 480p_001.ts 200 663264 bytes 480p_002.ts 200 639012 bytes 480p_003.ts 200 657624 bytes 480p_004.ts 200 687328 bytes
Segment sizes differ from run to run of the encoder.
A player that steps down
The script plays the first five segments of the video. It throttles the server to about 6 Mbps for the first three segments and to 2.2 Mbps after that, which is an invented network, and it prints the rendition chosen, the download time, the measured rate and the buffer. The buffer arithmetic is simple: each segment adds 4 seconds, and each download time is subtracted because playback runs while it downloads.
import re, threading, time, urllib.request import hls_server PORT = 55504 BASE = f"http://127.0.0.1:{PORT}/" SEG_S = 4.0 srv = hls_server.serve(PORT) threading.Thread(target=srv.serve_forever, daemon=True).start() def get(name): t0 = time.perf_counter() body = urllib.request.urlopen(BASE + name).read() return body, time.perf_counter() - t0 master = get("master.m3u8")[0].decode() variants = re.findall(r"BANDWIDTH=(\d+).*?\n(\S+\.m3u8)", master) variants = sorted((int(b), u) for b, u in variants) # lowest first playlists = {u: re.findall(r"^(\S+\.ts)$", get(u)[0].decode(), re.M) for _, u in variants}
Save as v5_player.py. Start the server in a thread, read the master playlist, then each media playlist.
# Pretend the network gets worse from the fourth segment on. network = {0: 6000, 1: 6000, 2: 6000, 3: 2200, 4: 2200} level, buffer_s = 0, 0.0 print("seg rendition bytes took rate buffer") for i in range(5): hls_server.state["kbps"] = network[i] bw, url = variants[level] seg = playlists[url][i] body, took = get(seg) rate = len(body) * 8 / took / 1000 if i > 0: buffer_s = max(buffer_s - took, 0) buffer_s += SEG_S print(f"{i} {seg.split('_')[0]:>6} {len(body):>8} {took:5.1f}s" f" {rate:5.0f}kbps {buffer_s:5.1f}s") # next: the highest variant that fits in 80% of the measured rate budget = 0.8 * rate * 1000 fit = [k for k, (b, _) in enumerate(variants) if b <= budget] level = fit[-1] if fit else 0 srv.shutdown()
The decision rule is the three lines that set budget, fit and level.
seg rendition bytes took rate buffer 0 240p 266960 0.4s 5985kbps 4.0s 1 720p 1360556 1.9s 5860kbps 6.1s 2 720p 1258660 1.7s 5918kbps 8.4s 3 720p 1337808 4.9s 2198kbps 7.6s 4 480p 687328 2.5s 2232kbps 9.1s
Timings vary from run to run; this is one real run.
Part 6 · View counts, recommendations and failures
Counting views without a hot row
A view count looks like one number per video, and a popular video receives thousands of increments a second. If every play adds one to the same database row, writes queue behind that row's lock. The sharded counter chapter solves this by spreading one logical counter over many rows and summing them on read. This lesson applies it to video and adds a second trick.
The first trick is to count plays from a stream of events and not on the request path. The player sends a view event after a few seconds of playback, which also keeps accidental starts from counting. A collector appends events to a log, and an aggregator turns them into increments. The second trick is batching: the aggregator adds a minute's worth of plays for a video in one update instead of one update per play. The script below imitates the database row lock with a lock and a one millisecond hold, because SQLite allows one writer at a time for the whole database and could not show row contention.
import random, threading, time HOLD = 0.001 # time one update holds its row lock, a stand-in for a # database commit (SQLite locks the whole file, so it # cannot show row-level contention) class Counter: def __init__(self, shards): self.locks = [threading.Lock() for _ in range(shards)] self.n = [0] * shards def add(self, k=1): s = random.randrange(len(self.n)) with self.locks[s]: time.sleep(HOLD) self.n[s] += k def total(self): return sum(self.n)
A counter split over locked shards.
def run(shards, threads=8, per_thread=150, batch=1): c = Counter(shards) def worker(): for _ in range(per_thread // batch): c.add(batch) # one write carries `batch` views ts = [threading.Thread(target=worker) for _ in range(threads)] t0 = time.perf_counter() [t.start() for t in ts] [t.join() for t in ts] return time.perf_counter() - t0, c.total() for shards, batch in ((1, 1), (16, 1), (1, 10)): took, total = run(shards, batch=batch) print(f"shards={shards:>2} batch={batch:>2} views={total}" f" took={took:.2f}s")
Eight threads add 1,200 views.
shards= 1 batch= 1 views=1200 took=1.84s shards=16 batch= 1 views=1200 took=0.30s shards= 1 batch=10 views=1200 took=0.19s
Timings are on this machine and vary.
All three runs counted 1,200 views. One shard with 8 threads took 1.84 seconds because every update waited for the same lock. Sixteen shards took 0.30 seconds, and a single shard with batches of ten plays took 0.19 seconds. The two fixes can be combined. The total a viewer sees can lag by a few seconds without harm, and an exact count is only needed for billing, which can be computed later from the event log.
Recommendations in two stages
The platform also suggests what to watch next. A video catalogue holds crores of videos, so scoring each one for each person with an expensive model is out of the question. A 2016 paper from Google researchers on neural networks for video recommendations describes the usual shape: a first stage, candidate generation, cheaply narrows the whole catalogue to a short list, and a second stage, ranking, scores only those with a richer model. Only that two-stage idea is borrowed here.
The toy below has the same two stages on made-up watch sessions. Stage one keeps videos that were watched together with the one just played. Stage two orders that short list by how often they were watched together, weighted by a quality score.
from collections import Counter # Made-up watch sessions: each list is what one viewer watched. sessions = [ ["dal", "rajma", "paratha"], ["dal", "rajma", "chai"], ["dal", "paratha", "chai"], ["cricket", "chai"], ["cricket", "highlights"], ["highlights", "cricket", "dal"], ["rajma", "paratha"], ["dal", "rajma"], ] quality = {"dal": 0.9, "rajma": 0.8, "paratha": 0.6, "chai": 1.0, "cricket": 0.95, "highlights": 0.7} def candidates(seed, k=4): """Stage 1: cheap, wide. Videos watched together with the seed.""" together = Counter() for s in sessions: if seed in s: together.update(v for v in s if v != seed) return [v for v, _ in together.most_common(k)], together def rank(seed, cands, together): """Stage 2: costlier scoring on the short list only.""" return sorted(cands, key=lambda v: together[v] * quality[v], reverse=True) cands, together = candidates("dal") print("stage 1 keeps:", cands, "from", len(quality) - 1, "videos") print("stage 2 order:", rank("dal", cands, together))
Sessions and scores are invented.
stage 1 keeps: ['rajma', 'paratha', 'chai', 'highlights'] from 5 videos stage 2 order: ['rajma', 'chai', 'paratha', 'highlights']
Deterministic output.
The ranking stage changed the order: chai, with the highest quality score, moved above paratha although they co-occur just as often (twice each). Splitting the work keeps the costly step on a small list, and each stage can be improved or cached separately. The candidate lists themselves can be computed ahead of time and stored, so the home page only runs the ranking.
Failures and trade-offs
Every part of the design can fail, and the table below lists the likely ones with what the viewer or creator sees and how the design copes.
| Failure | What happens | How the design copes |
|---|---|---|
| Upload connection drops | The creator's upload stalls | Resume from the server's offset |
| A transcoder dies | The job is not acknowledged | The queue redelivers it; fixed output keys make the rerun safe |
| A corrupt upload | Every retry fails | After a few attempts the video becomes failed and the creator is told |
| An edge location is lost | Viewers there get errors | Traffic is routed to another edge; the origin absorbs the extra misses |
| The origin is slow | Segments are late | The player steps down; shielding caches protect the origin |
| A viral video | Counters and the metadata row get hot | Sharded and batched counters; cache the video page |
There are real trade-offs in the choices. A longer segment gives fewer requests and better compression, but a slower reaction to network changes and a slower start. A larger ladder serves more devices but costs more storage and more encoding time. Encoding every video at every rung wastes work on videos nobody watches, so a platform may encode the top rungs only after a video becomes popular, which saves storage and compute at the cost of lower quality at first.
Extensions follow naturally from the same parts. Live streaming uses short segments and a playlist that keeps growing. Captions are one more text file per video. Protecting paid content adds encryption of segments and a licence step, which this chapter leaves out.
All chapters · Previous: Putting the Blocks Together: Timed Practice