Processing: One Source File Becomes Many Derived Assets
The fan-out, briefly
Once the source file is durable (end of the Upload part), it becomes the input to several parallel jobs, not just one:
| Job | What it produces | Why it exists |
|---|---|---|
| Transcoding | ~20 renditions across resolutions and codecs | So playback can match any device/network — the subject of the rest of this part |
| Thumbnail extraction | Frame samples for preview images | Needed before the video is browsable anywhere |
| Captions / ASR | Auto-generated transcripts and timed captions | Accessibility, search, and translation all depend on this existing |
| Content ID fingerprinting | Audio/video fingerprints matched against a reference database | Copyright matching has to happen before (or very soon after) a video is public, independent of whether anyone ever watches it |
| Moderation / policy scanning | Automated classification against platform policy | Has to run regardless of predicted popularity — a video with 3 views can still violate policy |
These jobs run off the same durable source, on their own schedules, and none of them blocks the others — a caption job failing doesn't hold up the video going live, and vice versa. This guide goes deep on transcoding specifically, because its cost model (codec choice, when to invest) is the most instructive example of the "defer expensive work until it's earned" pattern that shows up everywhere else in this pipeline.
What actually triggers the fan-out
Mechanically, how does finishing an upload turn into five independent jobs starting? This is an event-driven fan-out, not any job polling storage asking "is it ready yet?"
- Durability completion is the trigger, not a schedule. The instant the Upload part’s upload finishes (
201 Created, source bytes durable), that write completion fires a single "source ready" event — nothing downstream is on a timer or polling loop. - One event, published once, fans out to several independent queues. Standard pub/sub: one publisher, many independent subscribers. Each job type has its own queue/topic, and each queue receives its own copy of the event — a jammed captions queue has zero effect on the transcode queue.
- Each queue has its own worker pool, at its own pace. A large transcoding fleet drains the transcode queue; a much smaller, faster pool handles thumbnails. This is why thumbnails finish in seconds while the transcode ladder takes hours for the same video — they were never on the same clock.
- Transcoding gets triggered a second time, later. Most jobs run once, off the original event. Transcoding is the exception: crossing a view-count threshold (this part's popularity gate, below) publishes a second event onto the same transcode queue — "produce the expensive codec now."
The queue can't just hold a message for the whole job
A transcode subtask on a giant 4K/AV1 source can run for hours. A generic queue's reliability mechanism — the visibility timeout — wasn't designed for that timescale, and glossing over the mismatch hides where the real engineering is.
How visibility timeout works, briefly. A worker doesn't delete a message when it picks it up — it makes the message invisible to other workers for a configured window. If the worker finishes and explicitly acks (deletes) before the window closes, done. If the window closes first — worker crashed, got preempted — the message reappears for someone else to pick up. This is what makes a queue self-healing against dead workers, but it assumes the window is a reasonable estimate of "how long this should take."
Problem 1 — one fixed timeout doesn't fit wildly different job lengths
A 5-minute clip and a 3-hour livestream VOD don't transcode in the same time. Set the timeout to worst-case (hours) and a worker that dies 30 seconds in won't be noticed for hours. Set it short and a healthy worker gets its message reassigned out from under it mid-job.
Fix: the worker takes a short visibility window (e.g. 2 minutes) and heartbeats — renews it periodically — as long as it's alive and making progress. Silence for 2 minutes means genuinely dead, and the message requeues fast, no matter the job's total runtime.
Problem 2 — a crash near the end shouldn't lose the whole job
Heartbeating detects death fast, but if the worker process itself dies (OOM-killed, spot instance reclaimed) after 2h50m of a 3-hour encode, redelivery means starting over from zero.
Fix: never let one message represent one multi-hour job. Decompose it:
Each subtask writes its output and marks itself done in the job record; the job is "complete" once every subtask required for the current tier is done. Each subtask is minutes, not hours, so a crash loses minutes of work.
Concretely, end-to-end
The original "transcode video X" message is disposable the moment a job record exists for it — that's the entire trick. Mapped onto real primitives (any queue + any transactional store), it's two small pieces of code:
# ── Orchestrator: consumes the ONE trigger message, never touches ffmpeg ──
on receive("transcode-jobs", {video_id}):
put_item(job_record[video_id], {
renditions: {240p_h264: pending, 480p_h264: pending,
1080p_h264: pending, 4k_av1: pending},
status: in_progress
}, condition = not_exists(video_id)) # idempotent: redelivery of the
# trigger is a harmless no-op
for rendition in job_record[video_id].renditions:
send("transcode-subtasks", {video_id, rendition})
ack("transcode-jobs") # the multi-hour job now lives
# entirely in job_record, not the queue
# ── Worker: one process per subtask, short lease, heartbeats while alive ──
on receive("transcode-subtasks", {video_id, rendition}, lease = 2min):
start_heartbeat(renew lease every 60s while alive) # silence 2min = presumed
# dead, message redelivers
try:
output = f"video_{video_id}/{rendition}.mp4" # deterministic path —
ffmpeg_encode(source(video_id), output) # a duplicate run just
# overwrites identical bytes
update_item(job_record[video_id],
set renditions[rendition] = done,
condition = renditions[rendition] != done) # idempotent — a second
# delivery of this same
# subtask is a no-op
if all(v == done for v in job_record[video_id].renditions.values()):
won = update_item(job_record[video_id],
set status = complete,
condition = status != complete) # see note below — gate the
# PUBLISH on winning this write,
# not on the read-check above
if won:
publish("transcode.complete", video_id) # triggers the next stage
ack("transcode-subtasks")
finally:
stop_heartbeat()The orchestrator's job record is what actually survives for 3 hours; the queue never holds a lease longer than a couple of minutes at any point in that timeline. The popularity-gate's second event (below) is the same shape: send("transcode-subtasks", {video_id, rendition: 1080p_vp9}) plus adding that key to the job record — no new machinery, just a later trigger onto the same subtask queue.
Problem 3 — retries cause duplicates, so make the work idempotent
Queues give at-least-once delivery, never exactly-once: a heartbeat can be delayed by a GC pause, an ack can be lost after the work already finished, and two workers will occasionally process the same subtask. Don't try to prevent this — make it harmless instead. Output paths are deterministic (video_X/1080p_av1.mp4), so a duplicate encode just overwrites with identical bytes, and the job-record update ("mark 1080p/AV1 done") is a conditional write, not an append, so applying it twice is a no-op the second time.
Problem 4 — a subtask that fails forever shouldn't block the job forever
If 4K/AV1 keeps failing (corrupt source segment, an encoder bug on that specific codec path), retrying indefinitely just hangs the job. Standard answer: a dead-letter queue — after N redelivery attempts, the message moves off the main queue for manual attention/alerting, and the job record reflects "degraded: 4K/AV1 failed" instead of never reaching "complete."
| Piece | Role |
|---|---|
| Transcode queue | Dispatch only — one message per (video, rendition) subtask |
| Job record (durable store) | Source of truth for "what's done so far" — survives crashes and retries |
| Short, heartbeated visibility timeout | Detects a dead worker in minutes, independent of total job length |
| Idempotent writes | Makes duplicate delivery safe rather than something to prevent |
| Dead-letter queue | Catches subtasks that exhaust their retry budget so the job doesn't hang forever |
This is the general pattern for any long-running work dispatched off a queue — video encoding, large batch ML inference, big file processing: never let the queue hold a multi-hour lease. Decompose until each unit fits comfortably inside a normal retry/timeout window, and let durable state elsewhere stitch the units back into "the job."
In plain terms, before the ladder
| Term | What it means |
|---|---|
| Frame rate | A video is a rapid slideshow of still frames; frame rate is how many flash by per second. More fps = smoother motion; 24fps looks like film, 30fps is standard, 60fps makes fast motion (sports, gaming) look fluid instead of choppy. |
| Codec | Raw, uncompressed frames are huge. A codec is the compression algorithm that shrinks frames down to something practical, then reverses the process to display them. H.264 is older, less efficient, but universally supported; AV1 compresses much further for the same visual quality but costs far more compute to encode. Think "zip, but tuned for video." |
| Bitrate | How much data per second the compressed video actually uses while playing (Mbps). The dial that controls size-vs-quality within a given resolution and codec: higher bitrate looks crisper but needs a faster connection; lower bitrate looks softer but plays fine on a weak connection. |
How the three relate: frame rate is fixed by the source footage, codec is the compression method chosen, and bitrate is how generously that codec is allowed to spend data per second. A better codec (AV1) can hit the same visual quality at a lower bitrate than a worse one (H.264) — that's the bandwidth-savings story the rest of this part is about.
Bitrate vs. internet speed — a rate-matching problem, not a hard block
Video bitrate
Property of the file: how many bits belong to each second of compressed video. A "3 Mbps rendition" means second 47 of playback is ~3 million bits, second 48 is another ~3 million, and so on.
Internet speed
Property of the connection: how many bits per second it can actually deliver, constantly fluctuating (wifi congestion, cell load, other devices).
A slow connection isn't a hard wall — the data can always eventually be downloaded, given enough time. The problem is timing: to show second 47 of the video at second 47 of real playback time, those ~3 million bits need to have already arrived by then. Downloading 3 Mbps of data over a 1.5 Mbps connection takes 2 seconds, but playback only allows 1 second before it needs that data — so the download falls behind, the player's buffer drains, and once it's empty: the stall/buffering spinner. This is exactly the "running dry" failure mode from the staged pipeline part’s water-utility mapping, and it's the reason ABR (see Adaptive playback) exists at all.
The five knobs a rendition varies
"~20 renditions" isn't 20 arbitrary files — it's every source video multiplied out across five independent axes. Each axis exists to solve a different, unrelated constraint; a rendition is just one point picked from all five at once.
| Knob | Matches | Typical values |
|---|---|---|
| Resolution | The screen — no point sending 4K to a phone that can't display it | 144p → 8K |
| Frame rate | The source — forcing 60fps onto a 24fps film wastes bitrate on frames that don't exist | 24, 30, 48, 60 (120 for slow-mo) |
| Codec | The decoder on the viewer's device — trades encode cost for bandwidth savings | H.264 (universal floor), VP9 (mid-tier), AV1 (best compression, most expensive) |
| Bitrate | The network — a fixed resolution/codec still needs several bitrate rungs so playback can downshift without changing resolution | 1080p H.264: ~1.5–8 Mbps |
| Container | The delivery protocol/platform — same bytes wrapped differently for adaptive streaming vs. download | MP4, WebM, DASH/HLS segment formats |
This is a cross-product, not five independent lists: a viewer's actual situation (device, decoder support, network, protocol) pins down one specific combination, and the system has no way to know in advance which combination that'll be. Not every cell in the cross-product is actually produced, though — that's the rest of this part.
Why / The Problem — the codec bet
A better codec is a genuinely compelling trade: AV1 delivers roughly 45–50% bandwidth savings over H.264 at equivalent visual quality, and that saving compounds on every single view, forever. But encoding cost is not symmetric with the bandwidth savings it buys — AV1 takes roughly 18x longer to encode than H.264, a one-time cost paid regardless of whether the resulting bandwidth savings ever materialize.
| Eager (best codec for everything, at upload) | Gated (codec investment grows with view count) | |
|---|---|---|
| Encode cost | Paid once, in full, for every video regardless of outcome | Paid incrementally, scaled to actual demand |
| Cost on a 12-view video | Full expensive encode, wasted | Only the cheap, universal codec is ever produced |
| Cost on a 500M-view video | Same up-front cost as any other video | Expensive encode triggered once early view signal justifies it — trivial relative to bandwidth saved |
| Time-to-first-watchable | Delayed by waiting on the most expensive encode | Fast — cheapest codec ships first (see Upload) |
| Risk | None, if you can afford the aggregate compute bill | A video that goes viral faster than re-encoding catches up is served the less-efficient codec for a window |
How It Works — the ladder is popularity-gated
The ladder is a matrix: resolution × codec. H.264 is the universal floor — every video gets it, because it's the one format essentially every device on Earth can hardware-decode, and it's cheap to produce. Codec assignment tracks view count, and the bar moves over time:
The exact thresholds aren't fixed — they've shifted downward over time, because YouTube's own encode costs have fallen (notably via Argos, a custom ASIC Google built specifically to accelerate transcoding). As encoding gets cheaper, the view-count bar for "worth the expensive encode" drops.
Encoding happens in parallel chunks, not serially
A two-hour source video encoded serially on one machine would take a long time even on fast hardware. The source is split into smaller chunks — ideally aligned to scene boundaries or I-frames to avoid visible seams — and each chunk is dispatched to an independent worker in a large transcoding fleet, then re-stitched. This is orthogonal to which codec is chosen — it's how any given codec's encode gets done fast once the decision to encode has been made.
The Invariants
- Guarantees: Every uploaded video gets at least one universally-playable rendition quickly, regardless of predicted popularity.
- Does not guarantee: That a given video will ever receive the more efficient codecs — conditional on crossing a view-count bar that itself moves over time. A moderately-watched video may permanently remain on the cheap codec. Nothing at upload time tries to predict virality — the system watches view counts post-upload and re-triggers encoding once a threshold is crossed, meaning an unexpectedly viral video is served the cheap codec for a window, potentially its highest-traffic window, until re-encoding catches up.