Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why video is a different problemWhy it exists
The dated sources and the timelineWhere it comes from
Step 1: requirementsScope
Step 2: numbersEstimate
Resumable and chunked uploadUpload
Ladders, chunks, codecs, VCUTranscoding, Codecs and Argos VCU
Colossus, Bigtable, Spanner, VitessStorage
Google Global Cache, ABR, DASH, HLS, QUICDelivery
Titles, tags, searchMetadata and search
Candidate generation and rankingRecommendations
Procella, frozen counts, 301+View counting
Comments and live chatComments and live chat
RTMP, HLS ingest, latency, DVRLive streaming
Copyright matchingContent ID
Spam, fake engagementAbuse and spam
Step 4: the decisionsDecisions
What changed, by yearWhat changed over time
Which chapter to read for each subsystemWhat you can copy
Exact protocol knobs and codesMechanics
CodeGo, Laravel
Classic failuresSolving the classic problems
Which design for your productChoosing
From a monolith to YouTube scaleIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The subsystems and the one fact to remember.

SubsystemOne cited factSource
UploadResumable sessions; status query answers 308 Resume Incomplete with RangeYouTube Data API guide
TranscodingCustom VCU chip: "up to 20-33x" compute efficiencyYouTube blog 2021, ASPLOS 2021 paper
CodecsVP9 looks better than H.264 but "uses 5x more computer resources to encode"YouTube blog 2021
File storageColossus underpins "YouTube, Drive, and Gmail"Google Cloud blog 2021
MetadataVitess "was created in 2010" for YouTube's MySQL scalingvitess.io history
DeliveryGGC lets ISPs "serve certain Google content from within their own networks"Google Interconnect help
TransportQUIC cut YouTube rebuffer rates by 18.0% (desktop) and 15.3% (mobile)SIGCOMM 2017 paper
RecommendationsTwo networks: candidate generation, then rankingCovington et al., RecSys 2016
View countsCounts may be slowed, frozen or adjusted while views are verifiedYouTube Help
Counter servingProcella serves "over a million QPS" of view/like counter queries per instanceProcella, VLDB 2019
LiveLatency modes: normal, low (most viewers under 10 s), ultra-low (under 5 s)YouTube Help
CopyrightContent ID scans every upload; claim actions: block, monetize, trackYouTube Help

The four steps on one line each.

StepYouTube answer
1. ScopeUpload, process, watch on any device, find (search, recommendations), engage (views, likes, comments, chat), go live, protect rights
2. Estimate500 hours per minute upload, 20 million videos per day, billions of logged-in users, 200 billion daily Shorts views
3. High-level designUpload API → original store → chunked transcode (CPU/VCU) → renditions → ISP caches → ABR player; side paths for metadata, recs, counters, chat, Content ID
4. DecisionsSpend 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.

QuantityValueKind
Video uploadedmore than 500 hours per minute on averageCited (YouTube blog, 2021)
Videos uploadedover 20 million per dayCited (YouTube press page, 2026)
Shorts viewsover 200 billion per dayCited (YouTube press page, 2026)
Upload ingressabout 240 Gbit/s averageEstimate, inference (see Estimate)
New bytes storedabout 7.5 PB per day before replicationEstimate, inference
Recommendation modelabout one billion parameters, hundreds of billions of examplesCited (Covington 2016)
GGC offloadtypically 70 to 90 percent of cacheable trafficCited (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:

ForceConsequence
One upload, many devicesEvery file must exist in many resolutions and codecs (the encoding ladder)
Bytes dominate costSpending CPU once at upload to shrink bytes on every view pays back; better codecs (VP9, AV1) win
Viewers are everywhereBytes must come from close by: caches inside ISPs, not one data centre
Networks fluctuateThe player must change quality mid-stream (adaptive bitrate)
Open uploadCopyright matching, spam and abuse checks are part of the pipeline, not an add-on
Popularity is skewedA 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.

Creator appfile in chunksResumable uploadPUT + Content-Range308 / 201Original store(Colossus)Parallel transcodingsplit into chunks (inference)chunk x rung tasksH.264 / VP9 / AV1CPU or Argos VCU (ASIC)encoding ladder 144p ... 4KRenditionssegments + manifestsContent ID scan+ policy, spamClaim: block, monetizeor track (per country)GGC / edge nodescache inside ISPsPlayerABR over DASH / HLS, QUICmetadata row: Vitess (MySQL shards)status: processing -> ready

Three common misunderstandings, up front ​

  1. "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".
  2. "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.
  3. "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 | track

Real 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.

RequirementTarget (assumption unless cited)Design consequence
Upload survives bad networksResume after interruption (cited: resumable protocol)Session URI, byte offsets, 308
Time to watchableMinutes (assumption)Parallel transcoding; publish low rungs first (inference)
Playback startAbout a second (assumption)Caches near users, small first segments
RebufferingAs low as possible (QUIC paper uses rebuffer rate as the metric)ABR, QUIC, ISP caches
Durability of originalsNever lose an upload (assumption)Replicated or erasure-coded storage (Colossus)
Counts are trustworthyVerified before display (cited: YouTube Help)Validation pipeline, delayed counts
RightsEvery 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 alone

Every 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).

