Design a Video Streaming Service with ABR and Cross-Device Resume
System DesignModel answerLast updated
Design a large-scale video platform supporting catalog browsing, adaptive-bitrate playback across devices, cross-device resume, and content ingestion.
You are tasked with designing a video streaming service at scale. Users should be able to browse a catalog of content organized by genre and editorial collections (such as "Newly Available" or "Trending Now"), search for titles, stream videos with quality adaptation based on network conditions across web browsers, mobile apps, and connected TVs, and pick up playback from where they stopped on any device. Content creators and studios need to upload video files that are then processed into streamable formats.
Scale and constraints:
- Approximately 50 million daily active users, with peaks of around 5 million concurrent viewers
- Global deployment across multiple regions
- Source video files ranging from 1 to 10 GB
- Target low startup latency (under 2 seconds at p95), minimal rebuffering, high availability, and content protection
Required capabilities:
- Catalog browsing by genre and curated collections
- Full-text search across titles and metadata
- Adaptive-bitrate streaming that adjusts quality based on available bandwidth
- Cross-session and cross-device playback resume
- Video upload and automated processing pipeline
- Authentication, authorization, and concurrent stream limits per account
What to cover:
-
Requirements clarification and scale estimation — Distinguish functional from non-functional requirements, define what you would defer for an initial release serving ~100k users, and calculate bandwidth, request volume, and storage needs.
-
Service boundaries and architecture — Identify the major subsystems (ingestion, catalog, search, playback control, session management, CDN) and how they interact.
-
Data modeling — Schema for content metadata, video assets and quality variants, user accounts and profiles, playback sessions, and watch history.
-
API design — Endpoints for browsing, searching, initiating playback, tracking progress, and uploading content.
-
Video processing pipeline — How uploaded files are validated, transcoded into multiple quality levels, packaged for streaming, protected, and made available.
-
Adaptive streaming mechanics — How quality variants are created, packaged, and delivered; how clients select the appropriate bitrate.
-
Playback session lifecycle — Session initiation, periodic progress updates, concurrency enforcement, and durable resume state.
-
Content discovery features — How "Newly Available" and "Trending Now" collections are computed and served.
-
CDN strategy and caching — Origin versus edge responsibilities, cache policies, and cold-start handling.
-
Scalability, consistency, and fault tolerance — Partitioning strategies, multi-region deployment, consistency guarantees for different data types, and graceful degradation.
-
Observability and cost control — Key metrics, experimentation approach, and techniques to manage bandwidth and compute costs.
Be explicit about trade-offs and implementation priorities.
Hints
Hint 1
Separate the data plane (video bytes via CDN) from the control plane (metadata, session management) and size them independently—egress dominates the former, QPS the latter.
Hint 2
For an MVP with 100k users, defer personalized recommendations, multi-region active-active, and advanced search; focus on browse, play, and resume with a single CDN and tokenized URLs.
Hint 3
Use CMAF with common encryption to produce one segment set that works for both HLS and DASH, reducing storage by half and simplifying the pipeline.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The fundamental insight is recognizing this as two distinct systems: a data plane that moves massive volumes of video bytes through a CDN, and a control plane that handles metadata, playback initiation, progress tracking, and session management. Each has different scaling characteristics and consistency requirements.
1. Requirements and Scale Estimation
Functional Requirements
MVP (100k DAU):
- Browse catalog by genre and editorial collections
- Stream with adaptive bitrate on web, mobile, and TV
- Resume playback across devices
- Internal content upload workflow
Deferred post-MVP:
- Personalized recommendation engine (use popularity-based ranking initially)
- User-generated content uploads
- Multi-CDN routing
- Active-active multi-region writes
- Fuzzy search with typo correction
- 4K/HDR support
Non-negotiable at any scale:
- Time-limited signed URLs for video segments
- DRM for licensed content
- Entitlement verification before playback
- Durable persistence of watch progress
- CDN in front of all video delivery
- Idempotent transcoding to handle retries safely
Non-Functional Targets
- Startup latency (time to first frame) p95 < 2s
- Rebuffer rate < 0.5%
- Playback availability 99.95%
Back-of-Envelope Calculations
At 5M concurrent streams:
- Egress bandwidth: 5M × 5 Mbps average ≈ 25 Tbps peak. This necessitates a CDN with ISP peering or embedded cache nodes. Origin serves only 2–5% of traffic (cache misses).
- Heartbeat load: One update every 30s → 5M / 30 ≈ 170k QPS read/write. Debounced progress persistence (every 60s or on pause) ≈ 85k writes/s.
- Catalog/browse: 50M users × 30 requests/day ≈ 17k average QPS, ~60k peak. Mostly cacheable.
- Storage: A 2-hour title with a full quality ladder requires ~30 GB per codec. Supporting both H.264 and HEVC/AV1 means ~60 GB per title. For 20k titles: ~1.2 PB video assets, plus ~200 TB of source files.
2. High-Level Architecture
[Clients: Web/iOS/Android/TV]
↓
[Edge Gateway: auth, rate limiting, routing]
↓
[Backend-for-Frontend per platform]
├─ Catalog Service (PostgreSQL + Redis)
├─ Search Service (Elasticsearch)
├─ Collections/Rankings Service (materialized in KV store)
├─ Playback Service → Entitlement, Session Manager (Redis), URL Signer
├─ DRM License Service (Widevine/FairPlay/PlayReady)
└─ Progress Service (Cassandra/DynamoDB)
[Upload Service]
↓
[Object Storage (masters)] → [Workflow Orchestrator]
↓
[Transcode Workers (spot instances)] → [Packager (CMAF + CENC)]
↓
[Origin Storage] → [Multi-tier CDN with origin shield]
[Event Stream (Kafka): playback events, heartbeats]
→ Stream processors → collections updates, search index, analytics
3. Data Models
Catalog (PostgreSQL)
title: id, type (movie|series), name, synopsis, maturity_rating,
genres[], cast[], release_date, added_at
season: id, title_id, season_number
episode: id, title_id, season_number, episode_number, duration_ms
license_window: title_id, region, valid_from, valid_to
Video Assets
video_asset: id, episode_id, status, master_location
rendition: asset_id, codec, resolution, bitrate, segment_base_url
drm_metadata: asset_id, key_id, key_reference
Accounts and Profiles
account: id, plan_tier, max_concurrent_streams
profile: id, account_id, maturity_limit, language_preference
device: id, account_id, device_type, last_active
Hot State
- Watch progress (Cassandra/DynamoDB): Partition by
profile_id, sort bytitle_id. Columns:episode_id, position_ms, duration_ms, last_updated, completed_flag. Single-partition query for "Continue Watching." - Active sessions (Redis):
sessions:{account_id}→ sorted set of{session_id: last_heartbeat_timestamp}. - Collections (Redis/Memcached):
collection:{name}:{region}:{rating}→ ordered list of title IDs.
4. API Contracts
Client APIs
GET /v1/browse?profile_id&page
→ {collections: [{id, title, items: [title_card]}]}
GET /v1/genres/{id}/titles?cursor
GET /v1/search?q&genre&year&cursor
POST /v1/playback/start
Body: {title_id, episode_id, device_id, capabilities}
Response: {session_id, manifest_url (signed), license_url,
license_token, resume_position_ms}
Returns 409 if concurrent limit exceeded
POST /v1/playback/{session_id}/heartbeat
Body: {position_ms, bitrate, buffer_health_ms, sequence}
POST /v1/playback/{session_id}/stop
Body: {position_ms, sequence}
GET /v1/continue-watching?profile_id
Upload APIs
POST /v1/uploads
Body: {filename, size, checksum}
Response: {upload_id, presigned_part_urls[]}
POST /v1/uploads/{id}/complete
Body: {parts: [{part_number, etag}]}
GET /v1/uploads/{id}/status
Response: {status: UPLOADED|VALIDATING|TRANSCODING|READY|FAILED}
5. Video Processing Pipeline
- Upload: Presigned multipart URLs allow direct upload to object storage, bypassing API servers.
- Validation: Verify checksum, run media analysis (ffprobe) to detect codec, resolution, frame rate; scan for corruption or policy violations.
- Encoding ladder selection: Define a target ladder (e.g., 240p@235kbps to [email protected], 4K@16Mbps for premium). Use content-aware encoding to prune unnecessary rungs—animation needs less bitrate than live action.
- Parallel chunked transcoding: Split source on GOP boundaries into ~1-minute segments, encode in parallel on spot instances, then concatenate. Workflow orchestrator (Temporal, Step Functions) tracks each chunk with idempotency keys.
- Packaging: Generate CMAF fMP4 segments (4-second chunks, aligned keyframes) for all quality levels. Encrypt with CENC (cbcs scheme) to support Widevine, FairPlay, and PlayReady from a single segment set. Produce both HLS (
.m3u8) and DASH (.mpd) manifests pointing to the same segments—this halves storage. - Auxiliary assets: Generate thumbnail sprites, preview clips, WebVTT subtitles.
- Publish: Upload segments to origin storage, atomically update
video_asset.status = READY, emit event to update search index and "Newly Available" collection, optionally pre-warm CDN edge caches.
6. Adaptive Streaming and DRM
Playback Initialization
POST /playback/start performs:
- Authenticate and identify account/profile
- Verify entitlement: subscription tier, regional licensing window, maturity rating
- Enforce concurrency: Check active session count in Redis; reject with 409 if at limit
- Filter manifest based on device capabilities (codec support, DRM, max resolution)
- Generate signed manifest URL (CDN token with TTL ≈ video duration + buffer, bound to session and IP range) and DRM license token
- Return resume position from Progress Service
Adaptive Bitrate Mechanism
- Client receives a manifest listing all quality variants (e.g., 240p to 1080p)
- Player's ABR algorithm (throughput + buffer-based, e.g., BOLA) selects appropriate quality level
- Each segment URL is signed with short TTL, refreshed as needed
DRM
- Use CENC with multi-DRM (Widevine for Android/Chrome, FairPlay for Apple, PlayReady for Edge/Xbox)
- Licenses are session-scoped, short-lived, renewed via heartbeats
- Fallback: devices without hardware DRM (e.g., Widevine L3) are capped at SD resolution
7. Playback Session and Resume
Session lifecycle:
- Start: Create session record, add to
sessions:{account_id}sorted set - Heartbeat (every 30s): Update last-seen timestamp; debounced writes to Progress Service every 60s or on significant position jump
- Stop: Final progress write with sequence number to prevent stale updates
Concurrency enforcement: Before creating a session, count entries in sessions:{account_id} where last_heartbeat > now - 90s. Reject if at limit. Expired sessions are cleaned up asynchronously.
Resume state: Query Progress Service by profile_id to retrieve last position for the title. Use sequence numbers and timestamps to resolve conflicts when multiple devices update simultaneously (last-write-wins with timestamp tiebreaker).
8. Collections: "Newly Available" and "Trending Now"
Newly Available: Query title.added_at from the catalog, sort descending, materialize top 50 per region/maturity into Redis with TTL. Refresh hourly or on new title publish events.
Trending Now: Consume playback-start events from Kafka, aggregate play counts over a sliding 24-hour window using a stream processor, rank, and materialize. Update every 10–15 minutes.
Serving: GET /browse reads pre-computed lists from Redis (sub-millisecond latency), falling back to catalog if cache miss.
9. CDN and Caching Strategy
- Origin storage: Object storage (S3, GCS) holds all video segments
- Origin shield: Mid-tier cache between CDN edges and origin, reducing origin load
- Edge CDN: Multi-tier with ISP peering. Manifests have short TTL (~60s), segments have long TTL (days to weeks, immutable)
- Cache warming: On new title publish, prefetch high-demand segments (first 30s, popular quality levels) to edge nodes in major markets
- Cold start mitigation: Byte-range requests allow partial segment delivery while fetching from origin
10. Scalability and Fault Tolerance
Partitioning:
- Catalog: Read-heavy, replicated PostgreSQL with Redis cache
- Progress: Partition by
profile_idin wide-column store (Cassandra, DynamoDB) - Sessions: Shard Redis by
account_id
Multi-region:
- Catalog: Async replication, eventual consistency acceptable (stale by seconds)
- Progress: Regional writes with cross-region async replication; conflicts resolved by timestamp
- CDN: Geo-distributed by design
Consistency:
- Catalog metadata: eventual consistency
- Entitlements: strong consistency (fail-closed if unavailable)
- Session concurrency: linearizable reads from Redis
- Progress: last-write-wins with sequence numbers
Graceful degradation:
- CDN failure: Fallback to secondary CDN or direct origin
- License service down: Allow playback of non-DRM content
- Search unavailable: Serve cached browse results
- Transcode backlog: Queue uploads, display "Processing" status
11. Observability and Cost Control
Metrics:
- QoE: Startup latency, rebuffer ratio, bitrate distribution, completion rate
- Backend: API latency (p50/p95/p99), error rates, session concurrency, cache hit ratio
- Cost: CDN egress volume, transcode minutes, storage growth
Experimentation: A/B test ABR algorithms, encoding ladders, and UI features. Use guardrail metrics (rebuffer rate, user retention) to auto-stop harmful experiments.
Cost levers:
- Aggressive CDN caching (90%+ hit rate)
- Content-aware encoding to reduce bitrate without quality loss
- Spot instances for transcoding
- Tiered storage (frequent-access vs archive)
- Per-title popularity-based cache eviction
Common Mistakes
- Ignoring the data/control plane split: Trying to route video through application servers instead of CDN.
- Weak concurrency enforcement: Using stale session data or not accounting for heartbeat delays, allowing limit bypass.
- Write amplification on progress: Writing every heartbeat to disk instead of debouncing.
- Cache TTL mismatch: Long manifest TTL breaks ABR updates; short segment TTL causes origin overload.
- Synchronous transcoding: Blocking upload completion on encoding finish instead of async pipeline with status polling.
- Not planning for idempotency: Transcode retries produce duplicate work or corrupted outputs.
Complexity
- Time: Playback start O(1) with cached entitlement; browse O(1) from materialized collections; search O(log n) in inverted index.
- Space: O(titles × renditions × duration) for video storage; O(profiles) for progress state.
Code Example: Playback Start Logic (Pseudocode)
def start_playback(title_id, episode_id, profile_id, device_id, capabilities):
# 1. Authenticate and load profile
profile = auth_service.verify_and_get_profile(profile_id)
account = account_service.get_account(profile.account_id)
# 2. Check entitlement
episode = catalog_service.get_episode(episode_id)
if episode.maturity_rating > profile.maturity_limit:
raise ForbiddenError("Content rating exceeds profile limit")
if not license_service.is_available_in_region(title_id, profile.region):
raise ForbiddenError("Not available in your region")
# 3. Enforce concurrency
active_sessions = session_manager.get_active_sessions(account.id)
if len(active_sessions) >= account.max_concurrent_streams:
raise ConcurrencyLimitError("Maximum streams reached", 409)
# 4. Create session
session_id = generate_uuid()
session_manager.create_session(account.id, session_id, device_id)
# 5. Get resume position
resume_ms = progress_service.get_position(profile_id, episode_id) or 0
# 6. Generate signed manifest
manifest_url = cdn_signer.sign_url(
base_url=f"/manifests/{episode_id}.m3u8",
session_id=session_id,
ttl=episode.duration_ms + 300000, # duration + 5 min slack
ip_prefix=request.ip_prefix
)
# 7. Filter manifest by capabilities and generate DRM token
if "widevine" in capabilities.drm:
license_token = drm_service.issue_license_token(
episode_id, session_id, "widevine"
)
return {
"session_id": session_id,
"manifest_url": manifest_url,
"license_url": f"/drm/license/{session_id}",
"license_token": license_token,
"resume_position_ms": resume_ms
}
This design balances simplicity for an MVP with clear paths to scale, focusing on correctness in session management, cost efficiency through CDN leverage, and operational visibility.