Case Study 09 โ€” Video Streaming

Design a YouTube-like video streaming platform: creators upload videos, the system transcodes them into multiple qualities, and viewers watch with adaptive playback.

1. Problem

Video files are orders of magnitude larger than photos (a 10-minute 1080p upload might be 500 MBโ€“2 GB). Viewers expect:

  • Smooth playback with quality adapting to their bandwidth
  • Fast start โ€” playback begins within a few seconds (not after full download)
  • Global reach โ€” low latency via CDN edge caches

The core challenge is the upload โ†’ transcode โ†’ distribute pipeline, plus metadata and discovery (search, subscriptions feed).

2. Requirements

Functional (MVP)

  • Upload video (title, description, thumbnail)
  • Process / transcode to multiple resolutions (360p, 720p, 1080p)
  • Stream playback with adaptive bitrate (ABR)
  • Video detail page โ€” watch, view count
  • Channel page โ€” list creator's videos
  • Subscribe to channels; home feed of new uploads from subscriptions
  • Basic search by title (optional MVP stretch)

Out of scope (initially)

  • Live streaming, DRM/studio content, monetization/ads, comments moderation ML, Shorts, 4K/HDR, offline download

Non-functional

  • Time to first frame < 3 s for cached popular content
  • Upload pipeline completes in minutes (not hours) for 1080p 10-min video
  • 1B hours watched/month, 500k uploads/day
  • 99.9% availability for playback (CDN + multi-origin)
  • Cost-efficient storage tiering for long-tail videos

3. Back-of-the-envelope estimates

We do rough math so we know what to optimize. Exact precision is not the goal โ€” order of magnitude is.

Why we estimate (beginner tip)

Ask three questions:

  1. How busy? โ†’ QPS (requests per second)
  2. How much data? โ†’ storage (GB/TB)
  3. How fat is the pipe? โ†’ bandwidth (MB/s) when media matters

Cheat sheet: 1 QPS โ‰ˆ 86,400 requests/day. Peak is often 2โ€“5ร— average.

Assumptions (say these out loud)

  • 500k video uploads/day; average raw upload 5 GB
  • Transcode to 4 renditions (360p, 720p, 1080p, etc.) totaling ~30% of original size โ‰ˆ 1.5 GB stored per video
  • 1B hours watched per month; average playback bitrate 2 Mbps (adaptive HLS)
  • Video metadata row โ‰ˆ 2 KB (title, description, manifest URLs, status)
  • Popular videos cached at CDN edge; long-tail served from origin on cache miss

Step A โ€” Traffic (QPS)

Upload QPS:
  500k / day รท 86,400 โ‰ˆ 6/s average (each upload is long-running multipart)
  Concurrent uploads at peak: hundreds to low thousands (not same as QPS)

Concurrent streams (playback):
  1B hours/month รท 730 hours/month โ‰ˆ 1.37M average concurrent viewers
  Peak (rush hour multiplier ~2โ€“3ร—)     โ‰ˆ 2โ€“4M concurrent streams

Metadata API QPS (video detail, manifest URL):
  Much lower than stream count โ€” player hits CDN for segments, API for JSON
  Estimate ~50k/s peak for browse/search/detail combined

Step B โ€” Storage

Raw upload ingress per day:
  500k ร— 5 GB โ‰ˆ 2.5 PB/day to S3 raw bucket

Transcoded storage (1 year, 1.5 GB per video):
  500k ร— 1.5 GB ร— 365 โ‰ˆ 270 PB/year

Metadata DB (1 year):
  500k ร— 365 ร— 2 KB โ‰ˆ 365 GB โ€” manageable with sharding

Lifecycle: Standard (hot 30 days) โ†’ IA โ†’ Glacier for long-tail

Step C โ€” Bandwidth / other (if relevant)

CDN egress at peak playback (the dominant cost):

2M concurrent streams ร— 2 Mbps โ‰ˆ 4 Tbps peak CDN egress

Segment size (6s HLS chunk at 2 Mbps):
  2 Mbps ร— 6s / 8 โ‰ˆ 1.5 MB per segment
  Player fetches ~10 segments/min โ‰ˆ 15 MB/min/user

