Video Streaming (YouTube/Netflix)

Video is bandwidth- and CPU-dominated. The architecture is an ingestion pipeline feeding a CDN, with the database storing only metadata and state. The hard parts are not “upload a file.” They are resumable uploads, long-running idempotent jobs, bad inputs, cache behaviour, access control, deletion, and a cost curve that punishes every shortcut.

This chapter focuses on the process and failure handling. Code is illustrative; the pipeline and state machine are the deliverable.

Scope

In scope for v1

  • Upload (large files, resumable, multipart).
  • Validate and probe the input.
  • Transcode to multiple resolutions/bitrates.
  • Package HLS/DASH for adaptive playback.
  • Public/private videos with signed access.
  • Thumbnails and optional captions.
  • View analytics (aggregate).
  • Delete and storage lifecycle.

Out of scope for v1

  • Live streaming (different latency and failure model).
  • Recommendations.
  • Collaborative editing.
  • Full DRM (plan for it if licensing requires).
  • Multi-region active-active ingestion.

Actors and journeys

Actor Goal What can go wrong
Creator Upload a large file and publish it Connection drops, upload resumes twice, transcode stuck
Viewer Press play and watch without buffering Segment 404, bad manifest, signed URL expired
Moderator Remove a video Segments remain cached, CDN serves deleted content
Operator Keep the pipeline moving and costs bounded Poison input, worker crash loop, storage growth
Finance Understand unit economics Egress and transcoding cost explode

The critical journeys:

  1. Upload → validate → transcode → publish, with resumability at every step.
  2. Playback from the CDN with adaptive bitrate and correct access control.
  3. Delete or make private, and verify the content is no longer reachable.

Invariants

  1. The raw upload is immutable. Every derived rendition is traceable to one source object and one pipeline version.
  2. A video is not published until every required rendition and manifest exists. Partial publishing is a bug.
  3. Transcode jobs are idempotent by (videoId, rendition, pipelineVersion, attempt). Retries must not create duplicate outputs.
  4. Segments and manifests are immutable objects with versioned names. Publishing is a metadata flip, not an overwrite.
  5. Access control is enforced at playback, not only at the UI. Private videos require signed URLs/cookies with short TTLs.
  6. Deletion removes metadata, objects, and cache reachability. A tombstone alone is not deletion.
  7. The CDN is the delivery path, not the origin. Origin egress at scale is a design failure.
  8. Every job has a terminal state. A video can be failed with a reason, not stuck in processing forever.

Estimates

1M uploads/day × 500 MB average = 500 TB/day ingested
transcode: 1 hour of video → roughly 1–2 CPU-hours across the ladder (varies by codec, resolution, content)
playback: 10M concurrent viewers × 5 Mbps = 50 Tbps at the edge
metadata: 1M rows/day, tiny compared to media

Storage and egress dominate cost. The CDN is not optional. The transcode ladder, codec choice, and lifecycle rules decide whether the unit economics work.

A useful back-of-the-envelope:

storage/month ≈ uploads/day × avg size × 30 × replication factor
egress/month  ≈ watch hours × bitrate × 3600 × CDN price
transcode CPU ≈ video minutes × ladder factor

Model these before choosing a ladder. A 4K rendition that nobody watches is a permanent storage tax.

End-to-end flows

1. Create an upload session

client
  → POST /videos { title, sizeBytes, contentType }
  → auth + quota check
  → validate declared size/type (advisory only)
  → create video row: status=uploading
  → create multipart upload in object storage
  → return { videoId, uploadId, partUrls, partSize, expiresAt }

Rules:

  • Do not proxy large files through the API servers.
  • Pre-sign each part with a short expiry; refresh on request.
  • Record the expected part count and checksum strategy.
  • Reject early if the account quota or per-file limit is exceeded.

2. Upload parts and complete

client
  → PUT part 1..N directly to object storage
  → retry failed parts independently
  → POST /videos/{id}/complete { parts: [{partNumber, etag}] }
  → server completes multipart upload
  → HEAD object: size, checksum, content type
  → enqueue probe job
  → status=processing