LineInputResultKind
Upload hours/day500 × 60 × 24720,000Cited rate
Ingress3.6 GB/h sourceabout 240 Gbit/sinference
Renditions6.7 GB/habout 4.8 PB/dayinference
View events200 billion/dayabout 2.3 million/sCited rate, derived
Counter readsper watch-page loadmillions QPSProcella: "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.

ClientUpload APIPOST ?uploadType=resumable, X-Upload-Content-Length: 3000000200 OK, Location: session URI (upload_id=...)PUT bytes 0-2999999/3000000connection lostPUT, Content-Length: 0, Content-Range: bytes */3000000308 Resume Incomplete, Range: bytes=0-999999PUT Content-Range: bytes 1000000-2999999/3000000201 Created (video resource)Expired session URI: 404, start a new sessionoverlap or gap in bytes: nothing is uploaded
 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).

SituationResponseClient action
Upload finished201 Created (or 200)Done; poll processing status
Interrupted, still in progress308 with RangeResume from last byte + 1
Server error 500, 502, 503, 504ResumableBack off, query status, resume
Other 4xxPermanent failureFix the request
Expired session URI404 Not FoundStart 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 presentWait that longThen 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).

ChoiceCostBenefitNote
Whole-file encodeLong latency, one machineSimple; best rate control across the fileFine for small catalogues
Per-chunk parallel encodeChunk boundaries, schedulingLatency bounded by chunk time; retry granularityinference for YouTube
Never upscaleNoneSaves compute and bytesRungs above source height dropped
Codec per popularityTwo-tier pipelineExpensive codecs only where views pay backinference

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 encoding

Real 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.

CodecCompressionEncode costWhere it shows up on YouTube (cited)
H.264BaselineLowestLegacy comparison in the 2021 blog; live ingest over RTMP/RTMPS
HEVC (H.265)Better than H.264HigherLive ingest over HLS, HDR live
VP9Better than H.264"5x" H.264Playback; DASH live ingest
AV1Better than VP9Higher stillNext-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 graduation

Real 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.

DataStore named in a YouTube/Google sourceGeneric equivalent
Video bytes, segmentsColossusS3, GCS, HDFS
Video, channel, user rowsMySQL sharded with VitessPostgreSQL + Citus, MySQL + Vitess/PlanetScale
File system metadataBigtable (under Colossus)Wide-column store
Global consistent metadataSpanner (Google storage services, Procella metadata)CockroachDB, Spanner
Analytics and countersProcella (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).

LayerYouTube/Google element (cited)Generic equivalent
Cache inside ISPGoogle Global Cache nodeNetflix Open Connect, ISP-embedded CDN appliances
Edge and backboneGoogle front-end servers running QUICCDN PoPs
TransportQUIC (rebuffer rate down 15–18%)HTTP/3
FormatDASH, HLSSame
Player logicABR 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.

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).

ConcernCited factinference
Metadata shapeUpload API snippet/status partsStored in sharded MySQL historically (Vitess)
Search as a signalSearch 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
RankingNot documented in saved sourcesLearned 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.

Video corpus: millionsuser history + context as inputCandidates: hundredscandidate generation DNNShown: dozensranking DNNothercandidatesourcesCandidate generationuser embedding vs video embeddings (softmax)serving: nearest neighbour in dot-product spaceRankingrich features, one score per impressionobjective: expected watch time, not clicksEvaluationoffline metrics, then live A/B tests
 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 tests

Real 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.