Upload ingress:
  2.5 PB/day โ‰ˆ 29 GB/s average raw upload to S3 (multipart, parallel parts)

Transcode compute (separate from bandwidth):

10-min 1080p video โ‰ˆ 5โ€“15 min on one FFmpeg worker
500k uploads/day ร— 10 min avg โ‰ˆ need thousands of parallel transcode workers (spot instances)

Step D โ€” Read:write ratio

PathApprox shareImplication
Segment download (CDN read)~99.9% of bytesHLS/DASH segments from CDN โ€” API never streams video
Manifest + metadata APITiny QPS vs streamsReturn master.m3u8 URL; signed CDN URLs
Upload + transcode (write)500k/dayAsync pipeline: S3 event โ†’ queue โ†’ FFmpeg workers
View count beaconsFire-and-forgetKafka โ†’ aggregate; approximate counts OK

What the numbers tell us

  • 4 Tbps peak CDN egress โ†’ major CDN provider; 95%+ edge hit rate for popular content
  • 270 PB/year transcoded storage โ†’ lifecycle policies; don't keep all renditions in Standard tier forever
  • 2.5 PB/day upload ingress โ†’ multipart upload to S3; API only orchestrates, never proxies bytes
  • Thousands of FFmpeg workers โ†’ job queue + spot instances; transcode is async (minutes, not seconds)
  • HLS 6-second segments enable adaptive bitrate and fast start from CDN cache
  • 365 GB/year metadata โ†’ API serves JSON + manifest URLs only; playback is 100% CDN

Common mistake for this problem

Serving one giant MP4 file from the API server with progressive download. At 2M concurrent viewers ร— 2 Mbps, your origin dies โ€” use HLS/DASH segmented delivery via CDN with adaptive bitrate switching.

4. High-Level Design (HLD)

Components

ComponentRole
Video APIUpload session, metadata CRUD, playback manifest URLs
S3 Raw BucketOriginal uploads (multipart)
Transcode OrchestratorSplit job into renditions; track state machine
Transcoding WorkersFFmpeg fleet: H.264/H.265 โ†’ HLS segments per resolution
S3 Processed Bucket{videoId}/360p/seg_001.ts, manifests .m3u8
CDNCache segments and manifests at edge
Metadata DBVideo info, processing status, view counts
Subscription FeedNew uploads from subscribed channels
Search IndexTitle, description, tags (async index on publish)
Thumbnail GeneratorSprite / poster frame at 10% timestamp

Flows

Upload video

  1. Creator POST /videos/upload/init โ†’ { videoId, uploadId, presignedMultipartUrls[] }
  2. Client uploads parts to S3; POST /videos/upload/complete with part ETags
  3. API creates metadata row status = uploaded; Orchestrator enqueues transcode job
  4. Return 202 โ€” processing async

Transcode pipeline

  1. Worker pulls job, downloads raw from S3 (or S3 โ†’ worker in same region)
  2. Probe: duration, codec, resolution
  3. For each profile (360p, 720p, 1080p): FFmpeg โ†’ HLS segments (6s each) + .m3u8 playlist
  4. Upload segments to s3://processed/{videoId}/{profile}/
  5. Generate master playlist .m3u8 listing all renditions (ABR)
  6. Generate thumbnail; update metadata status = ready, CDN URLs
  7. Index in search; fan-out to subscribers' feeds

Playback (viewer)

  1. Client GET /videos/:id/play โ†’ { masterManifestUrl, title, ... }
  2. CDN URL: https://cdn.example/videos/{id}/master.m3u8
  3. Video player (hls.js / native) fetches master โ†’ picks rendition โ†’ downloads segments adaptively
  4. API server never streams bytes โ€” only metadata + signed CDN URLs

View count

  1. Player beacons POST /videos/:id/view every 30s or on start
  2. Aggregate via Kafka โ†’ counter workers โ†’ DB (approximate counts OK)

Trade-offs

Streaming protocolProsCons
HLSApple/mobile friendly; CDN standardHigher latency than LL-HLS
DASHCodec agnosticSlightly more complex
Progressive MP4SimpleNo ABR; bad for long videos
TranscodingNotes
Batch FFmpeg workersFlexible; industry standard
Managed (MediaConvert)Less ops; higher $/minute
Per-title encodingBetter quality/size; expensive