Failure branches:

  • Part fails: retry that part; do not restart the whole upload.
  • Complete called twice: return the same result; do not create a second object.
  • Client disappears: expire the multipart upload after a TTL and clean up orphaned parts.
  • Declared size/type lies: validate the actual object with HEAD, sniffing, and a probe. Do not trust headers.
  • Checksum mismatch: mark the upload failed and require a new session.

3. Validate and probe

object storage
  → probe (ffprobe or equivalent)
  → extract duration, codecs, resolution, bitrate, rotation, audio tracks
  → reject unsupported/unsafe inputs
  → if valid: status=transcoding; enqueue jobs
  → if invalid: status=failed with a user-visible reason

Checks:

  • Container and codec allowlist.
  • Duration and resolution limits.
  • Audio track count and channel layout.
  • Malware scan (async) before publishing.
  • No hidden multi-part tricks or decompression bombs.
  • File size and duration limits per plan.

4. Transcode

probe result
  → choose ladder based on source, plan, and content complexity
  → split into segments/chunks
  → transcode each rendition (parallel where possible)
  → write immutable outputs to object storage
  → verify output duration/streams
  → package HLS/DASH
  → publish metadata atomically

Ladder example:

Rendition Resolution Bitrate When to include
240p 426×240 300 kbps Always, for compatibility
480p 854×480 800 kbps Mobile/default
720p 1280×720 2.5 Mbps Most content
1080p 1920×1080 5 Mbps HD source
4K 3840×2160 15–25 Mbps Only if source and audience justify it

Decisions:

  • Codec: H.264 for compatibility; HEVC/AV1 for bandwidth savings where decode support exists.
  • Per-title encoding: analyze complexity; a talking-head video does not need the same bitrate as sports.
  • Chunking: split long videos into segments and transcode in parallel; merge with a manifest.
  • Priority: small/paid uploads first; fairness across tenants.
  • Retry budget: a poison input must not retry forever. After N attempts, mark failed and quarantine.

5. Package

renditions
  → segment into 2–6 s chunks
  → write per-rendition playlists
  → write master manifest
  → version object names (e.g., v1/…)
  → publish: update video.status=published and manifest pointer

Rules:

  • Manifests are mutable metadata only through a versioned pointer; never overwrite a manifest that players may be using.
  • Segments are immutable and cacheable aggressively.
  • Keep the first segment small to reduce startup time.
  • Validate that every rendition has the same timeline/duration within tolerance.

6. Playback

viewer
  → GET /videos/{id}/playback
  → auth + entitlement check
  → return signed manifest URL (short TTL)
  → player requests manifest from CDN
  → player selects rendition
  → player fetches segments from CDN
  → ABR switches based on throughput/buffer
  • Private content: sign the manifest and/or segment URLs with short expiry; bind to session/user where possible.
  • Cache segments aggressively; cache manifests briefly.
  • Use origin shield/request collapsing so a cold popular video does not melt the origin.
  • Do not put long-lived credentials in URLs. Rotate signing keys and support overlap during rotation.

7. Delete or make private

owner/admin
  → update metadata: status=deleted/private
  → publish invalidation
  → purge CDN manifests/segments (or let short TTLs expire)
  → delete derived renditions
  → delete raw upload per retention policy
  → keep a tombstone/audit record

Deletion must be verified from the outside: request the old manifest/segment URL and confirm it is no longer accessible. A metadata flag is not enough if the CDN still has the bytes.

Data model and state

CREATE TABLE videos (
  id            uuid PRIMARY KEY,
  owner_id      uuid NOT NULL,
  title         text NOT NULL,
  status        text NOT NULL, -- uploading | processing | published | failed | deleted
  source_key    text,
  manifest_key  text,
  duration_ms   bigint,
  visibility    text NOT NULL DEFAULT 'private',
  pipeline_ver  integer NOT NULL DEFAULT 1,
  failure_code  text,
  created_at    timestamptz NOT NULL DEFAULT now(),
  published_at  timestamptz,
  deleted_at    timestamptz
);