StageInput sizeOutput sizeModel (cited)Latency budget
Candidate generationmillionshundredsDNN + sampled softmax, ANN at servingtens of ms (cited)
Other sourcesvariessomee.g. earlier related-video workinference
RankinghundredsdozensDNN, weighted logistic regression for watch timeinference
Multitask ranking (2019)hundredsdozensMMoE + shallow tower for selection biasnot stated
Responsibility layer (2019+)ranked listfiltered listclassifiers for borderline/authoritativenot 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").

ProblemNaive designYouTube (cited)Copyable fix
Hot counter writesUPDATE videos SET views = views + 1Not documentedSharded counters, buffered increments (Write Buffering)
Fake viewsCount every playVerify, freeze, discard low-quality playbacksValidation stage before publish
Counter readsRead primary rowProcella stats serving, data preloaded in memoryCache the sum for seconds
Overflowint (32-bit)64-bit (press coverage, inference)bigint
Many metricsOne system eachProcella unifies dashboards, counters, monitoring, ad hocOne 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 modePer-user token bucket on the write path (Rate Limiting)
Subscribers-only, with minimum durationSubscription lookup with timestamp on every write
Members-only chatEntitlement check; cannot combine with subscribers-only
Approved users (live commentary)Allow-list per stream
Moderators, hold for reviewModeration queue and removal events
AI-generated chat summary for new viewersAsync 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".

EncoderOBS, hardwarekeyframe 2 sPrimary ingestRTMP(S) / HLS / DASHBackup ingestcopy=1 (HLS)Live transcodemany output formatsSegments +sliding playlist, edgePlayer bufferlatency = read-aheadLive chat (separate realtime channel)slow mode, subscribers-only, moderatorsviewers and creator see each other with stream delayNormal | Low (< 10 s) | Ultra-low (< 5 s)DVR window: rewind, limited past 12 h
 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 video

Real 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)EncryptedVideo codecsLatency suitability
RTMPNoH.264Normal, low, ultra-low
RTMPSYesH.264Normal, low, ultra-low
HLSYesH.264, HEVCNot ultra-low; 4K, HDR
DASHYesH.264, VP9Not ultra-low; 4K
Encoder setting (cited, YouTube Help)Value
Keyframe frequencyRecommended 2 seconds; do not exceed 4 seconds
Bitrate encodingCBR
1080p60 recommended bitrate12 Mbit/s (AV1/H.265), 17 Mbit/s (H.264)
4K60 recommended bitrate35 Mbit/s (AV1/H.265), 50 Mbit/s (H.264)
AudioAAC 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.

AspectCitedinference
WhenEvery upload is scanned automaticallyAlso on later reference additions (rescans)
Against whatAudio and visual reference files from ownersFingerprint index sharded by hash
ResultClaim with block / monetize / track, per geographyPolicy evaluated at playback time per country
WhoOwners meeting eligibility criteria—
Abuse of the toolErroneous 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 hitsDefence that fits (copyable)
Engagement manipulation, fake engagementViews, likes, subscriptionsValidation before publishing counts
Comment spamComments, live chatPer-user rate limits, duplicate detection
Detection evasionUpload pipelineRobust fingerprints (Content ID)
Automated mass production, scraped contentUploads, recommendationsNear-duplicate detection, demotion
Scams, off-platform diversionLinks in descriptionsURL reputation, link scanning
Malicious clickbaitRecommendationsRank 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 counts

Real 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.

DecisionSourceCost paidAlternative refused
Custom VCU ASICASPLOS 2021, YouTube blogMulti-year hardware risk ("getting it right the first time")Keep scaling CPU fleets
VP9, then AV1YouTube blog 20215x encode cost for VP9; more for AV1Stay on H.264
Caches in ISPsGGC helpHardware and remote operations at many ISPsServe only from Google sites
QUICSIGCOMM 2017A new transport to build and maintainTCP + TLS only
Vitess on MySQLvitess.ioA proxy layer and sharding disciplineApp-level shard routing everywhere
Watch-time objectiveCovington 2016, YouTube blog 2021"immediate 20% drop in views"Click-through rate
Verified countsYouTube HelpCounts that lag or freezeReal-time raw counts
Unified analytics (Procella)VLDB 2019Building a new SQL engineSeparate 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 ​