| Storage tier | Hot new uploads on Standard; long-tail โ†’ IA/Glacier after 90 days |

| Popular vs long-tail | CDN caches hot videos; origin fetch for rare views acceptable |

5. Low-Level Design (LLD)

APIs

POST /api/v1/videos/upload/init
Body: { "title": "...", "contentType": "video/mp4", "fileSize": 500000000 }
โ†’ 201 {
     "videoId": "v_abc",
     "uploadId": "mpu_xyz",
     "partSize": 10485760,
     "presignedUrls": [ "..." ]
   }

POST /api/v1/videos/upload/:uploadId/complete
Body: { "parts": [ { "partNumber": 1, "etag": "..." } ] }
โ†’ 202 { "videoId": "v_abc", "status": "processing" }

GET /api/v1/videos/:videoId
โ†’ 200 {
     "videoId", "title", "description", "status": "ready",
     "durationSec": 600,
     "thumbnailUrl": "https://cdn.../thumb.jpg",
     "playManifestUrl": "https://cdn.../master.m3u8",
     "viewCount": 1234567
   }

GET /api/v1/videos/:videoId/play
โ†’ 200 { "manifestUrl": "...", "expiresAt": "..." }   // optional signed URL

GET /api/v1/feed/subscriptions?limit=20&cursor=...
GET /api/v1/channels/:channelId/videos?limit=20

POST /api/v1/channels/:channelId/subscribe
POST /api/v1/videos/:videoId/view
Body: { "watchTimeSec": 30, "sessionId": "..." }

Schema / tables

channels (
  channel_id     BIGINT PRIMARY KEY,
  owner_user_id  BIGINT NOT NULL,
  name           VARCHAR(100),
  subscriber_count INT DEFAULT 0
)

videos (
  video_id       VARCHAR(36) PRIMARY KEY,
  channel_id     BIGINT NOT NULL,
  title          VARCHAR(200) NOT NULL,
  description    TEXT,
  status         ENUM('uploading','processing','ready','failed') NOT NULL,
  s3_raw_key     TEXT NOT NULL,
  duration_sec   INT,
  thumbnail_url  TEXT,
  manifest_url   TEXT,
  view_count     BIGINT DEFAULT 0,
  created_at     TIMESTAMPTZ NOT NULL,
  published_at   TIMESTAMPTZ,
  INDEX (channel_id, published_at DESC)
)

transcode_jobs (
  job_id         VARCHAR(36) PRIMARY KEY,
  video_id       VARCHAR(36) NOT NULL,
  status         ENUM('queued','running','done','failed'),
  profiles       JSONB,              -- ["360p","720p","1080p"]
  progress_pct   INT DEFAULT 0,
  error_message  TEXT,
  created_at     TIMESTAMPTZ NOT NULL,
  INDEX (video_id)
)

subscriptions (
  user_id        BIGINT NOT NULL,
  channel_id     BIGINT NOT NULL,
  created_at     TIMESTAMPTZ NOT NULL,
  PRIMARY KEY (user_id, channel_id),
  INDEX (channel_id)
)

video_renditions (
  video_id       VARCHAR(36) NOT NULL,
  profile        VARCHAR(10) NOT NULL,   -- 360p, 720p, 1080p
  playlist_url   TEXT NOT NULL,
  bandwidth_bps  INT,
  PRIMARY KEY (video_id, profile)
)

S3 layout

raw/{videoId}/source.mp4
processed/{videoId}/master.m3u8
processed/{videoId}/360p/index.m3u8
processed/{videoId}/360p/segment_00001.ts
processed/{videoId}/720p/...
processed/{videoId}/thumb_1280.jpg

Modules

UploadController / VideoController / FeedController
MultipartUploadService    โ€” S3 MPU init/complete
TranscodeOrchestrator     โ€” state machine, enqueue profiles
FfmpegWorker              โ€” run transcode, upload segments
ManifestBuilder           โ€” master.m3u8 generation
PlaybackService           โ€” signed CDN URLs, geo restrictions
ViewCounterAggregator     โ€” Kafka consumer
SubscriptionFeedService   โ€” fan-out on new publish (reuse feed patterns)
SearchIndexer             โ€” Elasticsearch sync