CREATE TABLE transcode_jobs (
  id            uuid PRIMARY KEY,
  video_id      uuid NOT NULL,
  rendition     text NOT NULL,
  pipeline_ver  integer NOT NULL,
  attempt       integer NOT NULL DEFAULT 1,
  status        text NOT NULL, -- queued | running | done | failed
  started_at    timestamptz,
  finished_at   timestamptz,
  error         text,
  UNIQUE (video_id, rendition, pipeline_ver, attempt)
);

State machine:

uploading → processing → published
     │           │
     └───────────┴──→ failed
published → private/deleted

Every transition should be idempotent and recorded with a timestamp and reason.

Edge cases

Case Expected behavior Notes
Upload connection drops Resume from the last part Multipart + per-part retry
Complete called twice Same result, no duplicate object Idempotent completion
Part uploaded twice Last write wins or checksum verifies Object storage semantics
Declared MIME is wrong Sniff/probe and reject if unsupported Do not trust headers
Corrupt container failed with a clear reason Quarantine, do not retry forever
Video has no audio Publish silently or with a policy Player must handle
Multiple audio tracks Preserve or expose as options Ladder decision
Variable frame rate Normalize or preserve correctly Timing bugs are visible
Rotated phone video Apply rotation metadata Wrong orientation is a support ticket
Very long video Chunked transcode with progress Bounded job time
Very short video Skip unnecessary renditions Cost
4K source, mobile audience Cap ladder by plan Do not pay for unused quality
Transcode worker dies Retry the chunk/job Idempotent outputs
Poison input crashes worker Quarantine after N attempts DLQ + alert
CDN cache miss storm Origin shield + request collapsing Protect origin
Manifest cached after publish Versioned pointer + short TTL Stale renditions
Signed URL expires mid-playback Player refreshes via playback API Do not use one-hour URLs for a long movie? Plan
Private video leaked URL Short TTL + revocation Signed URL is bearer access
Delete while viewers are watching Existing sessions may continue per policy CDN purge has a lag
Storage lifecycle deletes raw too early Keep raw per reprocessing policy Re-encode needs the source
Region outage Fail playback to another region/CDN Multi-CDN/origin failover

Failure modes and recovery

Failure Impact Detection Mitigation Recovery
Transcode backlog Videos stuck in processing Queue depth, age Autoscale workers, priority queues, ETA Drain backlog; notify users
Poison input Worker crash loop Repeated attempts for one video Validation, quarantine, DLQ Fix input or fail with reason
Worker dies mid-job Partial outputs Missing manifest/segments Idempotent jobs, checkpoints Retry; clean orphaned outputs
Object storage errors Upload/transcode failures 5xx rate, checksum failures Retries with backoff, multi-part resume Re-upload/retry; verify objects
CDN miss storm Origin overload Origin QPS, cache hit ratio Origin shield, collapsing, prewarm Scale origin; prewarm popular content
Stale manifest Players see old renditions QoE errors, version mismatch Versioned names, short manifest TTL Flip pointer; purge/publish new version
Signed URL leak Unauthorized playback Access logs, reports Short TTL, session binding, revocation Rotate keys; purge; audit
Storage cost creep Margin collapse Cost per hour/GB Lifecycle tiers, per-title encoding, raw deletion Re-encode; delete unused renditions
Encoding bug Bad playback on a device QoE by device/codec Canary renditions, device matrix Re-encode affected ladder; rollback pointer
Delete does not propagate Content still reachable External synthetic check Purge + short TTL + tombstone Purge again; verify from outside
Metadata DB down No new playback/upload decisions DB health Cached playback URLs, read replicas Fail over; reconcile state

Degraded-mode rules:

  1. Keep existing playback working even if uploads are down.
  2. Prefer serving a lower rendition over failing playback.
  3. Prefer a clear “processing failed” state over an infinite spinner.
  4. Never publish a partial ladder. A broken manifest is worse than a delayed publish.