YearChangeSource (saved)
2007 (published 2012)YouTube Scalability talk, Seattle Conference on ScalabilityYouTube video page (title and upload date only)
2008Recommendation system started; before it, one popularity "Trending" pageYouTube blog, 2021
2010Vitess created for YouTube's MySQL scalingvitess.io history
2011Learned clicks do not mean watching; classifiers keep racy/violent videos out of recommendationsYouTube blog, 2021
2012Watch time added to recommendationsYouTube blog, 2021
2015QUIC: about half of Chrome requests to Google; 30% fewer YouTube rebuffers reportedChromium blog, April 2015
2015VCU project startedYouTube blog, 2021
2016Deep neural network candidate generation + rankingCovington et al., RecSys 2016
2017QUIC paper: YouTube rebuffer rate down 18.0% desktop, 15.3% mobileSIGCOMM 2017
2018–2019Vitess CNCF incubation (Feb 2018), graduation (Nov 2019)vitess.io history
2019Procella; multitask ranking (MMoE); two-tower retrieval; borderline demotionVLDB 2019, RecSys 2019, YouTube blog 2021
2020Pandemic surge: watch time +25% in Q1, daily livestreams +45% in H1YouTube blog, 2021
2021Argos VCU paper and blog; next-gen chip adds AV1; Colossus postASPLOS 2021, YouTube blog, Google Cloud blog
202620 million videos/day; 200 billion daily Shorts views; co-views counted on TVs from November 2026YouTube 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.

SubsystemYouTube (cited)What you buildRead
UploadResumable protocol, 308, 256 KB chunkstus or S3 multipart with presigned parts; same status semanticsObject Storage, API Idempotency
TranscodingVCU ASIC, VP9/AV1FFmpeg workers or a cloud transcoder, chunk × rung queueCompeting Consumers, Durable Workflows
File storageColossusS3/GCS with lifecycle tiersObject Storage
MetadataMySQL + VitessPostgreSQL, then partitioning/Citus, or MySQL + VitessSharding at System Level
DeliveryGGC, QUIC, DASH/HLSCommercial CDN, HTTP/3, HLS/CMAFCDNs, HTTP evolution
SearchNot documentedElasticsearch/OpenSearch + re-rankerSearch Systems
RecommendationsTwo-stage DNNEmbeddings + ANN + rankerML Systems, Vector Search
View countsValidation + ProcellaEvent log, sharded counters, cached sumsWrite Buffering & Sharded Counters, Top-K
Comments, live chatSlow mode, moderatorsSharded table + WebSocket fan-out + limiterReal-Time Communication, Rate Limiting
LiveRTMPS/HLS ingest, latency modes, DVRMedia server + LL-HLS + CDNCDNs
Content IDReference fingerprint matchingPerceptual hashes + ANN indexBloom Filters & Probabilistic Structures for the indexing mindset
AbusePolicy + classifiersRate limits, reputation, async classifiersLoad Shedding, OWASP Top 10

Mechanics ​

Resumable upload knobs and codes ​

ItemValue (YouTube Data API guide)
Start URLPOST https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=...
Required headers on startAuthorization, Content-Type: application/json; charset=UTF-8, X-Upload-Content-Length, X-Upload-Content-Type (video/* or application/octet-stream)
Session URILocation header of the 200 response
Status queryPUT with Content-Length: 0 and Content-Range: bytes */TOTAL
Progress response308 Resume Incomplete, Range: bytes=0-N (absent if nothing received)
Resumable errors500, 502, 503, 504, or a lost connection
Session expired404 Not Found
Chunk sizeMultiple of 256 KB (262,144 bytes), same for every chunk except the last
Non-contiguous blockRejected silently: nothing uploaded

Live streaming knobs ​

ItemValue (YouTube Help / Live Streaming API docs)
Latency modesNormal; Low latency (most viewers < 10 s); Ultra-low latency (most viewers < 5 s)
4K with low latencyNot supported; 4K streams use normal latency
Keyframe interval2 s recommended, never above 4 s
HLS ingest segment duration1 to 4 seconds, M2TS, H.264 or HEVC, AAC single track
HLS backup ingestb.upload.youtube.com with copy=1
DVR limitMay be limited or unavailable past 12 hours; never before the stream start
DVR toggle mid-streamApplies only to viewers who start after the change

Recommendation model facts ​

ItemValue (Covington et al. 2016)
Candidate outputHundreds of videos
Training trickSampled softmax: "several thousand negatives", "more than 100 times speedup"
ServingApproximate nearest neighbour in dot-product space, tens of ms
Ranking objectiveExpected watch time per impression (weighted logistic regression)
Model sizeAbout one billion parameters, hundreds of billions of examples
Decision ruleOffline metrics guide; live A/B tests decide

Error and status vocabulary ​

Code or messageWhereMeaning
308 Resume IncompleteUpload APIBytes so far in Range; keep sending
201 CreatedUpload APIUpload complete; body is the video resource
404 Not FoundUpload APISession URI expired
Retry-AfterUpload APIWait before resuming
Content ID claimYouTube StudioMatch found; owner policy applied
Frozen or slowed countWatch pageMetrics 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.

go
// 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)))
}
go
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.