Key algorithms (pseudocode)

Transcode orchestrator

function onUploadComplete(videoId):
  video = videoRepo.get(videoId)
  jobId = uuid()
  profiles = selectProfiles(video.probeMetadata)   // skip 1080p if source is 720p
  jobRepo.insert({ jobId, videoId, status: "queued", profiles })
  for profile in profiles:
    queue.publish("transcode", { jobId, videoId, profile, s3RawKey: video.s3RawKey })

function transcodeWorker(task):
  rawPath = s3.download(task.s3RawKey)
  outDir = tempDir()
  if task.profile == "360p":
    scale = "640:360"
  else if task.profile == "720p":
    scale = "1280:720"
  else:
    scale = "1920:1080"

  ffmpeg.run(
    input: rawPath,
    output: outDir + "/segment_%05d.ts",
    scale: scale,
    codec: "libx264",
    hlsTime: 6,
    hlsListSize: 0
  )
  s3.uploadDir(outDir, "processed/" + task.videoId + "/" + task.profile + "/")
  playlistUrl = cdn.url("processed/" + task.videoId + "/" + task.profile + "/index.m3u8")
  renditionRepo.upsert(task.videoId, task.profile, playlistUrl, bandwidth)
  jobRepo.markProfileDone(task.jobId, task.profile)

  if jobRepo.allProfilesDone(task.jobId):
    masterUrl = manifestBuilder.buildMaster(task.videoId)
    thumbUrl = thumbnailGenerator.generate(task.videoId, rawPath, atSec=10)
    videoRepo.update(task.videoId, { status: "ready", manifestUrl: masterUrl, thumbnailUrl: thumbUrl })
    searchIndex.index(videoRepo.get(task.videoId))
    subscriptionFeed.fanOut(task.videoId)

Master playlist (ABR)

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360
360p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=2500000,RESOLUTION=1280x720
720p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080
1080p/index.m3u8

Adaptive playback (client-side)

function playVideo(manifestUrl):
  player.load(manifestUrl)
  loop every segment:
    bandwidth = measureDownloadRate()
    player.selectRendition(maxBitrate: bandwidth * 0.8)
    // player automatically switches up/down between HLS variants

View count aggregation

function onViewEvent(videoId, watchTimeSec, sessionId):
  if watchTimeSec < 10: return   // ignore accidental clicks
  kafka.publish("views", { videoId, sessionId, ts: now() })
  // dedupe by sessionId per day in Flink/Spark
  aggregatedCounts.flushToDb(every 5 min)

Concurrency notes

  • Multipart upload โ€” parts upload in parallel; complete call is atomic in S3
  • Transcode job idempotency โ€” check rendition exists before re-running worker retry
  • Status state machine โ€” uploading โ†’ processing โ†’ ready; illegal transitions rejected
  • View counts โ€” approximate; dedupe by (videoId, sessionId, day) in stream processor
  • CDN signed URLs โ€” short TTL (1โ€“4 h); manifest refresh during long playback
  • Hot video โ€” single origin path; CDN shield prevents S3 overload

6. Scale evolution

StageChange
MVPSingle S3 bucket; one FFmpeg worker; progressive MP4 + CDN (no ABR)
GrowthHLS ABR; transcode queue + worker pool; CloudFront; subscription feed
ScaleRegional upload buckets; spot transcode fleet; ES search; view counter pipeline
HugePer-title encoding; multi-CDN; peer-assisted delivery research; Glacier for archives

7. Recap

  • S3 + CDN + transcoding โ€” the holy trinity for video; API only serves metadata and manifest URLs
  • HLS/DASH segments enable adaptive bitrate and fast start via CDN edge caches
  • Async transcode pipeline with job queue; upload ack is immediate, ready comes later
  • View counts and search are async aggregates โ€” don't block playback path

Practice: Explain why serving one giant MP4 from your API server fails at YouTube scale. What does the client download instead?