Operations

Pipeline operations

  • Separate queues for probe, transcode, package, thumbnails, and delete.
  • Per-tenant fairness; cap concurrent jobs per owner.
  • Store job attempts and errors; alert on age, not just queue depth.
  • Reap orphaned multipart uploads and partial outputs on a schedule.
  • Keep a reprocessing path for codec/security fixes; version the pipeline.

Cost and lifecycle

  • Delete or archive raw uploads after a defined window, unless reprocessing is a product requirement.
  • Move long-tail renditions to infrequent-access storage.
  • Expire unused renditions and thumbnails.
  • Model storage, transcode CPU, and egress per 1,000 watch hours.
  • Watch the “zombie video” case: uploaded, never published, still stored.

Monitoring

  • Upload success rate, part retry rate, completion latency.
  • Queue depth and job age per stage.
  • Transcode failure rate by input type/codec.
  • Publish latency from upload completion.
  • CDN hit ratio, origin egress, startup time, rebuffer ratio.
  • Playback errors by device, region, and rendition.
  • Deletion propagation checks.

Incident process

  1. Is upload, processing, or playback broken? Check each stage separately.
  2. Is it one video, one codec, one region, or all? Check poison inputs and regional CDN health.
  3. Contain: pause new transcode jobs if the queue is poisoned; shift traffic to a healthy CDN; serve a lower rendition.
  4. Recover: replay jobs idempotently, clean partial outputs, republish manifests, verify playback from multiple regions.
  5. Learn: add input validation, a canary, or a cost guard.

Testing strategy

  • Upload: resume after dropped parts, duplicate complete, checksum mismatch, expired session.
  • Probe: corrupt files, wrong MIME, unusual codecs, rotated video, multi-audio.
  • Transcode: idempotent retries, worker death, poison input, partial outputs.
  • Packaging: manifest duration consistency, segment continuity, version pointer.
  • Playback: ABR switching, signed URL expiry, CDN miss, origin shield.
  • Delete: metadata, objects, CDN purge, external verification.
  • Load: cold popular video, concurrent uploads, transcode backlog.
  • Chaos: kill workers, pause queue, fail object storage, expire CDN cache.

Milestones and acceptance criteria

Milestone Build Accept when
1. Upload Pre-signed multipart + metadata A 5 GB file uploads resumably; duplicate complete is safe
2. Validate Probe + allowlist + failure state Bad input fails with a reason, not a stuck job
3. Single rendition Transcode + store + playback One rendition plays from object storage
4. HLS + CDN Package + CDN delivery ABR works; origin is not hit per segment
5. Ladder Multiple renditions + per-title choice Player switches without gaps; cost is modelled
6. Access Private videos + signed URLs Unauthorized URL fails; expiry/refresh works
7. Lifecycle Delete + archive + purge Deleted content is unreachable from outside
8. Drills Load + chaos Backlog, poison input, CDN miss storm meet recovery SLO

Review questions

  • Why should uploads bypass the API servers?
  • How do you make transcoding idempotent and resumable?
  • What happens when a worker dies mid-job?
  • What is the cache TTL for manifests vs segments, and why?
  • How does a private video work end to end?
  • How do you prove a deleted video is actually unreachable?
  • What is the egress cost at 10M concurrent viewers?
  • Which failures degrade playback, and which fail closed?
  • How do you reprocess content after a codec/security fix?

Checklist

  • Uploads go directly to object storage with resumable parts.
  • Input is validated and scanned before publishing.
  • Transcode jobs are idempotent with retries, checkpoints, and a DLQ.
  • Renditions are immutable; publishing flips a versioned pointer.
  • Manifests/segments are CDN-cached with correct TTLs.
  • Private content uses short-lived signed access and revocation.
  • Deletion removes metadata, objects, and cache reachability.
  • Storage lifecycle and egress costs are modelled.
  • QoE metrics and playback error alerts exist.
  • Poison inputs have a terminal failed state.
  • Reprocessing and pipeline versioning are possible.