go
// 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
}
go
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.

go
// 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]
}
go
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/http gives everything the upload protocol needs: Header().Set("Range", ...), arbitrary status codes (308), httptest.NewServer for protocol tests. For large files, stream r.Body to storage with io.Copy instead of io.ReadAll (the snippet buffers to stay short).
  • context.WithCancelCause (Go 1.20+) lets one failed task cancel the pool and report why; errgroup.WithContext from golang.org/x/sync is the common alternative.
  • range workers over an int and the min builtin need Go 1.22 and 1.21; the module declares go 1.24.
  • For real encoding, Go services usually shell out to FFmpeg with exec.CommandContext so 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/sql and github.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
<?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
<?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
<?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
<?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:

sql
-- 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:

sql
SELECT COALESCE(SUM(views), 0) AS views
FROM view_count_shards
WHERE video_id = 42;

The Laravel angle ​

  • Job batching needs the job_batches table (php artisan make:queue-batches-table); batched jobs use the Illuminate\Bus\Batchable trait and check $this->batch()->cancelled(); then, catch and finally callbacks 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_filesize and web-server body limits raised; at scale, let clients upload straight to object storage with Storage::temporaryUploadUrl and keep Laravel as the control plane (inference for YouTube; standard practice elsewhere).
  • Live chat in Laravel: Reverb for WebSockets, RateLimiter::attempt per user for slow mode, broadcast events for removals.

Solving the classic problems ​

Uploads restart from zero on mobile networks ​

SolutionHowAdvantageCost
Resumable sessionSession URI + status query + Content-RangeOnly missing bytes resentSession state, expiry
Chunks with progressFixed-size chunks, multiple of 256 KBProgress bar, small retriesMore requests (the guide discourages it unless needed)
Direct-to-storage multipartPresigned part URLsApp servers carry no bytesAssemble and verify parts

New uploads take hours to become watchable ​

SolutionHowAdvantageCost
Chunk-parallel encodingSplit at keyframes, chunk × rung tasksLatency ≈ one chunk's encode timeScheduling, boundaries
Publish low rungs firstMark watchable when 360p is ready (inference)Fast first viewViewers see low quality briefly
Expensive codecs laterVP9/AV1 for videos that get views (inference)Compute spent where it paysTwo passes
Specialised hardwareVCU-style accelerators or GPU encoders20–33x efficiency at YouTube (cited)Capital and engineering

The view counter is the hottest row in the database ​

SolutionHowAdvantageCost
Sharded counter rowsN rows per video, random shard per writeSpreads lock contentionRead must sum N rows
Buffer and flushAggregate in memory, write every second1000x fewer writesLoss window on crash
Event log + stream aggregationAppend events; aggregator writes deltasReplayable, auditablePipeline to run
Serve from an analytics storeProcella-style stats serving, data in memoryMillions QPS, ms latency (cited)Separate system

Viewers rebuffer during peaks ​

SolutionHowAdvantageCost
Caches inside ISPsGGC-style appliances (cited)70–90% of cacheable traffic localPartnerships, hardware
QUIC / HTTP/3Faster handshakes, no TCP head-of-line15–18% fewer YouTube rebuffers (cited)UDP blocked on some networks; fallback needed
ABR ladder with low rungsAlways a rung the network can carryPlays instead of stallsMore renditions to store

Fake views, spam comments and chat floods ​

SolutionHowAdvantageCost
Verify before publishing countsHold, dedupe, discard low-quality playbacksTrustworthy numbersCounts lag (and may look frozen)
Slow mode and subscriber-only chatPer-user limiter and membership checksReadable chatLess participation
Async classifiersScore after write; remove or demoteNo latency on write pathSpam visible briefly

Choosing ​

