Case Study: YouTube & Video Streaming
"We've seen up to 20-33x improvements in compute efficiency compared to our previous optimized system, which was running software on traditional servers." — Jeff Calow, YouTube, Reimagining video infrastructure to empower YouTube (YouTube Official Blog, 21 April 2021)
Summary: YouTube is a write-once, read-billions video system. Creators upload one file, the platform turns it into dozens of renditions (resolution × codec), copyright and abuse checks run, and the renditions are served from caches inside ISPs to players that switch quality every few seconds. Around that core sit metadata (sharded MySQL behind Vitess, historically), recommendations (a two-stage deep neural network), view counts that are validated before they are shown, comments, live chat and live streaming. Focus: The 4-step method applied to YouTube: scope, estimate (500 hours uploaded per minute, 20 million videos a day, 200 billion daily Shorts views), high-level design per subsystem (resumable upload, chunked parallel transcoding, the encoding ladder, VP9/AV1 and the Argos VCU ASIC, Colossus/Bigtable/Spanner, Vitess MySQL sharding, Google Global Cache, adaptive bitrate over DASH/HLS, QUIC, metadata and search, candidate generation + ranking, view counting and the 301+ folklore, comments and live chat, live streaming with RTMP/HLS ingest, latency modes and DVR, Content ID, spam), and the decisions. Every architecture claim is cited to YouTube's or Google's own pages; everything else is marked inference. Learning goal: Explain each YouTube subsystem with one cited fact and one number, reproduce the estimate, say which generic chapter each subsystem maps to, and implement the two mechanisms you would really copy (a resumable chunked upload endpoint and a chunk × rung transcoding fan-out, plus a validated view counter) in Go and Laravel 13.
This is a case study in the SD 10 group. It owns the YouTube-specific story: what YouTube and Google have published about the system, the numbers, and the decisions. It does not re-teach the mechanics. Caching tiers, HLS/DASH packaging and signed URLs live in CDNs; the method in The 4-Step Approach and Capacity Estimation; blob storage in Object Storage; counters in Write Buffering & Sharded Counters; chat transport in Real-Time Communication; ranking in Search Systems and ML Systems; QUIC in HTTP evolution. The other video case study is Case Study: Netflix.
Rule for this page. A sentence that describes YouTube's architecture is backed by a source written by YouTube or Google (blog, paper, help centre, developer docs, vitess.io) that was fetched and saved. When the page generalises, guesses a number or fills a gap with industry practice, it says inference.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why video is a different problem | Why it exists |
| The dated sources and the timeline | Where it comes from |
| Step 1: requirements | Scope |
| Step 2: numbers | Estimate |
| Resumable and chunked upload | Upload |
| Ladders, chunks, codecs, VCU | Transcoding, Codecs and Argos VCU |
| Colossus, Bigtable, Spanner, Vitess | Storage |
| Google Global Cache, ABR, DASH, HLS, QUIC | Delivery |
| Titles, tags, search | Metadata and search |
| Candidate generation and ranking | Recommendations |
| Procella, frozen counts, 301+ | View counting |
| Comments and live chat | Comments and live chat |
| RTMP, HLS ingest, latency, DVR | Live streaming |
| Copyright matching | Content ID |
| Spam, fake engagement | Abuse and spam |
| Step 4: the decisions | Decisions |
| What changed, by year | What changed over time |
| Which chapter to read for each subsystem | What you can copy |
| Exact protocol knobs and codes | Mechanics |
| Code | Go, Laravel |
| Classic failures | Solving the classic problems |
| Which design for your product | Choosing |
| From a monolith to YouTube scale | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The subsystems and the one fact to remember.
| Subsystem | One cited fact | Source |
|---|---|---|
| Upload | Resumable sessions; status query answers 308 Resume Incomplete with Range | YouTube Data API guide |
| Transcoding | Custom VCU chip: "up to 20-33x" compute efficiency | YouTube blog 2021, ASPLOS 2021 paper |
| Codecs | VP9 looks better than H.264 but "uses 5x more computer resources to encode" | YouTube blog 2021 |
| File storage | Colossus underpins "YouTube, Drive, and Gmail" | Google Cloud blog 2021 |
| Metadata | Vitess "was created in 2010" for YouTube's MySQL scaling | vitess.io history |
| Delivery | GGC lets ISPs "serve certain Google content from within their own networks" | Google Interconnect help |
| Transport | QUIC cut YouTube rebuffer rates by 18.0% (desktop) and 15.3% (mobile) | SIGCOMM 2017 paper |
| Recommendations | Two networks: candidate generation, then ranking | Covington et al., RecSys 2016 |
| View counts | Counts may be slowed, frozen or adjusted while views are verified | YouTube Help |
| Counter serving | Procella serves "over a million QPS" of view/like counter queries per instance | Procella, VLDB 2019 |
| Live | Latency modes: normal, low (most viewers under 10 s), ultra-low (under 5 s) | YouTube Help |
| Copyright | Content ID scans every upload; claim actions: block, monetize, track | YouTube Help |
The four steps on one line each.
| Step | YouTube answer |
|---|---|
| 1. Scope | Upload, process, watch on any device, find (search, recommendations), engage (views, likes, comments, chat), go live, protect rights |
| 2. Estimate | 500 hours per minute upload, 20 million videos per day, billions of logged-in users, 200 billion daily Shorts views |
| 3. High-level design | Upload API → original store → chunked transcode (CPU/VCU) → renditions → ISP caches → ABR player; side paths for metadata, recs, counters, chat, Content ID |
| 4. Decisions | Spend compute once at upload to save bytes forever; build hardware when software stops scaling; push bytes into ISPs; rank for watch time; validate counts before showing them |
Numbers to carry.
| Quantity | Value | Kind |
|---|---|---|
| Video uploaded | more than 500 hours per minute on average | Cited (YouTube blog, 2021) |
| Videos uploaded | over 20 million per day | Cited (YouTube press page, 2026) |
| Shorts views | over 200 billion per day | Cited (YouTube press page, 2026) |
| Upload ingress | about 240 Gbit/s average | Estimate, inference (see Estimate) |
| New bytes stored | about 7.5 PB per day before replication | Estimate, inference |
| Recommendation model | about one billion parameters, hundreds of billions of examples | Cited (Covington 2016) |
| GGC offload | typically 70 to 90 percent of cacheable traffic | Cited (Google Interconnect help) |
Why it exists
Most web systems move kilobytes. A video system moves gigabytes per user session and stores each upload many times. Three forces shape everything:
| Force | Consequence |
|---|---|
| One upload, many devices | Every file must exist in many resolutions and codecs (the encoding ladder) |
| Bytes dominate cost | Spending CPU once at upload to shrink bytes on every view pays back; better codecs (VP9, AV1) win |
| Viewers are everywhere | Bytes must come from close by: caches inside ISPs, not one data centre |
| Networks fluctuate | The player must change quality mid-stream (adaptive bitrate) |
| Open upload | Copyright matching, spam and abuse checks are part of the pipeline, not an add-on |
| Popularity is skewed | A few videos get most views; counters and caches face hot keys |
Everyday picture. A publisher that receives a manuscript, prints it in pocket, hardcover and large-print editions, ships boxes to every local bookshop in advance, and lets each reader swap edition page by page depending on the light. The printing is expensive but done once; the shipping is cheap only because the shops are close to the readers.
Three common misunderstandings, up front
- "YouTube streams the file the creator uploaded." It streams renditions produced by transcoding; the blog states video "is created and uploaded in a single format, but will ultimately be consumed on different devices".
- "YouTube is one big database." The published sources describe many systems: Vitess on MySQL, Colossus, Bigtable, Spanner, Procella, Monarch, Dremel, each for a different job.
- "The view count is a counter incremented on play." YouTube's help centre says counts are verified and may be frozen or adjusted; the Procella paper shows counters are served from an analytics engine in a special stats-serving mode.
Where it comes from
The public record is a set of dated primary sources. In order:
- 2007–2012, the early architecture talk. Cuong Do's talk YouTube Scalability at the Seattle Conference on Scalability is on YouTube; the saved page shows it was published on 2012-08-22. The conference itself was in 2007 (that date is not on the saved page). This page does not quote it, because the video was not transcribed; treat any summary of it you read elsewhere as historical (pre-Google-infrastructure) and secondary.
- 2008, recommendations begin. YouTube's VP of Engineering for recommendations writes that "Back in 2008, when we first started building our recommendation system", videos were ranked by popularity on one "Trending" page (YouTube blog, September 2021).
- 2010, Vitess. "Vitess was created in 2010 to solve the MySQL scalability challenges that the team at YouTube faced" (vitess.io history). The page tells the classic ladder: one primary, read replicas, more replicas, then sharding in the application, then a proxy.
- 2012, watch time. "That's why we added in watchtime in 2012" (YouTube blog 2021), after learning in 2011 that clicks are not watching.
- 2015, QUIC and the VCU project. Chromium blog (April 2015): about half of Chrome's requests to Google use QUIC, and "Users report 30% fewer rebuffers" on YouTube. The VCU project "kicked off" in 2015 (YouTube blog 2021).
- 2016, deep learning recommendations. Covington, Adams and Sargin, Deep Neural Networks for YouTube Recommendations, RecSys 2016.
- 2017, QUIC paper. Langley et al., The QUIC Transport Protocol: Design and Internet-Scale Deployment, SIGCOMM 2017, with YouTube rebuffer measurements.
- 2019, Procella and multitask ranking. Procella: Unifying serving and analytical data at YouTube (VLDB 2019); Recommending What Video to Watch Next: A Multitask Ranking System (RecSys 2019); Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations (RecSys 2019).
- 2021, Argos VCU and Colossus. Warehouse-Scale Video Acceleration: Co-design and Deployment in the Wild (ASPLOS 2021) and the YouTube blog interview (April 2021); the Google Cloud blog on Colossus (April 2021).
- 2026, current numbers. YouTube press page (fetched November 2026): over 20 million videos uploaded daily; Shorts "averaging over 200 billion daily views". YouTube Help on engagement metrics: from November 2026 public counts include co-view estimates on TV screens.
The year-by-year table is in What changed over time.
The concept catalogue
The catalogue follows the 4-step method of The 4-Step Approach: Step 1 and Step 2 first, then one block per subsystem of the high-level design (Step 3), then the decisions (Step 4).
Step 1 · Scope: what YouTube must do Must-know
In plain words: Before drawing boxes, list what users do: upload, watch, find, react, chat, go live; and what the company must guarantee: rights, safety, ads.
Common misunderstanding: "The scope is upload and playback." That is a file server. Recommendations drive "a significant amount of the overall viewership on YouTube, even more than channel subscriptions or search" (YouTube blog 2021), and Content ID runs on every upload; leaving them out produces the wrong design.
Definition: Functional requirements are user actions; non-functional requirements are the qualities (availability, latency, cost per byte, durability, fairness of counts) that the actions must meet.
creator: upload -> (processing) -> publish -> watch stats, comments, claims
viewer : open app -> recommendations -> play (ABR) -> like / comment / subscribe
live : encoder -> ingest -> live transcode -> players (latency mode, DVR) + live chat
rights : upload -> Content ID scan -> claim -> block | monetize | trackReal scenario: a creator on a train uploading from a phone (resumable upload); a TV in a living room (4K, co-viewing counted); a phone on a bus (low bitrate, ABR); a record label protecting a catalogue (Content ID); a gamer streaming with ultra-low latency and live chat.
| Requirement | Target (assumption unless cited) | Design consequence |
|---|---|---|
| Upload survives bad networks | Resume after interruption (cited: resumable protocol) | Session URI, byte offsets, 308 |
| Time to watchable | Minutes (assumption) | Parallel transcoding; publish low rungs first (inference) |
| Playback start | About a second (assumption) | Caches near users, small first segments |
| Rebuffering | As low as possible (QUIC paper uses rebuffer rate as the metric) | ABR, QUIC, ISP caches |
| Durability of originals | Never lose an upload (assumption) | Replicated or erasure-coded storage (Colossus) |
| Counts are trustworthy | Verified before display (cited: YouTube Help) | Validation pipeline, delayed counts |
| Rights | Every upload scanned (cited: Content ID help) | Fingerprinting in the pipeline |
Fix / how to use it: write this table first in any video design; the rows with "cited" are YouTube's own constraints, the others are yours to set.
Step 2 · Estimate: the numbers Must-know
In plain words: Turn the published numbers into bandwidth, storage and request rates, and label every assumption.
Common misunderstanding: "Hours uploaded per minute is a vanity number." It is the input to every capacity line: ingress bandwidth, transcode compute and storage all scale with it.
Definition: A back-of-envelope estimate multiplies a cited rate by assumed sizes; the method is in Capacity Estimation.
1 cited : > 500 hours uploaded per minute (2021) -> 720,000 hours/day
2 assume : source bitrate 8 Mbit/s = 1 MB/s = 3.6 GB/hour
3 ingress : 720,000 h x 3.6 GB = 2.6 PB/day -> 2.6e15 / 86,400 s = 30 GB/s = 240 Gbit/s
4 assume : ladder 144p..1080p H.264 = 9.3 Mbit/s total, VP9 copy about 60% of that = 5.6 Mbit/s
5 output : 14.9 Mbit/s = 6.7 GB per source hour -> 4.8 PB/day of renditions
6 total : about 7.5 PB/day new bytes before replication or erasure coding
7 cited : > 20 million videos/day (2026) and 720,000 h/day (2021) -> mixing years, avg about 2 minutes
8 cited : > 200 billion Shorts views/day -> 200e9 / 86,400 = 2.3 million views/s average
9 assume : peak = 2 x average -> about 4.6 million view events/s for Shorts aloneEvery line marked assume is an inference for teaching. Line 7 deliberately shows a trap: the two cited numbers come from different years and the second includes Shorts, so the "average length" is not a fact about YouTube.
Real scenario: sizing an upload front end (line 3); budgeting transcoding (line 5 times encode cost); planning counter infrastructure (line 9); explaining why storage tiers matter (most old videos are rarely watched, inference).
| Line | Input | Result | Kind |
|---|---|---|---|
| Upload hours/day | 500 × 60 × 24 | 720,000 | Cited rate |
| Ingress | 3.6 GB/h source | about 240 Gbit/s | inference |
| Renditions | 6.7 GB/h | about 4.8 PB/day | inference |
| View events | 200 billion/day | about 2.3 million/s | Cited rate, derived |
| Counter reads | per watch-page load | millions QPS | Procella: "millions of low latency queries per second" (cited) |
Fix / how to use it: keep cited and assumed values in separate columns; change the assumptions, never the citations.
Upload: resumable and chunked Must-know
In plain words: The client opens an upload session, sends bytes, and when the network drops it asks "how much did you get?" and continues from there instead of starting over.
Common misunderstanding: "Chunked upload is required for resumability." The YouTube Data API guide says uploading in chunks "is rarely necessary and is actually discouraged because it requires additional requests"; a single PUT plus resume-on-failure is the default, and chunks are for progress bars on very unstable networks.
Definition: The resumable upload protocol for Google APIs, as documented for YouTube: (1) POST /upload/youtube/v3/videos?uploadType=resumable with X-Upload-Content-Length and the video metadata JSON; (2) the 200 response carries a Location session URI; (3) PUT the bytes to it; (4) on interruption, an empty PUT with Content-Range: bytes */TOTAL returns 308 Resume Incomplete and Range: bytes=0-N; resume with Content-Range: bytes N+1-LAST/TOTAL; 201 Created ends it. Chunks must be "a multiple of 256 KB" except the last. An expired session URI returns 404.
1 client -> POST ?uploadType=resumable X-Upload-Content-Length: 3000000
2 server -> 200 OK Location: .../videos?uploadType=resumable&upload_id=xa298sd_f
3 client -> PUT (3,000,000 bytes) ... connection lost after 1,000,000
4 client -> PUT Content-Length: 0 Content-Range: bytes */3000000
5 server -> 308 Resume Incomplete Range: bytes=0-999999
6 client -> PUT Content-Range: bytes 1000000-2999999/3000000
7 server -> 201 Created (video resource JSON)Real scenario: mobile uploads on cellular; a 4K file from a home connection; a desktop app that shows progress per chunk; a creator who closes the laptop and resumes next morning (if the session has not expired).
| Situation | Response | Client action |
|---|---|---|
| Upload finished | 201 Created (or 200) | Done; poll processing status |
| Interrupted, still in progress | 308 with Range | Resume from last byte + 1 |
Server error 500, 502, 503, 504 | Resumable | Back off, query status, resume |
Other 4xx | Permanent failure | Fix the request |
| Expired session URI | 404 Not Found | Start a new session |
| Overlapping or skipped bytes | "none of the remaining binary content will be uploaded" | Re-read Range and send the exact next byte |
Retry-After present | Wait that long | Then resume |
Fix / how to use it: the Go and Laravel re-implementations in Go and Laravel implement exactly these rules. For S3-style storage the same idea is multipart upload with presigned part URLs (Object Storage, File Uploads, S3 & CDN in Go).
Transcoding: the encoding ladder and parallel chunks Must-know
In plain words: One uploaded file becomes many: each resolution (the rungs of a ladder) in each codec. To make this fast, the video is cut into pieces that are encoded at the same time on many machines.
Common misunderstanding: "Transcoding is a format conversion that happens once." It is the "compressing of videos so that we send the smallest amount of data to your chosen device with the highest possible quality video" (YouTube blog 2021), repeated per rung and per codec, and repeated again when a new codec arrives.
Definition: An encoding ladder is the list of (resolution, codec, bitrate) renditions produced for each video. Parallel transcoding splits the source into chunks at keyframes, encodes every (chunk, rung) task independently, and concatenates the results. The split-and-parallelise step is standard industry practice; YouTube's published sources describe the VCU hardware and its co-design with "large-scale distributed software systems" but the saved pages do not document YouTube's chunk scheduler, so the chunk details on this page are inference.
1 upload complete -> probe: 1080p, 10 min, H.264 source
2 split at keyframes -> 60 chunks of 10 s
3 plan: rungs {144p..1080p} x codecs {H.264, VP9} -> 60 x 12 = 720 tasks
4 workers (CPU or VCU) pull tasks in parallel; failed task retried alone
5 per rung: concatenate 60 segments in order -> manifest entry
6 low rungs finish first -> video watchable before 4K/AV1 exists (inference)Real scenario: a ten-minute video becomes watchable in minutes instead of hours; a single corrupt chunk fails the task, not the whole video; a newly added codec is backfilled for popular videos first (inference, consistent with the 2021 blog saying VP9 costs 5x to encode).
| Choice | Cost | Benefit | Note |
|---|---|---|---|
| Whole-file encode | Long latency, one machine | Simple; best rate control across the file | Fine for small catalogues |
| Per-chunk parallel encode | Chunk boundaries, scheduling | Latency bounded by chunk time; retry granularity | inference for YouTube |
| Never upscale | None | Saves compute and bytes | Rungs above source height dropped |
| Codec per popularity | Two-tier pipeline | Expensive codecs only where views pay back | inference |
Fix / how to use it: transcode.Split, transcode.Plan and transcode.Run in Go and the Bus::batch fan-out in Laravel. Worker pools and queues: Competing Consumers, Durable Workflows & Jobs.
Codecs and the Argos VCU ASIC Must-know
In plain words: Newer codecs (VP9, AV1) make files smaller for the same quality but cost much more CPU to encode. YouTube built its own chip, the Video (trans)Coding Unit, to pay that cost.
Common misunderstanding: "Hardware encoders are only for live or consumer devices." The ASPLOS 2021 paper is about "warehouse-scale video transcoding" in data centres, evaluated "in the wild" on live data-centre jobs.
Definition: H.264 is the legacy codec; VP9 (Google) and AV1 (Alliance for Open Media) compress more efficiently. The YouTube blog says VP9 looks better than H.264 "but it uses 5x more computer resources to encode", and that the next-generation chip adds "AV1, a new advanced coding standard that compresses more efficiently than VP9". Argos is the name of the VCU project in the ASPLOS 2021 paper Warehouse-Scale Video Acceleration: Co-design and Deployment in the Wild. A VCU is an ASIC (application-specific integrated circuit) for video encoding and decoding, deployed in data-centre machines.
2015 project kicked off: demand for 1080p/4K/8K + codecs that cost more to encode
2015+ simulate the chip in software and emulation hardware before tape-out
2020 pandemic: watch time +25% in Q1, daily livestreams +45% in H1, VCUs absorb it
2021 ASPLOS paper + blog: 20-33x compute efficiency vs prior optimized software
next next-generation chip adds AV1 encodingReal scenario: a sudden traffic surge without waiting for CPU capacity (the pandemic example in the blog); offering VP9 or AV1 widely because encode cost dropped; changing bottlenecks handled by the "balanced systems" the paper describes.
| Codec | Compression | Encode cost | Where it shows up on YouTube (cited) |
|---|---|---|---|
| H.264 | Baseline | Lowest | Legacy comparison in the 2021 blog; live ingest over RTMP/RTMPS |
| HEVC (H.265) | Better than H.264 | Higher | Live ingest over HLS, HDR live |
| VP9 | Better than H.264 | "5x" H.264 | Playback; DASH live ingest |
| AV1 | Better than VP9 | Higher still | Next-gen VCU; recommended for ultra-low-latency live ingest |
Fix / how to use it: you will not build an ASIC. The copyable lesson is the economic one: when a workload is large, stable and compute-bound, measure cost per output minute and consider specialised hardware (GPU encoders, cloud transcoding services) before adding CPUs (inference).
Storage: Colossus, Bigtable, Spanner and Vitess Must-know
In plain words: Video bytes go into Google's cluster file system; small structured data (video rows, channels) went into MySQL that YouTube sharded with its own proxy, Vitess; Google's other databases sit underneath many services.
Common misunderstanding: "YouTube moved everything to Spanner." No saved source says so. The sources say: Colossus supports "globally available services like YouTube, Drive, and Gmail"; Vitess was built for YouTube's MySQL; the Procella paper names Bigtable and Spanner as its metadata store. Anything beyond that is inference.
Definition: Colossus is Google's "cluster-level file system, successor to the Google File System (GFS)"; its metadata lives in Bigtable and "a single cluster is scalable to exabytes of storage". Bigtable is Google's wide-column NoSQL store; Spanner is "our globally-consistent, scalable relational database" (both phrases from the Colossus post). Vitess is a proxy layer that routes queries to MySQL shards so that the application no longer contains shard logic.
vitess.io history, as a sequence:
1 one MySQL primary -> peak traffic near capacity
2 primary for writes + replica for reads -> reads overload the replica
3 more replicas -> writes overload the primary
4 shard; app code picks the shard per query -> shard logic everywhere in the app
5 Vitess proxy between app and MySQL -> app talks to one endpoint; Vitess routes
6 2018 CNCF incubation, 2019 graduationReal scenario: video rows and channel rows (sharded MySQL, historically); upload originals and renditions (Colossus, which the post shows serving "YouTube serving nodes"); Procella's data in Colossus with metadata in Bigtable and Spanner; the Procella paper also says Vitess was used "for embedded statistics in pages" before Procella.
| Data | Store named in a YouTube/Google source | Generic equivalent |
|---|---|---|
| Video bytes, segments | Colossus | S3, GCS, HDFS |
| Video, channel, user rows | MySQL sharded with Vitess | PostgreSQL + Citus, MySQL + Vitess/PlanetScale |
| File system metadata | Bigtable (under Colossus) | Wide-column store |
| Global consistent metadata | Spanner (Google storage services, Procella metadata) | CockroachDB, Spanner |
| Analytics and counters | Procella (with Dremel, Mesa, Monarch earlier) | ClickHouse, Druid, Pinot |
Fix / how to use it: follow the vitess.io ladder in order and stop at the first rung that fits; see Sharding at System Level, Partitioning & Sharding in PostgreSQL and the SQL schema on this page.
Delivery: Google Global Cache, edge nodes, adaptive bitrate, DASH, HLS and QUIC Must-know
In plain words: Popular segments are cached inside the viewer's ISP. The player downloads a few seconds at a time and picks the quality the network can carry right now. Google's own transport, QUIC, cut rebuffering.
Common misunderstanding: "YouTube uses a third-party CDN." Google operates its own cache nodes: Google Global Cache "allows ISPs to serve certain Google content from within their own networks", with Google providing the hardware and running it remotely.
Definition: A GGC node (an edge node inside an ISP) caches Google content; "Typically between 70-90% of cacheable traffic can be served from GGC". Adaptive bitrate (ABR) streaming cuts each rendition into segments listed in a manifest; DASH (MPEG-DASH) and HLS (Apple HTTP Live Streaming) are the two manifest/segment formats (packaging details: CDNs). QUIC is the UDP-based transport that became HTTP/3; the SIGCOMM 2017 paper says QUIC "reduces rebuffer rates of YouTube playbacks by 18.0% for desktop users and 15.3% for mobile users" and accounted for "over 30% of Google's total egress traffic in bytes".
1 player -> fetch manifest (DASH MPD or HLS playlist)
2 player -> GET segment 1 at 360p from nearest node (GGC in ISP, else Google edge)
3 throughput high, buffer healthy -> switch up to 1080p for segment 4
4 bus enters tunnel, buffer drains -> switch down to 240p
5 rebuffer rate = rebuffer time / (rebuffer time + play time) (QUIC paper definition)Real scenario: an ISP that hosts a GGC node to reduce transit cost; a mobile viewer switching between Wi-Fi and cellular; a smart TV choosing VP9 or AV1 when hardware decoding exists (inference); a live event where everyone requests the same segment at once (CDNs covers request coalescing).
| Layer | YouTube/Google element (cited) | Generic equivalent |
|---|---|---|
| Cache inside ISP | Google Global Cache node | Netflix Open Connect, ISP-embedded CDN appliances |
| Edge and backbone | Google front-end servers running QUIC | CDN PoPs |
| Transport | QUIC (rebuffer rate down 15–18%) | HTTP/3 |
| Format | DASH, HLS | Same |
| Player logic | ABR on buffer and throughput (inference for algorithm details) | dash.js, hls.js, ExoPlayer |
Fix / how to use it: for your system, a commercial CDN with origin shield plus HLS/CMAF packaging gets most of the benefit; see CDNs, HTTP/1.1, HTTP/2, HTTP/3 and TCP & UDP.
Metadata and search Important
In plain words: Titles, descriptions, tags, captions and channel data make a video findable; search ranks them against a query.
Common misunderstanding: "YouTube search is a SQL LIKE over titles." Nothing in YouTube's saved sources describes the search stack. The Covington paper only says that "metadata associated with content is poorly structured without a well defined ontology" and that search query tokens are features for recommendations. The rest of this block is inference.
Definition: Metadata is everything about a video except its bytes: the snippet (title, description, tags, category) and status parts sent in the upload request, plus derived data (duration, resolution, captions, policy status). Search indexes that metadata (and, inference, derived signals such as captions and engagement) into an inverted index and ranks with learned models.
1 upload POST carries snippet {title, description, tags, categoryId} + status
2 pipeline adds duration, resolutions, captions (inference)
3 indexer writes terms -> inverted index shards (inference)
4 query -> retrieve candidates -> rank -> filter by policy and region (inference)Real scenario: a newly uploaded tutorial that must be searchable within minutes; a takedown that must vanish from results everywhere; spelling variants and multiple languages (YouTube is localised in "over 100 countries", press page).
| Concern | Cited fact | inference |
|---|---|---|
| Metadata shape | Upload API snippet/status parts | Stored in sharded MySQL historically (Vitess) |
| Search as a signal | Search query tokens feed candidate generation (Covington) | Search and recs share embeddings |
| Freshness | "many hours of video are uploaded per second" (Covington) | Near-real-time indexing |
| Ranking | Not documented in saved sources | Learned ranking like Search Systems |
Fix / how to use it: Elasticsearch or OpenSearch with BM25 plus a learned re-ranker is the copyable pattern (Search Systems, Full-Text Search).
Recommendations: candidate generation and ranking Must-know
In plain words: First narrow millions of videos to a few hundred that might fit you, cheaply. Then score those few hundred carefully and show the best dozens.
Common misunderstanding: "Recommendations optimise clicks." Covington et al.: "Ranking by click-through rate often promotes deceptive videos that the user does not complete (“clickbait”) whereas watch time better captures engagement"; the YouTube blog adds that switching to watch time in 2012 caused "an immediate 20% drop in views", accepted on purpose.
Definition: The 2016 system "is comprised of two neural networks: one for candidate generation and one for ranking". Candidate generation treats recommendation as extreme multiclass classification over videos with a softmax, learns user and video embeddings, and at serving time reduces to "a nearest neighbor search in the dot product space" under "a strict serving latency of tens of milliseconds". Ranking is a deep neural network with rich features whose objective "is generally a simple function of expected watch time per impression". The models "learn approximately one billion parameters and are trained on hundreds of billions of examples". Later work (RecSys 2019) uses Multi-gate Mixture-of-Experts for multiple ranking objectives and a sampling-bias-corrected two-tower model for retrieval; the 2021 blog adds survey-based "valued watchtime" and demotion of borderline content.
1 request: user history (watches, searches), context, demographics
2 candidate generation DNN -> user embedding u
3 ANN lookup over video embeddings v_j by dot product -> hundreds of candidates
4 blend other candidate sources (the paper allows this)
5 ranking DNN scores each impression -> expected watch time
6 sort, apply policy (borderline demotion, 2019+), return dozens
7 evaluate offline (precision, recall, ranking loss), decide by live A/B testsReal scenario: the home page; the "Up Next" panel (the two surfaces named in the 2021 blog); a new upload that must get impressions despite no history (the paper's "Example Age" feature addresses freshness); a news topic where authoritative sources are promoted.
| Stage | Input size | Output size | Model (cited) | Latency budget |
|---|---|---|---|---|
| Candidate generation | millions | hundreds | DNN + sampled softmax, ANN at serving | tens of ms (cited) |
| Other sources | varies | some | e.g. earlier related-video work | inference |
| Ranking | hundreds | dozens | DNN, weighted logistic regression for watch time | inference |
| Multitask ranking (2019) | hundreds | dozens | MMoE + shallow tower for selection bias | not stated |
| Responsibility layer (2019+) | ranked list | filtered list | classifiers for borderline/authoritative | not stated |
Fix / how to use it: copy the two-stage shape, not the model: retrieval by embeddings in a vector index (Vector Search & pgvector), then a ranker (ML Systems); measure watch time or another satisfaction metric, not clicks (Feeds uses the same funnel).
View counting, Procella and the 301+ story Must-know
In plain words: Counting plays is easy; counting plays that are real is hard. YouTube shows a count that is checked first, and it serves that number to millions of pages per second.
Common misunderstanding: "A frozen count is a bug." YouTube Help: "To verify that metrics are accurate, we may temporarily slow down, freeze, or change your metric count, and discard low-quality playbacks", and "Using several devices to watch the same video and streaming the same video across several windows and tabs are examples of low-quality playbacks."
Definition: Two separate problems. Validation: turning raw play events into accepted views (YouTube's rule since November 2026 per the help page: "Views are counted the moment a video starts to play", plus co-view estimates on TVs, then verification). Serving: the Procella paper says it "powers various embedded statistical counters, such as views, likes, and subscriptions, on high traffic pages", the logical query is SELECT SUM(views) FROM Table WHERE video_id = N, and "each Procella instance needs to be able to serve over a million QPS of such queries with millisecond latency"; before Procella, "Vitess [25] for embedded statistics in pages".
The 301+ story. Many engineers remember view counts that stuck at "301+" for new popular videos in the early 2010s while views were checked. No YouTube-authored source for the exact number was found and saved for this page, so treat the number and its era as inference (folklore). The documented fact is the general rule above: counts may be frozen while verified. Similarly, press coverage in December 2014 reported that Gangnam Style exceeded a signed 32-bit counter (2,147,483,647); the original YouTube social-media post is offline and not quoted here. The lesson for designers is plain: use 64-bit counters.
1 play starts on 3 tabs of one browser + a TV in a living room
2 raw events -> event log (high rate, append only) (inference)
3 dedupe + fraud model: tabs collapse, bots discarded (help page: "discard low-quality playbacks")
4 accepted delta -> stats store, near real time (Procella "stats serving" mode)
5 watch page -> SUM(views) WHERE video_id = N (> 1M QPS per instance, ms latency)
6 public number moves; may lag or be adjusted later (help page)Real scenario: a music premiere with a hot key (one video, millions of increments per second); a bot farm buying views (blocked by validation and the spam policy); an advertiser billing on TrueView views, which have their own rules (the help page lists e.g. "at least 30 seconds of an ad that's more than 30 seconds long").
| Problem | Naive design | YouTube (cited) | Copyable fix |
|---|---|---|---|
| Hot counter writes | UPDATE videos SET views = views + 1 | Not documented | Sharded counters, buffered increments (Write Buffering) |
| Fake views | Count every play | Verify, freeze, discard low-quality playbacks | Validation stage before publish |
| Counter reads | Read primary row | Procella stats serving, data preloaded in memory | Cache the sum for seconds |
| Overflow | int (32-bit) | 64-bit (press coverage, inference) | bigint |
| Many metrics | One system each | Procella unifies dashboards, counters, monitoring, ad hoc | One OLAP engine with a serving mode |
Fix / how to use it: views.Counter in Go and view_count_shards in the SQL schema; top lists from these counts: Top-K & Heavy Hitters.
Comments and live chat Important
In plain words: Comments are threaded, stored, moderated text under a video. Live chat is a fast stream of short messages tied to a live broadcast, with tools to slow it down.
Common misunderstanding: "Live chat is comments on a timer." YouTube Help describes chat-specific controls: slow mode (a wait between messages per user), subscribers-only chat with a minimum subscription age, members-only chat, approved-users-only chat, moderators and held messages. These shape the design (per-user rate limits, membership checks on the write path). The storage and transport behind comments and chat are not described in the saved sources: inference.
Definition: Comments: persistent, paginated, ranked, moderated. Live chat: a realtime fan-out of messages to all viewers of a stream; the latency page notes low latency matters "If you live chat with viewers".
1 viewer posts chat message -> write API: auth, membership/subscription check, slow-mode rate limit
2 spam/abuse classifier (spam policy covers "live chats") (inference for placement)
3 message appended to the stream's chat log (inference)
4 fan-out to connected viewers (long polling / WebSocket) (inference)
5 moderator holds or removes -> removal event fans out too (inference)Real scenario: a premiere with tens of thousands of messages per minute (slow mode); a creator who allows only subscribers of 10 minutes or more; a comment section held for review; identical "check out my channel" comments across hundreds of videos (named as comment spam in the policy).
| Feature (cited from YouTube Help) | What it means for the design |
|---|---|
| Slow mode | Per-user token bucket on the write path (Rate Limiting) |
| Subscribers-only, with minimum duration | Subscription lookup with timestamp on every write |
| Members-only chat | Entitlement check; cannot combine with subscribers-only |
| Approved users (live commentary) | Allow-list per stream |
| Moderators, hold for review | Moderation queue and removal events |
| AI-generated chat summary for new viewers | Async summariser over the chat log (inference for mechanics) |
Fix / how to use it: use Real-Time Communication for transport (Laravel Reverb or a Go WebSocket hub), a per-user limiter, and a message log per stream; comments are a normal sharded table with keyset pagination (Pagination).
Live streaming: ingest, low latency and DVR Must-know
In plain words: A broadcaster's encoder pushes video to YouTube; YouTube transcodes it live into many qualities, cuts segments and serves them with a delay that the creator chooses; viewers can pause and rewind.
Common misunderstanding: "Live needs a special protocol all the way to the viewer." Ingest uses RTMP/RTMPS or segment-based HLS/DASH; YouTube then transcodes "to create many different output formats"; the player's read-ahead buffer is "the main source of stream latency". And SRT: YouTube's official ingestion comparison page (fetched November 2026) lists RTMP, RTMPS, HLS and DASH only, so SRT is not a documented YouTube ingest protocol on that page; SRT is common in contribution links elsewhere (inference for any YouTube use).
Definition: RTMP (Real-Time Messaging Protocol) and RTMPS (RTMP over TLS) carry H.264 and are "Suitable for normal, low, or ultra-low latency live streaming". HLS ingest sends M2TS Media Segments of "between one and four seconds" plus Media Playlists by HTTP PUT or POST, with a backup URL (b.upload.youtube.com, copy=1); HLS (HEVC) and DASH (VP9) ingest are better for 4K and HDR but "Not suitable for ultra-low latency". Latency modes: Normal (highest quality), Low latency (most viewers under 10 s, no 4K), Ultra-low latency (most viewers under 5 s, no 4K). DVR lets viewers "pause, rewind, and continue", but may be limited for streams "longer than 12 hours", and viewers "can never seek back to before you went live".
1 encoder (keyframe every 2 s, CBR, H.264/HEVC/AV1) -> rtmps ingest, backup ingest
2 live transcode -> ladder renditions every segment
3 segments + sliding playlist -> edge caches
4 player keeps read-ahead buffer: Normal (largest) > Low (< 10 s) > Ultra-low (< 5 s)
5 viewer pauses -> DVR window keeps segments -> resumes where paused
6 stream ends -> recording becomes a regular videoReal scenario: a concert in 4K (Normal latency, HLS/HEVC ingest); a Q&A with chat (Ultra-low latency over RTMPS); a 24-hour charity stream (DVR limits past 12 hours); a creator with flaky upload bandwidth (low latency modes suffer first: "live ingestion issues on your network will affect viewers more").
| Ingest protocol (cited) | Encrypted | Video codecs | Latency suitability |
|---|---|---|---|
| RTMP | No | H.264 | Normal, low, ultra-low |
| RTMPS | Yes | H.264 | Normal, low, ultra-low |
| HLS | Yes | H.264, HEVC | Not ultra-low; 4K, HDR |
| DASH | Yes | H.264, VP9 | Not ultra-low; 4K |
| Encoder setting (cited, YouTube Help) | Value |
|---|---|
| Keyframe frequency | Recommended 2 seconds; do not exceed 4 seconds |
| Bitrate encoding | CBR |
| 1080p60 recommended bitrate | 12 Mbit/s (AV1/H.265), 17 Mbit/s (H.264) |
| 4K60 recommended bitrate | 35 Mbit/s (AV1/H.265), 50 Mbit/s (H.264) |
| Audio | AAC or MP3; 128 kbit/s stereo |
Fix / how to use it: for your own product, ingest RTMP(S) into a media server (NGINX RTMP module, SRS, MediaMTX, or a cloud service like AWS Elemental MediaLive), package low-latency HLS (CDNs: Low-latency HLS), and keep chat on a separate realtime channel.
Content ID: copyright fingerprinting Important
In plain words: Rights holders give YouTube reference files; every upload is compared against them; a match produces a claim that blocks, monetizes or tracks the video, possibly differently per country.
Common misunderstanding: "Content ID is a takedown tool everyone can use." It "is available to copyright owners who meet specific criteria": they "must own exclusive rights to a substantial body of original material that is frequently uploaded", and claimants who repeatedly make erroneous claims can lose access.
Definition: "Using a database of audio and visual files submitted by copyright owners, Content ID identifies matches of copyright-protected content. When a video is uploaded to YouTube, it's automatically scanned by Content ID." Claim actions: "Blocks a video from being viewed", "Monetizes the video by running ads against it and sometimes sharing revenue with the uploader", "Tracks the video’s viewership statistics"; "any of these actions can be geography-specific". The matching technique (fingerprinting: compact perceptual signatures of audio and video that survive re-encoding) is not detailed on the help page: inference.
1 rights holder uploads reference -> fingerprints stored (fingerprint step: inference)
2 creator upload -> pipeline computes fingerprints of the new video (inference)
3 lookup against reference index -> match segments (inference)
4 claim created -> owner policy per country: block | monetize | track (cited)
5 dispute -> review; misuse -> claimant loses Content ID access (cited)Real scenario: a vlog with background music (monetized for the label); a full movie re-upload (blocked); a mirrored TV episode uploaded "to avoid detection" (named in the spam policy as detection evasion); a song monetized in one country and blocked in another.
| Aspect | Cited | inference |
|---|---|---|
| When | Every upload is scanned automatically | Also on later reference additions (rescans) |
| Against what | Audio and visual reference files from owners | Fingerprint index sharded by hash |
| Result | Claim with block / monetize / track, per geography | Policy evaluated at playback time per country |
| Who | Owners meeting eligibility criteria | — |
| Abuse of the tool | Erroneous claimants lose access | — |
Fix / how to use it: for smaller platforms, perceptual hashing (pHash for images, audio fingerprint libraries such as Chromaprint) plus a nearest-neighbour index; store claims as data with per-country policy, evaluated at serve time (inference).
Abuse and spam Important
In plain words: An open upload site attracts spam comments, fake engagement, scams and re-uploads disguised to dodge detection. The policy names them; the systems must detect them at scale.
Common misunderstanding: "Abuse is a moderation team problem." The policy itself describes technical behaviours (bots, templated mass production, "speeding up audio, heavy filters, cropping" to evade detection), and the view-count rules discard low-quality playbacks automatically. Abuse is a pipeline stage.
Definition: YouTube's Spam, deceptive practices and scams policy prohibits "content, metadata, or behavior designed to take advantage of the YouTube community", including engagement manipulation, fake engagement, comment spam ("high-volume, repetitive, or deceptive comments, live chats"), off-platform diversion, detection evasion, automated mass production, scraped content, scams and malicious clickbait. It applies to "unlisted and private content, comments, links, posts and thumbnails, and coordinated networks of channels". The 2021 recommendations post adds classifiers for borderline content trained from human evaluators.
1 write path: upload | comment | chat | like | view
2 synchronous cheap checks: rate limits, account age, known-bad links (inference)
3 asynchronous classifiers: spam, scams, borderline (2021 blog: classifiers + human raters)
4 actions: remove, hold, demote in recommendations, discard engagement (cited categories)
5 appeals and human review (inference for flow)Real scenario: a bot network buying likes (fake engagement, discarded); "free unreleased movie" videos with malware links (off-platform diversion); a channel network re-uploading clips without changes (scraped content); a borderline conspiracy video demoted (2019 change: "a 70% drop in watchtime on non-subscribed, recommended borderline content in the U.S.").
| Abuse type (policy name) | Where it hits | Defence that fits (copyable) |
|---|---|---|
| Engagement manipulation, fake engagement | Views, likes, subscriptions | Validation before publishing counts |
| Comment spam | Comments, live chat | Per-user rate limits, duplicate detection |
| Detection evasion | Upload pipeline | Robust fingerprints (Content ID) |
| Automated mass production, scraped content | Uploads, recommendations | Near-duplicate detection, demotion |
| Scams, off-platform diversion | Links in descriptions | URL reputation, link scanning |
| Malicious clickbait | Recommendations | Rank for watch time and satisfaction, not CTR |
Fix / how to use it: put rate limits (Rate Limiting) and idempotency on every write path, delay public counters until validated, and treat moderation actions as events that fan out (Event-Driven Architecture).
Step 4 · Decisions and their trade-offs Must-know
In plain words: The interesting part of a case study is why: which costs YouTube chose to pay and which it refused.
Common misunderstanding: "Big companies just buy more servers." The 2021 blog describes a decision to build a chip because CPUs were "pretty inefficient, especially as you add more and more videos"; Vitess was built because replicas and app-level sharding stopped being enough.
Definition: A decision is a choice with a named cost. Each row below cites the source of the choice; the "cost" column is partly inference.
1 bytes on every view >> compute once per upload -> encode more, better codecs
2 better codecs cost 5x encode -> build VCU (2015-2021)
3 transit and distance cost -> caches inside ISPs (GGC)
4 TCP head-of-line, slow handshakes -> QUIC
5 MySQL limits -> shard, then Vitess (2010)
6 clicks reward clickbait -> rank for watch time (2012)
7 fake views erode trust -> verify before showing countsReal scenario: a startup that wants to know which of these to copy (see What you can copy); an interview that asks "design YouTube" (walk these seven rows); a finance review asking why encode spend went up after a codec launch.
| Decision | Source | Cost paid | Alternative refused |
|---|---|---|---|
| Custom VCU ASIC | ASPLOS 2021, YouTube blog | Multi-year hardware risk ("getting it right the first time") | Keep scaling CPU fleets |
| VP9, then AV1 | YouTube blog 2021 | 5x encode cost for VP9; more for AV1 | Stay on H.264 |
| Caches in ISPs | GGC help | Hardware and remote operations at many ISPs | Serve only from Google sites |
| QUIC | SIGCOMM 2017 | A new transport to build and maintain | TCP + TLS only |
| Vitess on MySQL | vitess.io | A proxy layer and sharding discipline | App-level shard routing everywhere |
| Watch-time objective | Covington 2016, YouTube blog 2021 | "immediate 20% drop in views" | Click-through rate |
| Verified counts | YouTube Help | Counts that lag or freeze | Real-time raw counts |
| Unified analytics (Procella) | VLDB 2019 | Building a new SQL engine | Separate Dremel, Mesa, Bigtable, Monarch, Vitess silos |
Fix / how to use it: in your own design review, write the "alternative refused" column explicitly; it is what makes a decision reviewable (Architecture Decisions).
What changed over time
| Year | Change | Source (saved) |
|---|---|---|
| 2007 (published 2012) | YouTube Scalability talk, Seattle Conference on Scalability | YouTube video page (title and upload date only) |
| 2008 | Recommendation system started; before it, one popularity "Trending" page | YouTube blog, 2021 |
| 2010 | Vitess created for YouTube's MySQL scaling | vitess.io history |
| 2011 | Learned clicks do not mean watching; classifiers keep racy/violent videos out of recommendations | YouTube blog, 2021 |
| 2012 | Watch time added to recommendations | YouTube blog, 2021 |
| 2015 | QUIC: about half of Chrome requests to Google; 30% fewer YouTube rebuffers reported | Chromium blog, April 2015 |
| 2015 | VCU project started | YouTube blog, 2021 |
| 2016 | Deep neural network candidate generation + ranking | Covington et al., RecSys 2016 |
| 2017 | QUIC paper: YouTube rebuffer rate down 18.0% desktop, 15.3% mobile | SIGCOMM 2017 |
| 2018–2019 | Vitess CNCF incubation (Feb 2018), graduation (Nov 2019) | vitess.io history |
| 2019 | Procella; multitask ranking (MMoE); two-tower retrieval; borderline demotion | VLDB 2019, RecSys 2019, YouTube blog 2021 |
| 2020 | Pandemic surge: watch time +25% in Q1, daily livestreams +45% in H1 | YouTube blog, 2021 |
| 2021 | Argos VCU paper and blog; next-gen chip adds AV1; Colossus post | ASPLOS 2021, YouTube blog, Google Cloud blog |
| 2026 | 20 million videos/day; 200 billion daily Shorts views; co-views counted on TVs from November 2026 | YouTube press page, YouTube Help |
What you can copy
Each subsystem maps to a generic chapter. YouTube's specific technology is in the middle column; what a normal team builds is on the right.
| Subsystem | YouTube (cited) | What you build | Read |
|---|---|---|---|
| Upload | Resumable protocol, 308, 256 KB chunks | tus or S3 multipart with presigned parts; same status semantics | Object Storage, API Idempotency |
| Transcoding | VCU ASIC, VP9/AV1 | FFmpeg workers or a cloud transcoder, chunk × rung queue | Competing Consumers, Durable Workflows |
| File storage | Colossus | S3/GCS with lifecycle tiers | Object Storage |
| Metadata | MySQL + Vitess | PostgreSQL, then partitioning/Citus, or MySQL + Vitess | Sharding at System Level |
| Delivery | GGC, QUIC, DASH/HLS | Commercial CDN, HTTP/3, HLS/CMAF | CDNs, HTTP evolution |
| Search | Not documented | Elasticsearch/OpenSearch + re-ranker | Search Systems |
| Recommendations | Two-stage DNN | Embeddings + ANN + ranker | ML Systems, Vector Search |
| View counts | Validation + Procella | Event log, sharded counters, cached sums | Write Buffering & Sharded Counters, Top-K |
| Comments, live chat | Slow mode, moderators | Sharded table + WebSocket fan-out + limiter | Real-Time Communication, Rate Limiting |
| Live | RTMPS/HLS ingest, latency modes, DVR | Media server + LL-HLS + CDN | CDNs |
| Content ID | Reference fingerprint matching | Perceptual hashes + ANN index | Bloom Filters & Probabilistic Structures for the indexing mindset |
| Abuse | Policy + classifiers | Rate limits, reputation, async classifiers | Load Shedding, OWASP Top 10 |
Mechanics
Resumable upload knobs and codes
| Item | Value (YouTube Data API guide) |
|---|---|
| Start URL | POST https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=... |
| Required headers on start | Authorization, Content-Type: application/json; charset=UTF-8, X-Upload-Content-Length, X-Upload-Content-Type (video/* or application/octet-stream) |
| Session URI | Location header of the 200 response |
| Status query | PUT with Content-Length: 0 and Content-Range: bytes */TOTAL |
| Progress response | 308 Resume Incomplete, Range: bytes=0-N (absent if nothing received) |
| Resumable errors | 500, 502, 503, 504, or a lost connection |
| Session expired | 404 Not Found |
| Chunk size | Multiple of 256 KB (262,144 bytes), same for every chunk except the last |
| Non-contiguous block | Rejected silently: nothing uploaded |
Live streaming knobs
| Item | Value (YouTube Help / Live Streaming API docs) |
|---|---|
| Latency modes | Normal; Low latency (most viewers < 10 s); Ultra-low latency (most viewers < 5 s) |
| 4K with low latency | Not supported; 4K streams use normal latency |
| Keyframe interval | 2 s recommended, never above 4 s |
| HLS ingest segment duration | 1 to 4 seconds, M2TS, H.264 or HEVC, AAC single track |
| HLS backup ingest | b.upload.youtube.com with copy=1 |
| DVR limit | May be limited or unavailable past 12 hours; never before the stream start |
| DVR toggle mid-stream | Applies only to viewers who start after the change |
Recommendation model facts
| Item | Value (Covington et al. 2016) |
|---|---|
| Candidate output | Hundreds of videos |
| Training trick | Sampled softmax: "several thousand negatives", "more than 100 times speedup" |
| Serving | Approximate nearest neighbour in dot-product space, tens of ms |
| Ranking objective | Expected watch time per impression (weighted logistic regression) |
| Model size | About one billion parameters, hundreds of billions of examples |
| Decision rule | Offline metrics guide; live A/B tests decide |
Error and status vocabulary
| Code or message | Where | Meaning |
|---|---|---|
308 Resume Incomplete | Upload API | Bytes so far in Range; keep sending |
201 Created | Upload API | Upload complete; body is the video resource |
404 Not Found | Upload API | Session URI expired |
Retry-After | Upload API | Wait before resuming |
| Content ID claim | YouTube Studio | Match found; owner policy applied |
| Frozen or slowed count | Watch page | Metrics being verified |
Go
These are small, honest re-implementations of three mechanisms described above. They are not YouTube's code. All three packages build with the standard library only and are tested (go test ./...).
Example: a resumable upload server
Implements the documented rules: session start with X-Upload-Content-Length, 308 with Range, bytes */TOTAL status queries, 256 KB chunk multiples, "nothing uploaded" on gaps or overlaps, 404 on expiry.
// Package resumable is a small, single-process re-implementation of the
// resumable upload protocol documented for the YouTube Data API
// (POST to start a session, PUT with Content-Range, 308 Resume Incomplete).
// It is a teaching model, not YouTube's code: sessions live in memory and
// bytes are kept in a byte slice.
package resumable
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
// ChunkMultiple mirrors the documented rule: every chunk except the last
// must be a multiple of 256 KB.
const ChunkMultiple = 256 * 1024
// StatusResumeIncomplete is HTTP 308 as used by the protocol.
const StatusResumeIncomplete = 308
type session struct {
total int64
data []byte
done bool
expires time.Time
}
// Server holds upload sessions. Now and TTL are injectable for tests.
type Server struct {
mu sync.Mutex
sessions map[string]*session
TTL time.Duration
Now func() time.Time
// OnComplete is called once with the full file when the last byte arrives.
OnComplete func(id string, file []byte)
}
// NewServer returns a server whose sessions expire after ttl.
func NewServer(ttl time.Duration) *Server {
return &Server{sessions: map[string]*session{}, TTL: ttl, Now: time.Now}
}
func newID() string {
b := make([]byte, 12)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// ServeHTTP routes POST /upload (start) and PUT /upload/{id} (bytes or status).
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && r.URL.Path == "/upload":
s.start(w, r)
case r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, "/upload/"):
s.put(w, r, strings.TrimPrefix(r.URL.Path, "/upload/"))
default:
http.Error(w, "not found", http.StatusNotFound)
}
}
func (s *Server) start(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("uploadType") != "resumable" {
http.Error(w, "uploadType=resumable required", http.StatusBadRequest)
return
}
total, err := strconv.ParseInt(r.Header.Get("X-Upload-Content-Length"), 10, 64)
if err != nil || total <= 0 {
http.Error(w, "X-Upload-Content-Length required", http.StatusBadRequest)
return
}
id := newID()
s.mu.Lock()
s.sessions[id] = &session{total: total, expires: s.Now().Add(s.TTL)}
s.mu.Unlock()
w.Header().Set("Location", "/upload/"+id)
w.WriteHeader(http.StatusOK)
}
// parseRange reads "bytes first-last/total" or "bytes */total".
func parseRange(h string) (first, last, total int64, query bool, err error) {
v, ok := strings.CutPrefix(h, "bytes ")
if !ok {
return 0, 0, 0, false, fmt.Errorf("bad Content-Range %q", h)
}
span, tot, ok := strings.Cut(v, "/")
if !ok {
return 0, 0, 0, false, fmt.Errorf("bad Content-Range %q", h)
}
if total, err = strconv.ParseInt(tot, 10, 64); err != nil {
return 0, 0, 0, false, err
}
if span == "*" {
return 0, 0, total, true, nil
}
a, b, ok := strings.Cut(span, "-")
if !ok {
return 0, 0, 0, false, fmt.Errorf("bad span %q", span)
}
if first, err = strconv.ParseInt(a, 10, 64); err != nil {
return
}
if last, err = strconv.ParseInt(b, 10, 64); err != nil {
return
}
if last < first {
err = fmt.Errorf("last < first")
}
return
}
func writeIncomplete(w http.ResponseWriter, received int64) {
if received > 0 {
w.Header().Set("Range", fmt.Sprintf("bytes=0-%d", received-1))
}
w.WriteHeader(StatusResumeIncomplete)
}
func (s *Server) put(w http.ResponseWriter, r *http.Request, id string) {
first, last, total, query, err := parseRange(r.Header.Get("Content-Range"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
// A broken connection: the client will ask for status and resume.
return
}
s.mu.Lock()
defer s.mu.Unlock()
sess, ok := s.sessions[id]
if !ok || s.Now().After(sess.expires) {
delete(s.sessions, id)
http.Error(w, "session expired", http.StatusNotFound)
return
}
if total != sess.total {
http.Error(w, "total length changed", http.StatusBadRequest)
return
}
received := int64(len(sess.data))
if sess.done {
w.WriteHeader(http.StatusCreated)
return
}
if query {
writeIncomplete(w, received)
return
}
isLast := last == total-1
if int64(len(body)) != last-first+1 || (!isLast && len(body)%ChunkMultiple != 0) {
http.Error(w, "chunk size must match the range and be a multiple of 256 KB", http.StatusBadRequest)
return
}
// The documented rule: an overlapping or skipping block uploads nothing.
if first != received {
writeIncomplete(w, received)
return
}
sess.data = append(sess.data, body...)
if int64(len(sess.data)) == total {
sess.done = true
if s.OnComplete != nil {
s.OnComplete(id, sess.data)
}
w.WriteHeader(http.StatusCreated)
return
}
writeIncomplete(w, int64(len(sess.data)))
}package resumable
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func startSession(t *testing.T, srv *httptest.Server, total int) string {
t.Helper()
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/upload?uploadType=resumable", nil)
req.Header.Set("X-Upload-Content-Length", fmt.Sprint(total))
res, err := http.DefaultClient.Do(req)
if err != nil || res.StatusCode != http.StatusOK {
t.Fatalf("start: %v %v", err, res)
}
return res.Header.Get("Location")
}
func put(t *testing.T, srv *httptest.Server, loc string, body []byte, cr string) *http.Response {
t.Helper()
req, _ := http.NewRequest(http.MethodPut, srv.URL+loc, bytes.NewReader(body))
req.Header.Set("Content-Range", cr)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
return res
}
func TestChunkedUploadAndResume(t *testing.T) {
const total = 2*ChunkMultiple + 1000
file := bytes.Repeat([]byte("v"), total)
var got []byte
s := NewServer(time.Hour)
s.OnComplete = func(_ string, f []byte) { got = append([]byte(nil), f...) }
srv := httptest.NewServer(s)
defer srv.Close()
loc := startSession(t, srv, total)
res := put(t, srv, loc, file[:ChunkMultiple], fmt.Sprintf("bytes 0-%d/%d", ChunkMultiple-1, total))
if res.StatusCode != StatusResumeIncomplete || res.Header.Get("Range") != fmt.Sprintf("bytes=0-%d", ChunkMultiple-1) {
t.Fatalf("first chunk: %d %q", res.StatusCode, res.Header.Get("Range"))
}
// Status query after a "dropped connection".
res = put(t, srv, loc, nil, fmt.Sprintf("bytes */%d", total))
if res.StatusCode != StatusResumeIncomplete {
t.Fatalf("status: %d", res.StatusCode)
}
// A skipping block uploads nothing.
res = put(t, srv, loc, file[2*ChunkMultiple:], fmt.Sprintf("bytes %d-%d/%d", 2*ChunkMultiple, total-1, total))
if res.Header.Get("Range") != fmt.Sprintf("bytes=0-%d", ChunkMultiple-1) {
t.Fatalf("skip accepted: %q", res.Header.Get("Range"))
}
res = put(t, srv, loc, file[ChunkMultiple:], fmt.Sprintf("bytes %d-%d/%d", ChunkMultiple, total-1, total))
if res.StatusCode != http.StatusCreated {
t.Fatalf("final: %d", res.StatusCode)
}
if !bytes.Equal(got, file) {
t.Fatal("file mismatch")
}
}
func TestChunkSizeRule(t *testing.T) {
s := NewServer(time.Hour)
srv := httptest.NewServer(s)
defer srv.Close()
loc := startSession(t, srv, 1_000_000)
res := put(t, srv, loc, make([]byte, 1000), "bytes 0-999/1000000")
if res.StatusCode != http.StatusBadRequest {
t.Fatalf("want 400, got %d", res.StatusCode)
}
}
func TestExpiredSession(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
s := NewServer(time.Minute)
s.Now = func() time.Time { return now }
srv := httptest.NewServer(s)
defer srv.Close()
loc := startSession(t, srv, 10)
now = now.Add(2 * time.Minute)
res := put(t, srv, loc, make([]byte, 10), "bytes 0-9/10")
if res.StatusCode != http.StatusNotFound {
t.Fatalf("want 404, got %d", res.StatusCode)
}
}Example: chunk × rung parallel transcoding
Splits a video into chunks, plans tasks for each ladder rung (never upscaling), runs them with a bounded worker pool, retries transient failures, aborts on a permanent one, and returns segments in order.
// Package transcode models a split -> parallel encode -> assemble pipeline
// for one uploaded video and an encoding ladder. Splitting a video into
// chunks and encoding them in parallel is a generic technique; it is not a
// claim about how YouTube's (or Argos VCU's) software schedules work.
package transcode
import (
"context"
"errors"
"fmt"
"sort"
"sync"
"time"
)
// Rung is one rendition of the encoding ladder.
type Rung struct {
Name string // e.g. "1080p-vp9"
Height int
Codec string // "h264", "vp9", "av1"
KbitsSec int
}
// Chunk is a time range of the source; chunks are cut at keyframes.
type Chunk struct {
Index int
Start time.Duration
End time.Duration
}
// Task is one (chunk, rung) unit of work.
type Task struct {
Chunk Chunk
Rung Rung
}
// Output is an encoded segment for one task.
type Output struct {
Task Task
Bytes int64
}
// Encoder encodes one task. Real systems call FFmpeg, a hardware encoder, etc.
type Encoder func(ctx context.Context, t Task) (Output, error)
// ErrPermanent marks a task error that must not be retried (corrupt input).
var ErrPermanent = errors.New("permanent encode failure")
// Split cuts duration into chunks of at most size (the last may be shorter).
func Split(duration, size time.Duration) []Chunk {
if size <= 0 || duration <= 0 {
return nil
}
var out []Chunk
for i, start := 0, time.Duration(0); start < duration; i, start = i+1, start+size {
end := min(start+size, duration)
out = append(out, Chunk{Index: i, Start: start, End: end})
}
return out
}
// Plan returns every (chunk, rung) task. Ladder rungs above the source height
// are dropped: upscaling wastes compute and bytes.
func Plan(chunks []Chunk, ladder []Rung, sourceHeight int) []Task {
var tasks []Task
for _, r := range ladder {
if r.Height > sourceHeight {
continue
}
for _, c := range chunks {
tasks = append(tasks, Task{Chunk: c, Rung: r})
}
}
return tasks
}
// Run encodes tasks with a bounded worker pool, retries transient errors up
// to attempts times, cancels everything on the first permanent failure and
// returns outputs grouped by rung and ordered by chunk index.
func Run(ctx context.Context, tasks []Task, workers, attempts int, enc Encoder) (map[string][]Output, error) {
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil)
jobs := make(chan Task)
var (
mu sync.Mutex
out = map[string][]Output{}
wg sync.WaitGroup
)
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for t := range jobs {
var o Output
var err error
for try := 1; try <= attempts; try++ {
if o, err = enc(ctx, t); err == nil || errors.Is(err, ErrPermanent) || ctx.Err() != nil {
break
}
}
if err != nil {
cancel(fmt.Errorf("chunk %d %s: %w", t.Chunk.Index, t.Rung.Name, err))
continue
}
mu.Lock()
out[t.Rung.Name] = append(out[t.Rung.Name], o)
mu.Unlock()
}
}()
}
feed:
for _, t := range tasks {
select {
case jobs <- t:
case <-ctx.Done():
break feed
}
}
close(jobs)
wg.Wait()
if err := context.Cause(ctx); err != nil {
return nil, err
}
for _, segs := range out {
sort.Slice(segs, func(i, j int) bool { return segs[i].Task.Chunk.Index < segs[j].Task.Chunk.Index })
}
return out, nil
}package transcode
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
)
var ladder = []Rung{
{"360p-h264", 360, "h264", 700},
{"720p-vp9", 720, "vp9", 1800},
{"1080p-vp9", 1080, "vp9", 3000},
{"2160p-av1", 2160, "av1", 12000},
}
func TestSplitAndPlan(t *testing.T) {
chunks := Split(61*time.Second, 10*time.Second)
if len(chunks) != 7 || chunks[6].End-chunks[6].Start != time.Second {
t.Fatalf("chunks: %+v", chunks)
}
tasks := Plan(chunks, ladder, 1080) // no 2160p rung for a 1080p source
if len(tasks) != 7*3 {
t.Fatalf("tasks: %d", len(tasks))
}
}
func TestRunRetriesAndOrders(t *testing.T) {
var calls atomic.Int64
enc := func(_ context.Context, tk Task) (Output, error) {
if calls.Add(1)%5 == 0 {
return Output{}, errors.New("transient: worker preempted")
}
return Output{Task: tk, Bytes: int64(tk.Rung.KbitsSec) * 125 * int64((tk.Chunk.End-tk.Chunk.Start)/time.Second)}, nil
}
tasks := Plan(Split(60*time.Second, 6*time.Second), ladder, 1080)
out, err := Run(context.Background(), tasks, 4, 3, enc)
if err != nil {
t.Fatal(err)
}
for name, segs := range out {
if len(segs) != 10 {
t.Fatalf("%s has %d segments", name, len(segs))
}
for i, s := range segs {
if s.Task.Chunk.Index != i {
t.Fatalf("%s not ordered", name)
}
}
}
}
func TestRunStopsOnPermanentError(t *testing.T) {
enc := func(_ context.Context, tk Task) (Output, error) {
if tk.Chunk.Index == 3 {
return Output{}, ErrPermanent
}
return Output{Task: tk}, nil
}
_, err := Run(context.Background(), Plan(Split(60*time.Second, 6*time.Second), ladder, 720), 2, 3, enc)
if !errors.Is(err, ErrPermanent) {
t.Fatalf("want ErrPermanent, got %v", err)
}
}Example: a validated view counter
Accepts play events into sharded counters, discards repeats from the same viewer inside a window, and moves the public number only when a validation step runs; the count is int64.
// Package views models a "count fast, publish after validation" view counter:
// raw play events are accepted at high rate into sharded in-memory counters,
// obviously low-quality repeats are discarded, and the public number is only
// moved forward by a periodic validation step. YouTube's help centre says
// counts may be slowed, frozen or adjusted while views are verified; the
// mechanism below is an illustration (inference), not YouTube's algorithm.
package views
import (
"hash/fnv"
"sync"
"time"
)
// Event is one playback start.
type Event struct {
VideoID string
ViewerID string // signed-in id or a device/cookie id
At time.Time
}
type shard struct {
mu sync.Mutex
pending map[string]int64 // video -> unvalidated views
seen map[string]time.Time
}
// Counter keeps pending counts in shards and a published count per video.
type Counter struct {
shards []*shard
repeat time.Duration // same viewer+video inside this window is discarded
mu sync.RWMutex
published map[string]int64
}
// New returns a counter with n shards.
func New(n int, repeat time.Duration) *Counter {
c := &Counter{repeat: repeat, published: map[string]int64{}}
for range n {
c.shards = append(c.shards, &shard{pending: map[string]int64{}, seen: map[string]time.Time{}})
}
return c
}
func (c *Counter) shardFor(key string) *shard {
h := fnv.New32a()
_, _ = h.Write([]byte(key))
return c.shards[h.Sum32()%uint32(len(c.shards))]
}
// Record accepts an event; it returns false when the event is discarded.
func (c *Counter) Record(e Event) bool {
key := e.VideoID + "|" + e.ViewerID
s := c.shardFor(key)
s.mu.Lock()
defer s.mu.Unlock()
if last, ok := s.seen[key]; ok && e.At.Sub(last) < c.repeat {
return false
}
s.seen[key] = e.At
s.pending[e.VideoID]++
return true
}
// Validate drains pending counts, lets accept decide how many to keep for each
// video (a fraud model in real life), and adds them to the published counts.
func (c *Counter) Validate(accept func(videoID string, pending int64) int64) {
merged := map[string]int64{}
for _, s := range c.shards {
s.mu.Lock()
for v, n := range s.pending {
merged[v] += n
}
s.pending = map[string]int64{}
s.mu.Unlock()
}
c.mu.Lock()
defer c.mu.Unlock()
for v, n := range merged {
c.published[v] += accept(v, n)
}
}
// Public returns the published count: an int64, so it never wraps at 2^31-1.
func (c *Counter) Public(videoID string) int64 {
c.mu.RLock()
defer c.mu.RUnlock()
return c.published[videoID]
}package views
import (
"fmt"
"sync"
"testing"
"time"
)
func TestPublicCountMovesOnlyAfterValidation(t *testing.T) {
c := New(8, 30*time.Second)
t0 := time.Unix(1_800_000_000, 0)
var wg sync.WaitGroup
for i := range 1000 {
wg.Add(1)
go func() {
defer wg.Done()
c.Record(Event{VideoID: "v1", ViewerID: fmt.Sprint("u", i), At: t0})
}()
}
wg.Wait()
if c.Record(Event{VideoID: "v1", ViewerID: "u1", At: t0.Add(time.Second)}) {
t.Fatal("repeat inside window should be discarded")
}
if got := c.Public("v1"); got != 0 {
t.Fatalf("published before validation: %d", got)
}
// A validator that rejects 10 percent as low quality.
c.Validate(func(_ string, n int64) int64 { return n - n/10 })
if got := c.Public("v1"); got != 900 {
t.Fatalf("published = %d, want 900", got)
}
}
func TestNoInt32Overflow(t *testing.T) {
c := New(1, time.Second)
c.Validate(func(string, int64) int64 { return 0 })
c.published["psy"] = 2_147_483_647
c.Record(Event{VideoID: "psy", ViewerID: "x", At: time.Unix(0, 0)})
c.Validate(func(_ string, n int64) int64 { return n })
if c.Public("psy") != 2_147_483_648 {
t.Fatal("counter wrapped")
}
}The Go angle
net/httpgives everything the upload protocol needs:Header().Set("Range", ...), arbitrary status codes (308),httptest.NewServerfor protocol tests. For large files, streamr.Bodyto storage withio.Copyinstead ofio.ReadAll(the snippet buffers to stay short).context.WithCancelCause(Go 1.20+) lets one failed task cancel the pool and report why;errgroup.WithContextfromgolang.org/x/syncis the common alternative.range workersover an int and theminbuiltin need Go 1.22 and 1.21; the module declaresgo 1.24.- For real encoding, Go services usually shell out to FFmpeg with
exec.CommandContextso cancellation kills the encoder process. - Vitess itself is written in Go, as are many media servers (MediaMTX); a Go service talks to Vitess as if it were MySQL via
database/sqlandgithub.com/go-sql-driver/mysql.
Laravel
Example: resumable upload controller, transcoding batch and schema
Routes (Sanctum-protected), a controller that implements the same protocol with an atomic cache lock per session, a job that fans out one TranscodeChunk per (chunk, rung) with Bus::batch, and an idempotent chunk job that runs FFmpeg through the Process facade.
<?php
use App\Http\Controllers\ResumableUploadController;
use Illuminate\Support\Facades\Route;
// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
Route::post('/upload', [ResumableUploadController::class, 'start'])->name('uploads.start');
Route::put('/upload/{id}', [ResumableUploadController::class, 'put'])->name('uploads.put');
});<?php
namespace App\Http\Controllers;
use App\Jobs\TranscodeVideo;
use App\Models\UploadSession;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
/**
* A Laravel 13 re-implementation of the resumable upload protocol documented
* for the YouTube Data API: POST starts a session, PUT sends bytes with
* Content-Range, 308 + Range reports progress, 201 means complete.
* Teaching code, not YouTube's implementation. UploadSession casts
* total_bytes/received_bytes to 'integer' and expires_at to 'datetime'.
*/
class ResumableUploadController extends Controller
{
private const CHUNK_MULTIPLE = 262144; // 256 KB
public function start(Request $request): Response
{
$total = (int) $request->header('X-Upload-Content-Length');
abort_if($request->query('uploadType') !== 'resumable' || $total <= 0, 400);
$session = UploadSession::create([
'id' => (string) Str::ulid(),
'user_id' => $request->user()->id,
'total_bytes' => $total,
'received_bytes' => 0,
'expires_at' => now()->addDay(),
]);
return response('', 200)->header('Location', route('uploads.put', $session->id));
}
public function put(Request $request, string $id): Response
{
// One writer per session: two PUTs racing on the same file would corrupt it.
return Cache::lock("upload:{$id}", 30)->block(5, function () use ($request, $id) {
$session = UploadSession::whereKey($id)
->where('user_id', $request->user()->id)
->first();
if ($session === null || $session->expires_at->isPast()) {
return response('session expired', 404);
}
if ($session->received_bytes === $session->total_bytes) {
return response('', 201);
}
[$first, $last, $total, $query] = $this->parseRange((string) $request->header('Content-Range'));
abort_if($total !== $session->total_bytes, 400, 'total length changed');
if ($query) {
return $this->incomplete($session->received_bytes);
}
$body = $request->getContent();
$isLast = $last === $total - 1;
abort_if(strlen($body) !== $last - $first + 1, 400, 'body does not match Content-Range');
abort_if(! $isLast && strlen($body) % self::CHUNK_MULTIPLE !== 0, 400, 'chunk must be a multiple of 256 KB');
// Overlapping or skipping blocks upload nothing; the client re-reads Range.
if ($first !== $session->received_bytes) {
return $this->incomplete($session->received_bytes);
}
$path = Storage::disk('local')->path("uploads/{$id}.part");
@mkdir(dirname($path), 0775, true);
file_put_contents($path, $body, FILE_APPEND | LOCK_EX);
$session->increment('received_bytes', strlen($body));
if ($session->received_bytes === $session->total_bytes) {
TranscodeVideo::dispatch($session->id)->onQueue('transcode');
return response('', 201);
}
return $this->incomplete($session->received_bytes);
});
}
/** @return array{0:int,1:int,2:int,3:bool} */
private function parseRange(string $header): array
{
if (preg_match('#^bytes \*/(\d+)$#', $header, $m)) {
return [0, 0, (int) $m[1], true];
}
abort_unless(preg_match('#^bytes (\d+)-(\d+)/(\d+)$#', $header, $m) === 1, 400, 'bad Content-Range');
return [(int) $m[1], (int) $m[2], (int) $m[3], false];
}
private function incomplete(int $received): Response
{
$response = response('', 308);
return $received > 0
? $response->header('Range', 'bytes=0-'.($received - 1))
: $response;
}
}<?php
namespace App\Jobs;
use App\Models\UploadSession;
use App\Models\Video;
use Illuminate\Bus\Batch;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Bus;
use Throwable;
/**
* Splits the finished upload into chunks and fans out one TranscodeChunk job
* per (chunk, rung) as a Laravel job batch; when every job succeeds the video
* is published. Per-chunk parallel encoding is a generic technique (inference
* for YouTube); the ladder below is an example, not YouTube's ladder.
*/
class TranscodeVideo implements ShouldQueue
{
use Queueable;
private const CHUNK_SECONDS = 10;
/** @var list<array{name:string,height:int,codec:string,kbps:int}> */
private const LADDER = [
['name' => '360p-h264', 'height' => 360, 'codec' => 'h264', 'kbps' => 700],
['name' => '720p-vp9', 'height' => 720, 'codec' => 'vp9', 'kbps' => 1800],
['name' => '1080p-vp9', 'height' => 1080, 'codec' => 'vp9', 'kbps' => 3000],
['name' => '2160p-av1', 'height' => 2160, 'codec' => 'av1', 'kbps' => 12000],
];
public function __construct(public string $uploadId) {}
public function handle(): void
{
$upload = UploadSession::findOrFail($this->uploadId);
$video = Video::firstOrCreate(
['upload_id' => $upload->id],
['user_id' => $upload->user_id, 'status' => 'processing'],
);
// In a real system a probe (ffprobe) fills these from the file.
$duration = (int) ($video->duration_seconds ?? 60);
$sourceHeight = (int) ($video->source_height ?? 1080);
$jobs = [];
foreach (self::LADDER as $rung) {
if ($rung['height'] > $sourceHeight) {
continue; // never upscale
}
for ($start = 0, $i = 0; $start < $duration; $start += self::CHUNK_SECONDS, $i++) {
$jobs[] = new TranscodeChunk($video->id, $i, $start, min($start + self::CHUNK_SECONDS, $duration), $rung);
}
}
$videoId = $video->id;
Bus::batch($jobs)
->then(function (Batch $batch) use ($videoId) {
Video::whereKey($videoId)->update(['status' => 'ready']);
})
->catch(function (Batch $batch, Throwable $e) use ($videoId) {
Video::whereKey($videoId)->update(['status' => 'failed']);
})
->name("transcode video {$videoId}")
->onQueue('transcode')
->dispatch();
}
}<?php
namespace App\Jobs;
use App\Models\Rendition;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Process;
/**
* Encodes one chunk at one ladder rung. Idempotent: the upsert key is
* (video_id, rung, chunk_index), so a retried job overwrites, never duplicates.
*/
class TranscodeChunk implements ShouldQueue
{
use Batchable, Queueable;
public int $tries = 3;
/** @param array{name:string,height:int,codec:string,kbps:int} $rung */
public function __construct(
public int $videoId,
public int $index,
public int $start,
public int $end,
public array $rung,
) {}
public function handle(): void
{
if ($this->batch()?->cancelled()) {
return;
}
$codec = ['h264' => 'libx264', 'vp9' => 'libvpx-vp9', 'av1' => 'libaom-av1'][$this->rung['codec']];
$out = storage_path("app/renditions/{$this->videoId}/{$this->rung['name']}/{$this->index}.mp4");
@mkdir(dirname($out), 0775, true);
Process::timeout(600)->run([
'ffmpeg', '-y',
'-ss', (string) $this->start, '-to', (string) $this->end,
'-i', storage_path("app/uploads/{$this->videoId}.src"),
'-vf', 'scale=-2:'.$this->rung['height'],
'-c:v', $codec, '-b:v', $this->rung['kbps'].'k',
$out,
])->throw();
Rendition::upsert(
[[
'video_id' => $this->videoId,
'rung' => $this->rung['name'],
'chunk_index' => $this->index,
'bytes' => filesize($out),
]],
['video_id', 'rung', 'chunk_index'],
['bytes'],
);
}
}The schema behind both implementations (PostgreSQL), including the sharded view counter:
-- Teaching schema for the re-implementations on this page (PostgreSQL).
-- Not YouTube's schema: YouTube's metadata historically lived in sharded
-- MySQL behind Vitess (vitess.io history page).
CREATE TABLE upload_sessions (
id text PRIMARY KEY, -- ULID; also in the session URI
user_id bigint NOT NULL,
total_bytes bigint NOT NULL CHECK (total_bytes > 0),
received_bytes bigint NOT NULL DEFAULT 0 CHECK (received_bytes <= total_bytes),
expires_at timestamptz NOT NULL
);
CREATE TABLE videos (
id bigserial PRIMARY KEY,
upload_id text UNIQUE REFERENCES upload_sessions (id),
user_id bigint NOT NULL,
status text NOT NULL CHECK (status IN ('processing', 'ready', 'failed', 'blocked')),
duration_seconds int,
source_height int,
created_at timestamptz NOT NULL DEFAULT now()
);
-- One row per encoded chunk per ladder rung; the key makes retries idempotent.
CREATE TABLE renditions (
video_id bigint NOT NULL REFERENCES videos (id),
rung text NOT NULL, -- '720p-vp9'
chunk_index int NOT NULL,
bytes bigint NOT NULL,
PRIMARY KEY (video_id, rung, chunk_index)
);
-- Sharded view counter: N rows per video, writers pick a random shard.
CREATE TABLE view_count_shards (
video_id bigint NOT NULL,
shard smallint NOT NULL,
views bigint NOT NULL DEFAULT 0, -- bigint: no 2^31-1 ceiling
PRIMARY KEY (video_id, shard)
);
-- Write path (one of 16 shards, chosen by the application):
-- INSERT INTO view_count_shards (video_id, shard, views) VALUES ($1, $2, 1)
-- ON CONFLICT (video_id, shard) DO UPDATE SET views = view_count_shards.views + 1;
-- Read path (cache the result for a few seconds):
-- SELECT COALESCE(SUM(views), 0) FROM view_count_shards WHERE video_id = $1;A tiny inline query for the counter read path, cached in Laravel with Cache::remember for a few seconds:
SELECT COALESCE(SUM(views), 0) AS views
FROM view_count_shards
WHERE video_id = 42;The Laravel angle
- Job batching needs the
job_batchestable (php artisan make:queue-batches-table); batched jobs use theIlluminate\Bus\Batchabletrait and check$this->batch()->cancelled();then,catchandfinallycallbacks run when the batch ends (Laravel 13 queues docs). Callbacks are serialized, so they must not use$this. Cache::lock($key, $seconds)->block($wait, $callback)gives one writer per upload session across PHP-FPM workers or Octane workers (needs a lock-capable cache store such as Redis or database).Process::timeout(600)->run([...])->throw()runs FFmpeg with an argument array (no shell quoting) and throws on a non-zero exit code.- Large uploads through PHP need
post_max_size/upload_max_filesizeand web-server body limits raised; at scale, let clients upload straight to object storage withStorage::temporaryUploadUrland keep Laravel as the control plane (inference for YouTube; standard practice elsewhere). - Live chat in Laravel: Reverb for WebSockets,
RateLimiter::attemptper user for slow mode, broadcast events for removals.
Solving the classic problems
Uploads restart from zero on mobile networks
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Resumable session | Session URI + status query + Content-Range | Only missing bytes resent | Session state, expiry |
| Chunks with progress | Fixed-size chunks, multiple of 256 KB | Progress bar, small retries | More requests (the guide discourages it unless needed) |
| Direct-to-storage multipart | Presigned part URLs | App servers carry no bytes | Assemble and verify parts |
New uploads take hours to become watchable
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Chunk-parallel encoding | Split at keyframes, chunk × rung tasks | Latency ≈ one chunk's encode time | Scheduling, boundaries |
| Publish low rungs first | Mark watchable when 360p is ready (inference) | Fast first view | Viewers see low quality briefly |
| Expensive codecs later | VP9/AV1 for videos that get views (inference) | Compute spent where it pays | Two passes |
| Specialised hardware | VCU-style accelerators or GPU encoders | 20–33x efficiency at YouTube (cited) | Capital and engineering |
The view counter is the hottest row in the database
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Sharded counter rows | N rows per video, random shard per write | Spreads lock contention | Read must sum N rows |
| Buffer and flush | Aggregate in memory, write every second | 1000x fewer writes | Loss window on crash |
| Event log + stream aggregation | Append events; aggregator writes deltas | Replayable, auditable | Pipeline to run |
| Serve from an analytics store | Procella-style stats serving, data in memory | Millions QPS, ms latency (cited) | Separate system |
Viewers rebuffer during peaks
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Caches inside ISPs | GGC-style appliances (cited) | 70–90% of cacheable traffic local | Partnerships, hardware |
| QUIC / HTTP/3 | Faster handshakes, no TCP head-of-line | 15–18% fewer YouTube rebuffers (cited) | UDP blocked on some networks; fallback needed |
| ABR ladder with low rungs | Always a rung the network can carry | Plays instead of stalls | More renditions to store |
Fake views, spam comments and chat floods
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Verify before publishing counts | Hold, dedupe, discard low-quality playbacks | Trustworthy numbers | Counts lag (and may look frozen) |
| Slow mode and subscriber-only chat | Per-user limiter and membership checks | Readable chat | Less participation |
| Async classifiers | Score after write; remove or demote | No latency on write path | Spam visible briefly |
Choosing
| Your situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Course platform, hundreds of videos | Managed video service (Mux, Cloudflare Stream, AWS MediaConvert + CloudFront) | Signed URLs | Transcoding and ABR are solved problems at this size |
| User uploads, thousands per day | S3 multipart or tus upload + FFmpeg workers + CDN | Chunk-parallel jobs, H.264 ladder first | Cost and control without building infrastructure |
| Large catalogue, bytes dominate cost | Add VP9/AV1 renditions for popular videos | Per-title or popularity tiers | Bytes saved on every view repay encode cost |
| Live events with chat | RTMPS ingest + LL-HLS + WebSocket chat | Latency mode per event | Interaction needs low latency; quality needs buffer |
| 4K/HDR live | HLS (HEVC) or DASH (VP9) ingest, normal latency | Backup ingest | YouTube's own guidance: not suitable for ultra-low latency |
| Public counters | Sharded or buffered counters + cache | Validation before display | Hot keys and fraud |
| Recommendations from scratch | Popularity + "watched together" baseline, then two-stage | Watch-time metric, A/B tests | YouTube started with popularity in 2008 |
| Metadata outgrows one MySQL | Replicas → partitioning → Vitess (or PostgreSQL + Citus) | Pick shard key = channel or video id | The vitess.io ladder |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel app with a videos table, uploads to local disk or S3, one queue worker running FFmpeg, and files served through a CDN. The resumable controller and TranscodeVideo job on this page fit here unchanged. The first things that break: upload request size limits (move bytes to direct-to-storage uploads) and a single worker that blocks for an hour on one 4K file (split into chunk jobs).
Modular monolith: boundaries without a network
Modules: Upload, Media Processing, Catalog (metadata), Playback (manifests, signed URLs), Engagement (views, likes, comments), Rights (Content ID-like checks). Each owns its tables; Media Processing publishes VideoTranscoded, Catalog listens and flips status = ready. This is where the YouTube shape first becomes visible: processing is asynchronous and every other module reacts to its events.
Microservices: what crosses the wire
1 client -> upload-service : POST session, PUT bytes -> 308 ... 201
2 upload-service -> bus : VideoUploaded {video_id, uri}
3 transcode-orchestrator : split, enqueue chunk x rung tasks
4 transcode-workers (N) : encode, write segments, ack task
5 orchestrator -> bus : VideoReady {video_id, renditions}
6 rights-service : fingerprint + match -> ClaimCreated (block|monetize|track)
7 catalog-service : status = ready unless blocked; index for search
8 player -> playback-service : manifest URL (signed) -> CDN segments
9 player -> engagement-service : view events -> validation -> countersIdempotency matters on every arrow: a redelivered VideoUploaded must not start a second transcode (key on video_id), and a retried chunk task must overwrite, not duplicate (the renditions primary key). Use the outbox pattern for events (Transactional Outbox).
Distributed data: replicas, caches, regions
Metadata reads go to replicas and caches; the creator who just edited a title needs read-your-writes (route their reads to the primary for a short window, inference for YouTube). Video bytes are immutable, so they cache perfectly and replicate across regions lazily; manifests change (live, new renditions) and need short TTLs. Counters are eventually consistent by design: YouTube's help page says counts update "more often" after verification and vary with popularity. Sharded MySQL via Vitess (historically) means cross-shard queries such as "all videos with tag X" belong in a search index, not in SQL.
Scaling path: 1×, 10×, 100×
| Load | Upload | Processing | Delivery | Metadata | Counters |
|---|---|---|---|---|---|
| 1× (hundreds/day) | Through the app | One FFmpeg worker | One CDN | One PostgreSQL | views + 1 is fine |
| 10× | Direct to object storage | Chunk-parallel workers, autoscaled | CDN + origin shield | Replicas + cache | Buffered or sharded |
| 100× | Regional upload endpoints | Dedicated encode fleet, GPU or ASIC, codec tiers | Multi-CDN or ISP caches | Sharding (Vitess/Citus) | Event log + OLAP serving |
Lab
Single-process Go tests are cheap and were run; the HTTP sessions below are expected output, not run.
- Run the tests (run):
$ cd docs/snippets/system-design/case-study-youtube/go && go test ./...
ok academy/case-study-youtube/resumable
ok academy/case-study-youtube/transcode
ok academy/case-study-youtube/views- Start a session against a local copy of the Go server wrapped in
main(expected, not run):
$ curl -si -X POST 'http://127.0.0.1:8080/upload?uploadType=resumable' -H 'X-Upload-Content-Length: 600000'
HTTP/1.1 200 OK
Location: /upload/5f1c...e2- Send the first 262,144 bytes, then ask for status (expected, not run):
$ head -c 262144 video.mp4 | curl -si -X PUT --data-binary @- -H 'Content-Range: bytes 0-262143/600000' http://127.0.0.1:8080/upload/5f1c...e2
HTTP/1.1 308 Permanent Redirect
Range: bytes=0-262143
$ curl -si -X PUT -H 'Content-Range: bytes */600000' http://127.0.0.1:8080/upload/5f1c...e2
HTTP/1.1 308 Permanent Redirect
Range: bytes=0-262143Go's net/http prints the standard reason phrase for 308 ("Permanent Redirect"); Google's API documents it as "Resume Incomplete". Clients must key on the number, not the phrase, and must not follow it as a redirect.
Send a chunk that skips bytes and observe that nothing is stored (expected, not run):
Content-Range: bytes 524288-599999/600000returns308with the sameRange: bytes=0-262143.Finish the upload (expected, not run):
Content-Range: bytes 262144-599999/600000returnsHTTP/1.1 201 Created.Laravel (expected, not run): with a queue worker on
transcode, a finished upload dispatchesTranscodeVideo;php artisan queue:work --queue=transcodeshows oneTranscodeVideofollowed by 18TranscodeChunkjobs for a 60 s 1080p source (6 chunks × 3 rungs), then the batchthencallback marks the videoready.
Common misconceptions
| Belief | Reality |
|---|---|
| YouTube streams the uploaded file | It streams transcoded renditions in several codecs and resolutions |
| Chunked upload is how resumability works | Resumability is session + Range; chunking is optional and "discouraged" unless needed |
| Transcoding is cheap | VP9 costs "5x" H.264 to encode; YouTube built an ASIC (VCU) for it |
| YouTube runs on one database | Published sources name Vitess/MySQL, Colossus, Bigtable, Spanner, Procella and more |
| Vitess is a database | It is a proxy and management layer over MySQL shards |
| YouTube buys CDN capacity like everyone else | Google Global Cache puts Google hardware inside ISPs |
| Recommendations optimise clicks | Ranking predicts expected watch time; clicks reward clickbait |
| A frozen view count is a bug | YouTube may slow, freeze or adjust counts while verifying them |
| The "301+" number is documented | It is folklore here; the documented rule is verification may freeze counts (inference for 301) |
| YouTube Live ingests SRT | The official ingestion comparison lists RTMP, RTMPS, HLS and DASH |
| Ultra-low latency is always better | It means less buffer and more rebuffering, and no 4K |
| Content ID is open to all uploaders | Only owners meeting criteria; misuse loses access |
Cheat sheet
| Topic | Remember |
|---|---|
| Scale | 500+ hours uploaded per minute (2021); 20M+ videos/day and 200B daily Shorts views (2026) |
| Upload | POST session → Location; PUT bytes; bytes */TOTAL → 308 + Range; 201 done; 404 expired |
| Chunks | Multiple of 256 KB except last; no gaps, no overlaps |
| Transcoding | Ladder = resolution × codec; chunk × rung tasks in parallel (inference for YouTube's scheduler) |
| Codecs | H.264 → VP9 (5x encode) → AV1; VCU ASIC, 20–33x efficiency (ASPLOS 2021) |
| Storage | Colossus (bytes), Bigtable/Spanner (metadata of Google storage systems), Vitess (MySQL shards, 2010) |
| Delivery | GGC inside ISPs (70–90% of cacheable traffic); ABR over DASH/HLS; QUIC: 15–18% fewer rebuffers |
| Recommendations | Candidate generation (millions → hundreds, ANN) then ranking (expected watch time) |
| View counts | Verified, may freeze; served by Procella at >1M QPS per instance; use 64-bit |
| Live | RTMP/RTMPS/HLS/DASH ingest; Normal, Low (<10 s), Ultra-low (<5 s); keyframe 2 s |
| DVR | Pause/rewind; limited past 12 h; never before start |
| Content ID | Every upload scanned; claim: block, monetize, track; per country |
| Abuse | Spam policy covers fake engagement, comment spam, detection evasion, scams |
| Label | Anything not in a YouTube/Google source is inference |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A client's upload dropped. What exact request does it send next, and what does the response tell it? Must-know
Answer
Answer: An empty PUT to the session URI with Content-Length: 0 and Content-Range: bytes */TOTAL. A 308 Resume Incomplete response carries Range: bytes=0-N; the client resumes from byte N+1. If the upload had finished, the server returns the original final response; an expired session returns 404.
2 — Why does the YouTube guide discourage chunked uploads, and when are they still useful? Important
Answer
Answer: Chunks add requests with performance cost; a single PUT plus resume on failure is enough. Chunks help to show progress on very unstable networks. Each chunk except the last must be a multiple of 256 KB.
3 — From "500 hours per minute", estimate daily upload hours and average ingress at 8 Mbit/s source bitrate. Must-know
Answer
Answer: 500 × 60 × 24 = 720,000 hours per day. 8 Mbit/s = 3.6 GB per hour, so 2.6 PB per day, about 30 GB/s or 240 Gbit/s on average. The bitrate is an assumption (inference).
4 — What trade-off made YouTube build the VCU? Important
Answer
Answer: Viewers wanted higher resolutions and the network needed more efficient codecs, but VP9 uses about 5x the compute of H.264 to encode; CPUs were inefficient at that scale. The VCU delivered 20–33x compute efficiency over the optimized software baseline.
5 — Name the two stages of the 2016 recommendation system and their input/output sizes. Good to know
Answer
Answer: Candidate generation: millions of videos to hundreds, using learned embeddings and nearest neighbour search in dot-product space. Ranking: hundreds to dozens, scoring each impression by expected watch time.
6 — Why rank for watch time rather than click-through rate, and what did it cost? Important
Answer
Answer: Click-through rate promotes clickbait that viewers do not finish; watch time captures engagement better. YouTube's blog reports an immediate 20% drop in views when watch time was added in 2012.
7 — A creator says the view count froze. What does YouTube's own documentation say? Must-know
Answer
Answer: Metrics are verified; YouTube may temporarily slow down, freeze or change the count and discard low-quality playbacks (for example several tabs or devices on one video). The 301+ number specifically is folklore on this page (inference).
8 — How does Procella serve view counts to watch pages? Good to know
Answer
Answer: In a stats-serving mode: the query is a SUM of views for one video id; new data is loaded into memory as soon as it is registered so there is no remote disk access on the serving path; each instance serves over a million QPS with millisecond latency.
9 — Which ingest protocol would you choose for a 4K HDR concert, and which for a Q&A with live chat? Important
Answer
Answer: 4K HDR: HLS with HEVC (or DASH with VP9), normal latency; YouTube says these are not suitable for ultra-low latency. Q&A: RTMPS with H.264 and ultra-low latency (most viewers under 5 s), accepting more buffering and no 4K.
10 — What does Google Global Cache change for an ISP? Important
Answer
Answer: Google places cache hardware inside the ISP network; typically 70–90% of cacheable traffic is served from it, reducing peering and transit traffic. The ISP provides rack space, power and connectivity; Google operates the cache.
11 — What are Content ID's three claim actions, and who may use it? Important
Answer
Answer: Block the video, monetize it with ads (sometimes sharing revenue with the uploader), or track its viewership statistics, possibly differently per country. Only copyright owners with exclusive rights to a substantial body of frequently uploaded material qualify.
12 — Which parts of this page are inference, and why does it matter? Must-know
Answer
Answer: The chunk scheduler details, search architecture, comment and chat storage and transport, fingerprinting internals, all assumed bitrates and storage numbers, and the 301+ figure. Labelling them keeps the reader from mistaking a reasonable design for a documented fact.
Glossary
| Term | Meaning |
|---|---|
| YouTube | Google's video platform; the subject of this case study |
| Upload | Sending the creator's original file to the platform |
| Resumable upload | Google API protocol: session URI, Content-Range, 308 Resume Incomplete, resume from the next byte |
| Chunked upload | Sending a file in fixed-size pieces (multiples of 256 KB on YouTube) |
| Session URI | The Location returned at upload start; target of every PUT |
| 308 Resume Incomplete | Upload status response carrying Range: bytes=0-N |
| Transcoding | Decoding and re-encoding a video into other resolutions, bitrates and codecs |
| Encoding ladder | The set of renditions (resolution × codec × bitrate) produced per video |
| Rendition | One encoded version of a video |
| Parallel transcoding | Encoding chunks of one video concurrently on many workers |
| H.264 | Widely supported legacy video codec |
| HEVC (H.265) | Successor to H.264; used for HLS and HDR live ingest |
| VP9 | Google's royalty-free codec; better compression than H.264, about 5x encode cost |
| AV1 | Alliance for Open Media codec; compresses better than VP9 at higher encode cost |
| ASIC | Application-specific integrated circuit: a chip built for one task |
| VCU | Video (trans)Coding Unit, YouTube's video transcoding ASIC |
| Argos | The VCU project described in the ASPLOS 2021 paper |
| Colossus | Google's cluster file system, successor to GFS; metadata in Bigtable |
| Bigtable | Google's wide-column NoSQL store |
| Spanner | Google's globally consistent relational database |
| Vitess | Proxy and management layer that shards MySQL; created at YouTube in 2010 |
| MySQL sharding | Splitting MySQL data across many servers by a shard key |
| Procella | YouTube's SQL engine for dashboards, embedded counters, monitoring and ad hoc analysis |
| Google Global Cache (GGC) | Google cache nodes hosted inside ISP networks |
| Edge node | A cache server close to viewers (in an ISP or a Google edge site) |
| Adaptive bitrate (ABR) | Player switches rendition per segment based on network and buffer |
| DASH | MPEG Dynamic Adaptive Streaming over HTTP |
| HLS | Apple HTTP Live Streaming; also used by YouTube for live ingest |
| QUIC | UDP-based encrypted transport, basis of HTTP/3 |
| Rebuffer rate | Rebuffer time / (rebuffer time + play time) |
| Metadata | Title, description, tags, status and derived facts about a video |
| Search | Retrieval and ranking of videos for a query |
| Recommendations | Personalised video suggestions on home and Up Next |
| Candidate generation | First stage: millions of videos to hundreds |
| Ranking | Second stage: scoring candidates to show dozens |
| Deep neural network | Multi-layer learned model; both recommendation stages use one |
| Embedding | Dense vector representing a user or a video |
| Nearest neighbour search | Finding vectors with the highest similarity; used at serving time |
| Watch time | Time spent watching; the ranking objective instead of clicks |
| Valued watchtime | Watch time rated highly in user surveys (2021 blog) |
| MMoE | Multi-gate Mixture-of-Experts, multitask ranking model (RecSys 2019) |
| View count | Public number of verified views |
| 301+ | Folklore number at which counts appeared to freeze; inference here |
| Comments | Persistent threaded text under a video |
| Live chat | Realtime messages during a live stream |
| Slow mode | Minimum wait between one user's chat messages |
| Live streaming | Broadcasting video in near real time |
| RTMP / RTMPS | Real-Time Messaging Protocol (and over TLS) for live ingest |
| SRT | Secure Reliable Transport, a contribution protocol; not listed in YouTube's ingest comparison |
| Low latency | YouTube mode where most viewers are under 10 s behind; ultra-low is under 5 s |
| DVR | Pause and rewind during a live stream |
| Content ID | YouTube's automated copyright matching against owner reference files |
| Fingerprinting | Computing compact signatures of audio/video that survive re-encoding |
| Abuse | Use of the platform against its users or rules |
| Spam | Repetitive, deceptive or inorganic content or engagement |
| Hours uploaded per minute | The headline upload-scale metric (500+ in 2021) |
| Scale | The published usage numbers that drive capacity |
| Inference | A statement this page derives or assumes, not found in a YouTube/Google source |
References
- YouTube Official Blog, Reimagining video infrastructure to empower YouTube (21 April 2021): https://blog.youtube/inside-youtube/new-era-video-infrastructure/
- Ranganathan et al., Warehouse-Scale Video Acceleration: Co-design and Deployment in the Wild, ASPLOS 2021 (Google Research page): https://research.google/pubs/warehouse-scale-video-acceleration-co-design-and-deployment-in-the-wild/
- YouTube Data API, Resumable Uploads: https://developers.google.com/youtube/v3/guides/using_resumable_upload_protocol
- Vitess docs, History: https://vitess.io/docs/overview/history/
- Google Cloud Blog, Colossus under the hood (April 2021): https://cloud.google.com/blog/products/storage-data-transfer/a-peek-behind-colossus-googles-file-system
- Chattopadhyay et al., Procella: Unifying serving and analytical data at YouTube, VLDB 2019: https://research.google/pubs/procella-unifying-serving-and-analytical-data-at-youtube/ (PDF: https://storage.googleapis.com/gweb-research2023-media/pubtools/5226.pdf)
- Google Interconnect Help, Introduction to GGC: https://support.google.com/interconnect/answer/9058809?hl=en
- Langley et al., The QUIC Transport Protocol: Design and Internet-Scale Deployment, SIGCOMM 2017: https://research.google/pubs/the-quic-transport-protocol-design-and-internet-scale-deployment/ (PDF: https://storage.googleapis.com/gweb-research2023-media/pubtools/4102.pdf)
- Chromium Blog, A QUIC update on Google's experimental transport (April 2015): https://blog.chromium.org/2015/04/a-quic-update-on-googles-experimental.html
- Covington, Adams, Sargin, Deep Neural Networks for YouTube Recommendations, RecSys 2016: https://research.google/pubs/deep-neural-networks-for-youtube-recommendations/ (PDF: https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/45530.pdf)
- Zhao et al., Recommending What Video to Watch Next: A Multitask Ranking System, RecSys 2019: https://research.google/pubs/recommending-what-video-to-watch-next-a-multitask-ranking-system/
- Yi et al., Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations, RecSys 2019: https://research.google/pubs/sampling-bias-corrected-neural-modeling-for-large-corpus-item-recommendations/
- YouTube Official Blog, On YouTube's recommendation system (15 September 2021): https://blog.youtube/inside-youtube/on-youtubes-recommendation-system/
- YouTube Help, How engagement metrics are counted: https://support.google.com/youtube/answer/2991785?hl=en
- YouTube Help, How Content ID works: https://support.google.com/youtube/answer/2797370?hl=en
- YouTube Help, Understand live streaming latency: https://support.google.com/youtube/answer/7444635?hl=en
- YouTube Help, Choose live encoder settings, bitrates, and resolutions: https://support.google.com/youtube/answer/2853702?hl=en
- YouTube Help, Turn on DVR on live streams: https://support.google.com/youtube/answer/9296823?hl=en
- YouTube Help, Moderate live chat: https://support.google.com/youtube/answer/9826490?hl=en
- YouTube Help, Spam, deceptive practices & scams policies: https://support.google.com/youtube/answer/2801973?hl=en
- YouTube Live Streaming API, Delivering Live YouTube Content via HLS: https://developers.google.com/youtube/v3/live/guides/hls-ingestion
- YouTube Live Streaming API, Ingestion Protocol Comparison: https://developers.google.com/youtube/v3/live/guides/ingestion-protocol-comparison
- YouTube Official Blog, Press (stats, fetched November 2026): https://blog.youtube/press/
- Cuong Do, Seattle Conference on Scalability: YouTube Scalability (video, published 2012-08-22; historical): https://www.youtube.com/watch?v=w5WVu624fY8
- Laravel 13 docs: queues (job batching): https://laravel.com/docs/13.x/queues ; cache (atomic locks): https://laravel.com/docs/13.x/cache ; processes: https://laravel.com/docs/13.x/processes