Your situationRecommendationExtra techniqueReason
Course platform, hundreds of videosManaged video service (Mux, Cloudflare Stream, AWS MediaConvert + CloudFront)Signed URLsTranscoding and ABR are solved problems at this size
User uploads, thousands per dayS3 multipart or tus upload + FFmpeg workers + CDNChunk-parallel jobs, H.264 ladder firstCost and control without building infrastructure
Large catalogue, bytes dominate costAdd VP9/AV1 renditions for popular videosPer-title or popularity tiersBytes saved on every view repay encode cost
Live events with chatRTMPS ingest + LL-HLS + WebSocket chatLatency mode per eventInteraction needs low latency; quality needs buffer
4K/HDR liveHLS (HEVC) or DASH (VP9) ingest, normal latencyBackup ingestYouTube's own guidance: not suitable for ultra-low latency
Public countersSharded or buffered counters + cacheValidation before displayHot keys and fraud
Recommendations from scratchPopularity + "watched together" baseline, then two-stageWatch-time metric, A/B testsYouTube started with popularity in 2008
Metadata outgrows one MySQLReplicas → partitioning → Vitess (or PostgreSQL + Citus)Pick shard key = channel or video idThe 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 -> counters

Idempotency 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× ​

LoadUploadProcessingDeliveryMetadataCounters
1× (hundreds/day)Through the appOne FFmpeg workerOne CDNOne PostgreSQLviews + 1 is fine
10×Direct to object storageChunk-parallel workers, autoscaledCDN + origin shieldReplicas + cacheBuffered or sharded
100×Regional upload endpointsDedicated encode fleet, GPU or ASIC, codec tiersMulti-CDN or ISP cachesSharding (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.

  1. 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
  1. 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
  1. 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-262143

Go'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.

  1. Send a chunk that skips bytes and observe that nothing is stored (expected, not run): Content-Range: bytes 524288-599999/600000 returns 308 with the same Range: bytes=0-262143.

  2. Finish the upload (expected, not run): Content-Range: bytes 262144-599999/600000 returns HTTP/1.1 201 Created.

  3. Laravel (expected, not run): with a queue worker on transcode, a finished upload dispatches TranscodeVideo; php artisan queue:work --queue=transcode shows one TranscodeVideo followed by 18 TranscodeChunk jobs for a 60 s 1080p source (6 chunks × 3 rungs), then the batch then callback marks the video ready.

Common misconceptions ​

BeliefReality
YouTube streams the uploaded fileIt streams transcoded renditions in several codecs and resolutions
Chunked upload is how resumability worksResumability is session + Range; chunking is optional and "discouraged" unless needed
Transcoding is cheapVP9 costs "5x" H.264 to encode; YouTube built an ASIC (VCU) for it
YouTube runs on one databasePublished sources name Vitess/MySQL, Colossus, Bigtable, Spanner, Procella and more
Vitess is a databaseIt is a proxy and management layer over MySQL shards
YouTube buys CDN capacity like everyone elseGoogle Global Cache puts Google hardware inside ISPs
Recommendations optimise clicksRanking predicts expected watch time; clicks reward clickbait
A frozen view count is a bugYouTube may slow, freeze or adjust counts while verifying them
The "301+" number is documentedIt is folklore here; the documented rule is verification may freeze counts (inference for 301)
YouTube Live ingests SRTThe official ingestion comparison lists RTMP, RTMPS, HLS and DASH
Ultra-low latency is always betterIt means less buffer and more rebuffering, and no 4K
Content ID is open to all uploadersOnly owners meeting criteria; misuse loses access

Cheat sheet ​

TopicRemember
Scale500+ hours uploaded per minute (2021); 20M+ videos/day and 200B daily Shorts views (2026)
UploadPOST session → Location; PUT bytes; bytes */TOTAL → 308 + Range; 201 done; 404 expired
ChunksMultiple of 256 KB except last; no gaps, no overlaps
TranscodingLadder = resolution × codec; chunk × rung tasks in parallel (inference for YouTube's scheduler)
CodecsH.264 → VP9 (5x encode) → AV1; VCU ASIC, 20–33x efficiency (ASPLOS 2021)
StorageColossus (bytes), Bigtable/Spanner (metadata of Google storage systems), Vitess (MySQL shards, 2010)
DeliveryGGC inside ISPs (70–90% of cacheable traffic); ABR over DASH/HLS; QUIC: 15–18% fewer rebuffers
RecommendationsCandidate generation (millions → hundreds, ANN) then ranking (expected watch time)
View countsVerified, may freeze; served by Procella at >1M QPS per instance; use 64-bit
LiveRTMP/RTMPS/HLS/DASH ingest; Normal, Low (<10 s), Ultra-low (<5 s); keyframe 2 s
DVRPause/rewind; limited past 12 h; never before start
Content IDEvery upload scanned; claim: block, monetize, track; per country
AbuseSpam policy covers fake engagement, comment spam, detection evasion, scams
LabelAnything not in a YouTube/Google source is inference

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
YouTubeGoogle's video platform; the subject of this case study
UploadSending the creator's original file to the platform
Resumable uploadGoogle API protocol: session URI, Content-Range, 308 Resume Incomplete, resume from the next byte
Chunked uploadSending a file in fixed-size pieces (multiples of 256 KB on YouTube)
Session URIThe Location returned at upload start; target of every PUT
308 Resume IncompleteUpload status response carrying Range: bytes=0-N
TranscodingDecoding and re-encoding a video into other resolutions, bitrates and codecs
Encoding ladderThe set of renditions (resolution × codec × bitrate) produced per video
RenditionOne encoded version of a video
Parallel transcodingEncoding chunks of one video concurrently on many workers
H.264Widely supported legacy video codec
HEVC (H.265)Successor to H.264; used for HLS and HDR live ingest
VP9Google's royalty-free codec; better compression than H.264, about 5x encode cost
AV1Alliance for Open Media codec; compresses better than VP9 at higher encode cost
ASICApplication-specific integrated circuit: a chip built for one task
VCUVideo (trans)Coding Unit, YouTube's video transcoding ASIC
ArgosThe VCU project described in the ASPLOS 2021 paper
ColossusGoogle's cluster file system, successor to GFS; metadata in Bigtable
BigtableGoogle's wide-column NoSQL store
SpannerGoogle's globally consistent relational database
VitessProxy and management layer that shards MySQL; created at YouTube in 2010
MySQL shardingSplitting MySQL data across many servers by a shard key
ProcellaYouTube's SQL engine for dashboards, embedded counters, monitoring and ad hoc analysis
Google Global Cache (GGC)Google cache nodes hosted inside ISP networks
Edge nodeA 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
DASHMPEG Dynamic Adaptive Streaming over HTTP
HLSApple HTTP Live Streaming; also used by YouTube for live ingest
QUICUDP-based encrypted transport, basis of HTTP/3
Rebuffer rateRebuffer time / (rebuffer time + play time)
MetadataTitle, description, tags, status and derived facts about a video
SearchRetrieval and ranking of videos for a query
RecommendationsPersonalised video suggestions on home and Up Next
Candidate generationFirst stage: millions of videos to hundreds
RankingSecond stage: scoring candidates to show dozens
Deep neural networkMulti-layer learned model; both recommendation stages use one
EmbeddingDense vector representing a user or a video
Nearest neighbour searchFinding vectors with the highest similarity; used at serving time
Watch timeTime spent watching; the ranking objective instead of clicks
Valued watchtimeWatch time rated highly in user surveys (2021 blog)
MMoEMulti-gate Mixture-of-Experts, multitask ranking model (RecSys 2019)
View countPublic number of verified views
301+Folklore number at which counts appeared to freeze; inference here
CommentsPersistent threaded text under a video
Live chatRealtime messages during a live stream
Slow modeMinimum wait between one user's chat messages
Live streamingBroadcasting video in near real time
RTMP / RTMPSReal-Time Messaging Protocol (and over TLS) for live ingest
SRTSecure Reliable Transport, a contribution protocol; not listed in YouTube's ingest comparison
Low latencyYouTube mode where most viewers are under 10 s behind; ultra-low is under 5 s
DVRPause and rewind during a live stream
Content IDYouTube's automated copyright matching against owner reference files
FingerprintingComputing compact signatures of audio/video that survive re-encoding
AbuseUse of the platform against its users or rules
SpamRepetitive, deceptive or inorganic content or engagement
Hours uploaded per minuteThe headline upload-scale metric (500+ in 2021)
ScaleThe published usage numbers that drive capacity
InferenceA statement this page derives or assumes, not found in a YouTube/Google source

References ​

Built by Morteza Negahi