System Design: Netflix Architecture for Global Streaming
A hypothetical streaming architecture exercise informed by public Open Connect material, with explicit assumptions for capacity, delivery, and playback design.
This is a streaming-service design exercise informed by public descriptions of Netflix Open Connect, not a specification of Netflix's current internals. It separates documented content-delivery facts from assumed workload targets, works through one recalculable bandwidth estimate, and treats HTTP/3 as an option only on supported client and delivery paths. Use the model to replace the sample inputs with measured product requirements.
System Design: Netflix Architecture for Global Streaming
This is a design exercise for a hypothetical global streaming service, informed by public material about Netflix. Netflix’s Open Connect program describes partnerships with ISPs and content-delivery appliances placed within ISP networks. That public information does not describe the company’s complete current architecture.
The components, service boundaries, traffic values, availability goals, storage choices, and failure cases below are assumptions for the exercise unless explicitly identified as public information. They should not be read as claims about Netflix’s internal systems or current subscriber and viewing metrics.
Requirements Analysis
Functional Requirements
Users need to:
- Browse and search a catalog of movies and TV shows
- Stream video content on various devices
- Create and manage profiles
- Continue watching across devices
- Rate and review content
Exercise targets
For this hypothetical service, start with these targets and replace them with product requirements before sizing infrastructure:
- Stream in 4K HDR with surround sound
- Start playback in under 2 seconds
- Support a specified peak concurrent stream count, derived from the exercise workload
- Meet an availability objective chosen by the product owner
- Work on 1000+ device types
Recalculable capacity estimate
Let C be the assumed number of simultaneous streams, R the measured average delivered bitrate in Mbps per stream, and H the headroom multiplier selected for the exercise. Then the starting egress estimate is C × R × H Mbps. For example, using explicit hypothetical inputs of C = 100,000, R = 5 Mbps, and H = 1.3 gives 650,000 Mbps (650 Gbps) of aggregate egress before accounting for regional distribution, protocol overhead, cache misses, or peak shape. These inputs are not Netflix measurements; replace them with workload data and include only capacity the service must provide itself.
Content Delivery Architecture
Public Open Connect material describes Netflix’s CDN and its ISP partnerships. This design exercise uses a similar edge-cache placement pattern; the architecture below is a proposal, not a description of Netflix’s current routing or origin systems.
Open Connect CDN
graph TB
A[Content Origin] --> B[ISP Interconnects]
B --> C[Open Connect Appliances]
C --> D[Residential Routers]
D --> E[Devices]
subgraph "ISP Network"
B
end
subgraph "Customer Premise"
C
D
end
Netflix’s public Open Connect materials describe content-delivery appliances hosted through ISP partnerships to localize traffic. See the Open Connect overview for the program’s published scope; this diagram is a simplified design exercise and does not show Netflix’s current topology.
Request Flow
sequenceDiagram
participant D as Device
participant OCA as Open Connect Appliance
participant CS as Control Plane
participant LS as License Server
D->>CS: GET /manifest.m3u8
CS->>D: Return manifest with URL to nearest OCA
D->>OCA: GET /video/segment1.ts
OCA-->>D: Video segment
D->>LS: GET /license for DRM
LS-->>D: License key
D->>OCA: GET /video/segment2.ts
OCA-->>D: Video segment
Video Encoding Pipeline
graph LR
A[Source Video] --> B[Transcode Cluster]
B --> C{HD or 4K?}
C -->|4K| D[4K Encode Farm]
C -->|HD| E[HD Encode Farm]
D --> F[Output Profiles]
E --> F
F --> G[CDN Origins]
G --> H[Edge Cache]
The hypothetical service encodes each title into multiple renditions. Its player uses the manifest and current network and buffer measurements to choose a rendition; the specific codecs and ladder depend on supported devices and content requirements.
| Profile | Resolution | Bitrate | Codec |
|---|---|---|---|
| 4K HDR | 3840x2160 | 16 Mbps | H.265/VP9 |
| 1080p | 1920x1080 | 5 Mbps | H.264/H.265 |
| 720p | 1280x720 | 2.5 Mbps | H.264 |
| 480p | 854x480 | 1 Mbps | H.264 |
| Audio | Stereo/5.1/Atmos | 192-768 kbps | AAC |
Streaming Protocol
For this exercise, the player uses adaptive bitrate streaming and selects from the renditions exposed by a manifest according to measured network and buffer conditions.
HLS/DASH Manifest
sequenceDiagram
participant D as Device
participant CDN as CDN
participant L as License Server
Note over D: Initial playback request
D->>CDN: GET /title/1234/manifest.m3u8
CDN-->>D: M3U8 with quality levels
Note over D: Parse quality levels
D->>CDN: GET /title/1234/video_4k.m3u8
CDN-->>D: Segment list
D->>CDN: GET /title/1234/video_4k/segment1.ts
CDN-->>D: Video segment
D->>L: GET /widevine/license
L-->>D: DRM license
Note over D: Decode and display
D->>CDN: GET /title/1234/video_4k/segment2.ts
CDN-->>D: Video segment
Adaptive Bitrate Logic
class AdaptiveBitrateController:
def __init__(self, bandwidth_calculator: BandwidthCalculator):
self.bandwidth_calculator = bandwidth_calculator
self.current_quality = "auto"
self.quality_levels = ["4k", "1080p", "720p", "480p", "360p"]
def select_quality(self, buffer_level: float, throughput: float) -> str:
# Rules-based adaptation
if buffer_level < 10: # Buffer running low
return self._downgrade()
elif buffer_level > 60: # Buffer healthy
return self._upgrade(throughput)
else:
return self.current_quality
def _downgrade(self) -> str:
current_idx = self.quality_levels.index(self.current_quality)
if current_idx < len(self.quality_levels) - 1:
return self.quality_levels[current_idx + 1]
return self.current_quality
def _upgrade(self, throughput: float) -> str:
# Choose highest quality that fits throughput
for quality in self.quality_levels:
if self._required_throughput(quality) < throughput * 0.8:
return quality
return self.quality_levels[-1]
QUIC and HTTP/3 Deep Dive
HTTP/3 runs over QUIC, but that does not mean every streaming client or delivery path uses it. For this exercise, treat HTTP/3 as an option when both client and endpoint support it; retain a TCP-based HTTP fallback where UDP connectivity or deployment support is unavailable. The HTTP/3 specification defines the protocol behavior.
Compare protocols per delivery path
QUIC provides independent streams and connection migration features, but those properties do not make it a universal replacement for TCP. Measure handshake time, loss recovery, fallback behavior, and playback outcomes on the clients and networks the service supports.
graph TB
subgraph "TCP Limitations"
A[TCP Handshake] --> B[TLS Handshake]
B --> C[3-RTT Total]
C --> D[Head-of-line blocking]
D --> E[Connection migration impossible]
end
subgraph "QUIC Advantages"
F[QUIC Handshake] --> G[Combined crypto]
G --> H[1-RTT or 0-RTT]
H --> I[Stream multiplexing]
I --> J[Connection migration works]
end
Key QUIC benefits for streaming:
| Feature | TCP | QUIC |
|---|---|---|
| Connection establishment | 1-3 RTTs | 0-1 RTT |
| Head-of-line blocking | Yes | No (stream-level) |
| Connection migration | Breaks | Preserves |
| Packet loss impact | All streams | Single stream |
| TLS handshake | Separate | Combined |
Stream Multiplexing in QUIC
TCP’s head-of-line blocking problem means if packet N is lost, all HTTP/2 streams stall waiting for retransmission. QUIC fixes this at the transport layer:
class QUICStreamMultiplexing:
"""Streams are independent in QUIC"""
def __init__(self, connection: QUICConnection):
self.connection = connection
self.streams = {} # Stream ID -> Stream state
def send_on_stream(self, stream_id: int, data: bytes):
# Packet loss on stream 5 does NOT block stream 7
self.connection.send_stream_data(stream_id, data)
def handle_packet_loss(self, stream_id: int):
# Only this stream recovers, others continue
self.streams[stream_id].retransmit()
In a design using separate HTTP/3 streams, loss on one stream does not block delivery on another stream at the QUIC layer. Application behavior still depends on how the player requests and buffers media segments.
Connection Migration
Users switch between WiFi and cellular constantly. With TCP, this breaks connections and forces reconnection. QUIC’s connection migration preserves the logical session across network changes:
class ConnectionMigration:
"""QUIC connection survives network changes"""
def on_network_change(self, new_endpoint: tuple):
# Same connection ID, new network path
self.connection.migrate(new_endpoint)
# All stream state preserved
# Playback continues without rebuffering
assert self.streams_all_alive()
For a mobile client, connection migration may help preserve a QUIC connection when the network path changes. It depends on client, server, and network support; reconnect and resume behavior still needs a fallback.
0-RTT Resumption
QUIC’s 0-RTT mode allows clients to resume sessions and send data immediately without waiting for handshake completion. For streaming:
class ZeroRTTStreaming:
"""Send first video request immediately"""
async def start_playback(self, title_id: str):
# 0-RTT: send immediately, handshake in background
# First segments start downloading while TLS completes
self.transport.send_stream_data(
stream_id=1,
data=f"GET /video/{title_id}/segment1",
flush=True
)
This cuts startup latency significantly — the first video segments arrive while the secure connection is being established.
QUIC Loss Detection
QUIC implements its own loss detection optimized for streaming:
class QUICLossDetection:
def __init__(self):
self.packet_threshold = 3 # Pkt-based detection
self.time_threshold = 0.25 # 250ms time-based
def on_ack(self, ack_info: dict):
if self._detect_loss(ack_info):
# Fast retransmit for streaming
self._retransmit_lost_stream()
def _detect_loss(self, ack_info: dict) -> bool:
# QUIC uses both packet count AND time since last ack
elapsed = time.time() - ack_info['last_ack_time']
lost_packets = ack_info['total_packets'] - ack_info['acked_packets']
return (lost_packets >= self.packet_threshold or
elapsed >= self.time_threshold)
Microservices Architecture
For this exercise, assume services are split by operational ownership and can be deployed independently. A microservice count is not a design requirement.
Service Decomposition
graph TB
subgraph "Edge Layer"
GW[API Gateway]
GS[Gateway Service]
end
subgraph "Backend"
M[Metadata Service]
R[Recommendation Engine]
P[Playback Service]
S[Search Service]
A[Auth Service]
end
subgraph "Data"
EV[EVCache]
DB[(Cassandra)]
ES[Elasticsearch]
end
GW --> GS
GS --> M
GS --> R
GS --> P
GS --> S
GS --> A
M --> DB
M --> EV
R --> EV
S --> ES
Key Microservices
| Service | Responsibility | Data Store |
|---|---|---|
| API Gateway | Request routing, aggregation | None |
| Metadata | Titles, episodes, images | Cassandra |
| Playback | Streaming session management | EVCache |
| Recommendations | Personalized suggestions | Elasticsearch |
| Search | Full-text search | Elasticsearch |
| User Profile | Account, profiles, settings | Cassandra |
| Billing | Subscriptions, payments | PostgreSQL |
API Gateway
public class ApiGatewayApplication {
public static void main(String[] args) {
// Zuul routes configuration
addRequestThreadFilters();
addResponseFilters();
// Route definitions
configureRoutes(new ZuulRouteBuilder()
.route("/api/v1/metadata/**", "metadata-service")
.route("/api/v1/playback/**", "playback-service")
.route("/api/v1/recommendations/**", "recommendation-service")
.route("/api/v1/search/**", "search-service")
);
}
}
API Design
Streaming Endpoints
| Endpoint | Description |
|---|---|
| GET /api/v1/browse | Get personalized rows |
| GET /api/v1/titles/{id}/metadata | Get title details |
| GET /api/v1/titles/{id}/similars | Similar titles |
| GET /api/v1/playback/session | Initialize playback |
| POST /api/v1/playback/position | Update position |
| GET /api/v1/search?q={query} | Search titles |
Response Example
{
"data": {
"id": "81239481",
"title": "Stranger Things",
"type": "show",
"poster_url": "https://cdn.netflix.com/poster.jpg",
"backdrop_url": "https://cdn.netflix.com/backdrop.jpg",
"rating": "TV-14",
"year": 2024,
"duration": "4 seasons",
"synopsis": "When a young boy vanishes...",
"genres": ["Drama", "Horror", "Sci-Fi"],
"seasons": [
{
"season_num": 1,
"episodes": [
{
"num": 1,
"title": "The Vanishing",
"duration_secs": 3600,
"thumbnail": "https://cdn.netflix.com/s1e1.jpg"
}
]
}
]
},
"meta": {
"request_id": "abc123",
"version": "2.1"
}
}
Recommendation System
No viewing-share figure is assumed here. A streaming service may rank titles using viewing history, catalog metadata, and current context, but its ranking objective and success metric need to be defined and measured for the product.
Recommendation Pipeline
graph LR
A[User Events] --> B[Event Pipeline]
B --> C[Feature Store]
C --> D{Ranking Models}
D --> E[Personalized Ranking]
D --> F[Similar Titles]
D --> G[Top Picks]
E --> H[API Response]
F --> H
G --> H
Ranking Model Features
class RankingFeatures:
def __init__(self, user_id: int, title_id: int):
self.user_features = self._get_user_features(user_id)
self.title_features = self._get_title_features(title_id)
self.context_features = self._get_context_features()
def compute_features(self) -> Dict[str, float]:
return {
# User attributes
"user_age_days": self.user_features.age_days,
"user_avg_watch_time": self.user_features.avg_watch_time,
"user_rating_avg": self.user_features.avg_rating,
"user_genre_preferences": self.user_features.genre_scores,
# Title attributes
"title_popularity_score": self.title_features.popularity,
"title_recency": self.title_features.release_days_ago,
"title_rating": self.title_features.avg_rating,
"title_match_score": self._genre_match(),
# Context
"time_of_day": self.context_features.hour,
"day_of_week": self.context_features.day,
"device_type": self.context_features.device
}
Ranking Service
class RecommendationService:
def __init__(self, model: RankingModel, cache: RedisCache):
self.model = model
self.cache = cache
async def get_ranked_list(
self,
user_id: int,
row_count: int = 20,
evidence_count: int = 5
) -> List[RankedTitle]:
# Check cache
cache_key = f"recs:{user_id}:{row_count}"
cached = await self.cache.get(cache_key)
if cached:
return self._deserialize(cached)
# Get candidate titles
candidates = await self._get_candidates(user_id, 500)
# Compute features for each
ranked = []
for title in candidates:
features = self._compute_features(user_id, title)
score = await self.model.predict(features)
ranked.append((score, title))
# Sort and return top N
ranked.sort(key=lambda x: x[0], reverse=True)
results = [title for _, title in ranked[:row_count]]
# Cache for 5 minutes
await self.cache.setex(cache_key, 300, self._serialize(results))
return results
Capacity Planning Deep Dive
For the hypothetical recommendation service, estimate request volume from observed product traffic rather than an assumed release-day multiplier. Let H be peak homepage requests per second, q the fraction that require online ranking, t the measured CPU time per ranking request, and u the target CPU utilization. A first-pass worker estimate is ceil(H × q × t / u), with t in CPU-seconds. Validate it under a representative request mix, then separately size caches and event-driven refresh work.
The design separates forecast work, pre-provisioning, and load shedding. Those are options for this exercise, not a description of a Netflix framework:
| Layer | What it does | When it runs |
|---|---|---|
| Traffic Modeling | Forecasts demand from viewing history, marketing signals, regional demographics | Days to weeks ahead |
| Provisioning | Pre-scales infrastructure, pre-encodes content, pre-positions CDN files | Hours to days ahead |
| Load Shedding | Graceful degradation when actual demand exceeds even best forecasts | Real-time |
The first two layers are predictive – they try to get ahead of demand before it arrives. The third layer is reactive – it is the safety net that prevents cascading failures when predictions fall short. Each layer addresses a different failure mode: bad forecasts, slow provisioning, and unforeseeable demand spikes respectively. The subsections that follow drill into each layer’s mechanisms and the trade-offs involved.
Traffic Modeling
An example forecast model could use historical traffic, release timing, and regional demand. The inputs and model would need to be validated for the service:
class TrafficModel:
def predict_demand(self, title_id: str, release_datetime: datetime) -> DemandForecast:
# Base demand from similar title releases
base_demand = self._get_baseline_demand(title_id)
# Marketing multiplier
marketing_score = self._get_marketing_score(title_id)
# Time-of-day adjustment
hour_factor = self._get_hour_distribution(release_datetime)
# Geographic distribution
regional_demand = self._get_regional_forecast(title_id)
return DemandForecast(
peak_concurrent_streams=base_demand * marketing_score * hour_factor,
total_viewers=sum(regional_demand.values()),
bandwidth_tbps=self._estimate_bandwidth(regional_demand)
)
Provisioning for Major Releases
For a release with a known launch time, this hypothetical service might pre-position content and reserve capacity based on the forecast:
class ReleaseProvisioning:
def provision_for_release(self, title_id: str, release_date: datetime):
forecast = self.traffic_model.predict_demand(title_id, release_date)
# Pre-encode at all quality levels
self.encoding_queue.prioritize(title_id, priority="critical")
# Pre-position to CDN edges
for region, expected_streams in forecast.regional_demand.items():
self.cdn.pre_position(
title_id=title_id,
region=region,
expected_streams=expected_streams
)
# Scale recommendation service
self.recommendation_service.scale(
min_instances=forecast.peak_concurrent_streams / 1000
)
# License server capacity
self.license_service.scale(
target_capacity=forecast.peak_concurrent_streams * 1.5
)
Load Shedding Strategy
If demand exceeds capacity, the example service can shed optional work or reject requests according to an explicit product policy. Do not silently prioritize users by paid tier unless that behavior is an approved requirement:
class LoadShedding:
PRIORITY_LEVELS = {
"playback_start": 1,
"recommendation_refresh": 2,
"background_analytics": 3
}
def should_accept_request(self, request: Request, current_load: float) -> bool:
if current_load < self.capacity_threshold:
return True
# Defer optional work before rejecting playback requests
request_priority = self.PRIORITY_LEVELS[request.subscription_tier]
threshold_priority = self._load_to_priority_threshold(current_load)
return request_priority < threshold_priority
def _load_to_priority_threshold(self, load: float) -> int:
# As load increases, only accept higher-priority requests
if load > 0.95:
return 1 # Only premium
elif load > 0.85:
return 2 # Standard+
elif load > 0.70:
return 3 # Basic+
return 4 # Accept all
Data Storage
For this exercise, choose storage from access patterns and consistency needs. The examples below compare possible stores; they are not claims that Netflix currently stores these records in particular systems.
Cassandra for Metadata
CREATE TABLE titles (
title_id UUID PRIMARY KEY,
title_type TEXT, -- 'movie' or 'show'
title_name TEXT,
synopsis TEXT,
release_year INT,
duration_secs INT,
rating TEXT,
genres LIST<TEXT>,
-- Denormalized for query performance
genres_sorted SET<TEXT>,
created_at TIMESTAMP,
updated_at TIMESTAMP
);
CREATE TABLE episodes (
show_id UUID,
season_num INT,
episode_num INT,
episode_id UUID,
title_name TEXT,
duration_secs INT,
synopsis TEXT,
PRIMARY KEY ((show_id), season_num, episode_num)
);
CREATE TABLE title_by_genre (
genre TEXT,
release_year INT,
popularity_score DOUBLE,
title_id UUID,
PRIMARY KEY ((genre), popularity_score, release_year)
);
EVCache for Playback State
# Playback state cached in EVCache
PLAYBACK_STATE_TTL = 7200 # 2 hours
async def get_playback_state(user_id: int, title_id: int) -> PlaybackState:
key = f"playback:{user_id}:{title_id}"
cached = await evcache.get(key)
if cached:
return PlaybackState(**json.loads(cached))
# Fetch from database
state = await db.fetch_playback_state(user_id, title_id)
if state:
await evcache.setex(key, PLAYBACK_STATE_TTL, json.dumps(state))
return state
async def save_playback_position(user_id: int, title_id: int, position: int):
# Write to EVCache immediately
key = f"playback:{user_id}:{title_id}"
state = PlaybackState(user_id=user_id, title_id=title_id, position=position)
await evcache.setex(key, PLAYBACK_STATE_TTL, json.dumps(state))
# Persist to Cassandra async
asyncio.create_task(
db.save_playback_state(user_id, title_id, position)
)
Global Architecture
Multi-Region Setup
graph TB
subgraph "US-East (Primary)"
ZU[Zuul Gateway]
SVCS_E[Services]
DB_E[(Cassandra)]
end
subgraph "EU-West (Replica)"
ZU2[Zuul Gateway]
SVCS_W[Services]
DB_W[(Cassandra)]
end
subgraph "Asia-Pacific"
ZU3[Zuul Gateway]
SVCS_A[Services]
DB_A[(Cassandra)]
end
SVCS_E <--> DB_E
SVCS_W <--> DB_W
SVCS_A <--> DB_A
ZU --> SVCS_E
ZU2 --> SVCS_W
ZU3 --> SVCS_A
Traffic Routing
One option for the hypothetical service is to route clients to a healthy nearby region, subject to content availability and failover policy:
class LatencyRouter:
def route_request(self, user_id: int, service: str) -> str:
# Get user's last known region
user_region = self._get_user_region(user_id)
# Check if region is healthy
if self._is_region_healthy(user_region):
return f"{service}.{user_region}.netflix.com"
# Fallback to lowest latency
latencies = self._measure_all_regions(service)
return min(latencies, key=latencies.get)
def _measure_all_regions(self, service: str) -> Dict[str, float]:
return {
"us-east-1": self._ping(f"{service}.us-east-1.netflix.com"),
"eu-west-1": self._ping(f"{service}.eu-west-1.netflix.com"),
"ap-northeast-1": self._ping(f"{service}.ap-northeast-1.netflix.com")
}
DRM and Entitlement Systems
This exercise assumes the service must support the DRM systems required by its licensed content and devices. Verify platform compatibility with the relevant DRM provider documentation before deployment.
DRM Architecture
graph TB
D[Device] -->|1. Initialize| L[License Server]
L -->|2. Device ID + Content Key Request| E[Entitlement Service]
E -->|3. Check subscription| DB[(User DB)]
DB -->|4. Entitlement OK| E
E -->|5. Grant license| L
L -->|6. Encrypted License| D
D -->|7. Decrypt with device key| K[Content Key]
K -->|8. Play| V[Video Decrypt]
Multi-DRM Support
class DRMManager:
"""Handle multiple DRM schemes per platform"""
DRM_SCHEMES = {
"widevine": "com.widevine.alpha", # Android, Chrome, many devices
"playready": "com.microsoft.playready", # Windows, Xbox
"fairplay": "com.apple.fairplay", # iOS, Safari
"clearkey": "org.w3.clearkey" # Web fallback
}
def get_supported_drm(self, device_type: str) -> List[str]:
"""Return DRM schemes supported by device"""
capabilities = {
"android": ["widevine"],
"ios": ["fairplay"],
"web_safari": ["fairplay", "clearkey"],
"web_chrome": ["widevine", "clearkey"],
"windows": ["playready", "widevine", "clearkey"],
"smarttv": ["widevine", "playready"]
}
return capabilities.get(device_type, ["widevine"])
Entitlement Checking
class EntitlementService:
"""Verify user can access specific content"""
async def check_entitlement(
self,
user_id: int,
title_id: str,
device_type: str
) -> EntitlementResult:
# Get user's subscription tier
subscription = await self.user_service.get_subscription(user_id)
# Get title's required tier
title = await self.metadata_service.get_title(title_id)
if subscription.tier < title.required_tier:
return EntitlementResult(
allowed=False,
reason="subscription_tier_too_low",
upgrade_to=title.required_tier
)
# Check concurrent stream limit
active_streams = await self.playback_service.count_active_streams(user_id)
if active_streams >= subscription.max_streams:
return EntitlementResult(
allowed=False,
reason="max_streams_exceeded",
active_streams=active_streams
)
return EntitlementResult(allowed=True)
Resilience Patterns
Circuit Breaker
class CircuitBreaker:
def __init__(self, failure_threshold: int = 5, timeout: int = 60):
self.failure_threshold = failure_threshold
self.timeout = timeout
self.failure_count = 0
self.last_failure_time = None
self.state = "closed"
async def call(self, func: Callable, *args, **kwargs):
if self.state == "open":
if time.time() - self.last_failure_time > self.timeout:
self.state = "half-open"
else:
raise CircuitOpenException()
try:
result = await func(*args, **kwargs)
self._on_success()
return result
except Exception as e:
self._on_failure()
raise e
def _on_success(self):
self.failure_count = 0
self.state = "closed"
def _on_failure(self):
self.failure_count += 1
self.last_failure_time = time.time()
if self.failure_count >= self.failure_threshold:
self.state = "open"
Bulkheads
Isolate service dependencies to prevent cascading failures:
class BulkheadExecutor:
def __init__(self, max_concurrent: int = 100):
self.semaphore = asyncio.Semaphore(max_concurrent)
async def execute(self, func: Callable, *args, **kwargs):
async with self.semaphore:
return await func(*args, **kwargs)
# Different bulkheads for different service calls
metadata_bulkhead = BulkheadExecutor(max_concurrent=50)
recommendation_bulkhead = BulkheadExecutor(max_concurrent=20)
playback_bulkhead = BulkheadExecutor(max_concurrent=30)
Adaptive Bitrate Streaming Deep Dive
ABR Algorithm Details
class AdaptiveBitrateController:
"""Illustrative adaptive bitrate selection for the exercise."""
def __init__(self):
# Quality levels (lowest to highest)
self.levels = [
{"name": "auto", "min_bandwidth": 0},
{"name": "360p", "min_bandwidth": 0.7, "max_bandwidth": 1.5},
{"name": "480p", "min_bandwidth": 1.5, "max_bandwidth": 3},
{"name": "720p", "min_bandwidth": 3, "max_bandwidth": 5},
{"name": "1080p", "min_bandwidth": 5, "max_bandwidth": 10},
{"name": "4K", "min_bandwidth": 10, "max_bandwidth": float('inf')}
]
# State
self.current_level = 0
self.buffer_levels = [] # Ring buffer of recent buffer levels
self.throughput_samples = [] # Ring buffer of recent throughput
def calculate_throughput(self, segments: List[Segment]) -> float:
"""Calculate effective throughput from recent segments"""
if not segments:
return 0
# Weight recent samples higher
weights = [0.1, 0.15, 0.25, 0.5] # Oldest to newest
weighted_sum = sum(
s.download_time / s.size_mb * w
for s, w in zip(segments[-4:], weights)
)
return weighted_sum
def select_quality(self, throughput: float, buffer_level: float) -> str:
"""Select optimal quality based on conditions"""
# Determine if we're in startup, steady, or buffer-depleted state
state = self._classify_state(buffer_level)
if state == "startup":
# During startup, download multiple qualities in parallel
return self.levels[0]["name"] # "auto"
elif state == "buffer_depleted":
# Buffer running low - switch to lower quality
return self._select_lower_quality(throughput)
elif state == "steady":
# Try to improve quality if buffer is healthy
return self._select_quality_for_throughput(throughput)
return self.current_level
def _classify_state(self, buffer_level: float) -> str:
if buffer_level < 10:
return "buffer_depleted"
elif buffer_level < 60:
return "steady"
else:
return "startup" # Large buffer, can experiment
CDN Cache Invalidation
graph TB
A[Content Update] --> B{New encode or metadata change?}
B -->|Metadata| C[Update metadata service]
B -->|New encode| D[Push to origin]
D --> E[Invalidate edge caches]
E --> F[CDN propagates in < 30s]
subgraph "Cache Invalidation Strategy"
C
E
end
class CDNInvalidationService:
"""Handle content cache invalidation across CDN"""
async def invalidate_title(self, title_id: str, reason: str):
"""Invalidate all cached data for a title"""
# Invalidate manifest files
await self.cdn.invalidate(f"/title/{title_id}/*.m3u8")
# Invalidate metadata
await self.cdn.invalidate(f"/api/metadata/{title_id}")
# Invalidate thumbnails
await self.cdn.invalidate(f"/images/{title_id}/*")
# Log invalidation for audit
await self.audit_log.record({
"event": "cache_invalidation",
"title_id": title_id,
"reason": reason,
"timestamp": datetime.utcnow()
})
Multi-Device Session Management
In this exercise, playback state syncs across a user’s devices and any concurrent-play limit follows the product’s entitlement rules.
Session State
class PlaybackSession:
"""Represent an active playback session"""
def __init__(
self,
session_id: str,
user_id: int,
title_id: str,
device_type: str,
position_seconds: int,
quality: str
):
self.session_id = session_id
self.user_id = user_id
self.title_id = title_id
self.device_type = device_type
self.position_seconds = position_seconds
self.quality = quality
self.started_at = datetime.utcnow()
self.last_heartbeat = datetime.utcnow()
async def update_position(self, position_seconds: int):
"""Update playback position"""
self.position_seconds = position_seconds
self.last_heartbeat = datetime.utcnow()
# Persist to storage
await self.playback_store.save_position(
self.session_id,
position_seconds
)
# Invalidate device position cache
await self.cache.delete(f"position:{self.user_id}:{self.title_id}")
Continue Watching Sync
class ContinueWatchingService:
"""Sync playback position across devices"""
async def get_resume_position(
self,
user_id: int,
title_id: str,
requesting_device: str
) -> ResumePosition:
# Check if another device has more recent position
active_sessions = await self.session_manager.get_active_sessions(
user_id,
exclude_device=requesting_device
)
# Find session with this title
for session in active_sessions:
if session.title_id == title_id:
return ResumePosition(
position_seconds=session.position_seconds,
device=session.device_type,
updated_at=session.last_heartbeat
)
# Fallback to database
return await self.playback_store.get_position(user_id, title_id)
async def handle_playback_start(
self,
user_id: int,
title_id: str,
device_type: str
) -> Session:
# Create new session
session = PlaybackSession(
session_id=uuid4(),
user_id=user_id,
title_id=title_id,
device_type=device_type,
position_seconds=0,
quality="auto"
)
# Register session
await self.session_manager.register(session)
# Enforce concurrent stream limit
await self._enforce_stream_limit(user_id)
return session
async def _enforce_stream_limit(self, user_id: int):
"""Ensure user hasn't exceeded stream limit"""
subscription = await self.user_service.get_subscription(user_id)
active = await self.session_manager.count_active(user_id)
if active > subscription.max_streams:
# Force oldest session to stop
oldest = await self.session_manager.get_oldest_session(user_id)
await self.session_manager.terminate(oldest.session_id)
Trade-off Analysis
| Factor | Custom CDN (Open Connect) | Third-Party CDN | Hybrid Approach |
|---|---|---|---|
| Cost at scale | Lower (owned hardware) | Higher (per TB) | Medium |
| Control | Full | Limited | Partial |
| Time to deploy | Long (build your own) | Fast (existing) | Medium |
| Optimization | Streaming-specific | General purpose | Mixed |
| Operational burden | High (you manage) | Low (managed) | Medium |
Production Failure Scenarios
| Failure Scenario | Impact | Mitigation |
|---|---|---|
| CDN origin failure | Video segments unavailable | Multi-CDN; fallback to direct streaming |
| License server down | No new streams can start | Cache licenses; graceful degradation |
| Recommendation service slow | Homepage takes longer to load | Cache recommendations; show stale content |
| Encoding pipeline backlog | New content delayed | Priority encoding; capacity headroom |
| Device too many streams | New streams rejected | Clear error message; upgrade prompt |
Scenario Drills
Scenario 1: CDN Origin Server Failure
Situation: The CDN origin serving video segments goes down during peak viewing hours.
Analysis:
- Devices requesting segments get errors
- Playback stalls, rebuffering begins
- Millions of concurrent streams affected
Solution: Multi-CDN deployment with automatic failover. If one CDN has issues, traffic routes to another. Open Connect has multiple origin clusters geographically distributed. Devices can switch CDN transparently if segment requests fail.
Scenario 2: New Show Releases Simultaneously Worldwide
Situation: A highly anticipated show releases globally at midnight UTC. 10 million users try to start playback simultaneously.
Analysis:
- Encoding pipeline must complete all quality levels before release
- CDN edge caches start cold for a new title
- License servers receive burst of requests
Solution: Pre-encode content days before release. Pre-position popular titles at ISP locations. License server scales horizontally; licenses are cached for their validity period to reduce server load.
Scenario 3: ABR Algorithm Causes Quality Flutter
Situation: Users report constantly changing video quality, creating a jarring viewing experience.
Analysis:
- ABR switches quality too frequently
- Bandwidth measurements fluctuate (wireless networks)
- Buffer thresholds trigger rapid up/down switching
Solution: Test a quality-switch dwell rule and a throughput margin against playback traces. Select values that meet the service’s startup and rebuffering goals instead of treating one interval or percentage as universal.
Failure Flow Diagrams
Stream Playback Initialization
flowchart TD
A[User Clicks Play] --> B[Get Manifest from CDN]
B --> C[Parse Quality Levels]
C --> D[Select Initial Quality]
D --> E[Request Video Segment]
E --> F{Segment Available?}
F -->|No| G[Try Alternative CDN]
G --> E2[Request Video Segment]
E2 --> F2{Segment Available?}
F2 -->|Yes| H[Download Segment]
F2 -->|No| G
F -->|Yes| H
H --> I[Request DRM License]
I --> J[License Server]
J --> K{Check Entitlement?}
K -->|No| L[Return Error]
K -->|Yes| M[Return License Key]
M --> N[Decrypt Segment]
N --> O[Decode and Display]
O --> P[Buffer Next Segment]
P --> E
ABR Quality Selection
flowchart TD
A[Monitor Buffer Level] --> B{Buffer < 10s?}
B -->|Yes| C[Select Lower Quality]
B -->|No| D{Buffer > 60s?}
D -->|Yes| E[Select Higher Quality]
D -->|No| F[Maintain Current Quality]
C --> G[Download at New Quality]
E --> H[Download at New Quality]
F --> I[Continue Current Quality]
G --> J[Deliver to Player]
H --> J
I --> J
J --> A
Multi-CDN Failover
flowchart TD
A[Request Segment] --> B[Primary CDN]
B --> C{Response OK?}
C -->|Yes| D[Deliver to Device]
C -->|No| E[Try Secondary CDN]
E --> F{Response OK?}
F -->|Yes| G[Deliver to Device]
F -->|No| H[Fallback to Origin Direct]
H --> I{Origin Available?}
I -->|Yes| J[Deliver to Device]
I -->|No| K[Show Error]
Common Pitfalls / Anti-Patterns
Pitfall 1: Aggressive Quality Switching
Problem: Switching quality too frequently creates a “flutter” effect that’s visually jarring.
Solution: Compare stability-window values on representative traces and check both rebuffering and unnecessary quality reductions.
Quality flutter is one of the most common ABR complaints in production. The underlying issue is that naive throughput-based algorithms respond to every measurement fluctuation. A temporary network hiccup causes an immediate step down in quality; a brief burst of good throughput triggers a step back up. The result is a quality level that keeps oscillating, which users describe as “the video keeps changing.”
One possible control is a minimum dwell time between quality switches. Choose it from playback experiments and keep measuring throughput and buffer state during the interval; there is no universal duration that fits every player or network.
Weighted throughput averaging helps just as much. Rather than reacting to the last measurement, ABR algorithms weight recent samples more heavily while still smoothing out single-packet anomalies. A typical scheme might weight the last four samples as [0.1, 0.15, 0.25, 0.5], where the most recent sample dominates. One bad reading will not cause an unnecessary downgrade this way.
The selected bitrate needs headroom below measured throughput, but the margin should come from the player’s network traces and rebuffering target. Avoid using one fixed percentage as a rule for every network.
Pitfall 2: Ignoring Network Variability
Problem: Using average throughput misses spikes and drops.
Solution: Smooth recent throughput samples and choose a bitrate with a margin calibrated on representative traces. Check that the margin does not cause unnecessary quality reductions on stable links.
Wireless networks exhibit high variability that simple averaging fails to capture. A user on a WiFi network sharing bandwidth with other household devices, or a mobile user transitioning between cell towers, experiences conditions that change dramatically over seconds. A naive average over the last N samples treats a spike and a drop with equal weight, producing quality decisions that are either too aggressive or too conservative.
An ABR implementation can estimate throughput with an exponentially weighted moving average. A higher smoothing factor reacts more to recent samples; a lower factor dampens short-term variation. Tune the factor with playback traces from the supported network mix rather than assuming one value for mobile or Wi-Fi.
Variance itself is a useful signal. If the standard deviation of your throughput measurements is high relative to the mean, the network is unstable and you should be more conservative with quality selection. Some production systems track a separate confidence score combining both average and variance to make more informed quality decisions.
Packet loss rate is another signal that often gets ignored. TCP retransmissions caused by packet loss artificially inflate measured throughput because the protocol resends lost packets without the receiver acknowledging them. An ABR algorithm that only looks at bytes-per-second without accounting for retransmissions will overestimate available bandwidth following packet loss, leading to quality selections the network cannot sustain.
Pitfall 3: Not Testing on Real Networks
Problem: Lab testing does not capture real-world variability (WiFi interference, cellular handoffs).
Solution: Test ABR algorithms with controlled network traces, then use an approved gradual rollout or experiment. Monitor quality distribution, startup time, and rebuffer ratio with pre-set guardrails.
Lab testing with controlled network links captures some variability through configurable jitter and packet loss profiles, but cannot replicate the full range of conditions real users experience. The gap is real: a residential WiFi network dealing with a neighbor’s streaming load, a crowded conference WiFi with hundreds of devices competing for bandwidth, or a mobile user on a train passing through dead zones all behave in ways that lab equipment rarely simulates without deliberate effort.
For this exercise, compare an ABR change with a controlled rollout or experiment. Define guardrails such as startup time, rebuffer ratio, and quality distribution before exposing more traffic; traffic allocation and minimum sample size depend on the experiment design.
Segment-level instrumentation makes this possible. Every segment download records the requested quality, actual throughput achieved, buffer level before and after the segment, and whether rebuffering occurred during playback. This data feeds into experiment evaluation. Without this granularity, you cannot meaningfully compare algorithm variants.
Real-world testing also surfaces edge cases that simulation misses. Users who pause playback and resume hours later with a cold buffer behave differently from continuous viewers. VPN users routing traffic through distant exit points experience latency spikes that would never appear in a lab. Enterprise network users face rate limiting and traffic shaping that artificially constrains throughput. Each of these scenarios requires specific handling in the ABR logic.
Hypothetical failure exercises
These scenarios are invented test cases for the proposed service; they are not reports of Netflix incidents.
Edge cache unavailable in one region
Drain a cache cluster during a load test. Measure how origin traffic and playback startup change, and confirm that a regional circuit breaker or alternate route prevents an origin overload. Check that cache recovery does not trigger an uncontrolled refill burst.
Playback-state store slows down
Inject latency into the playback-state dependency. Verify that playback can continue if the feature permits stale resume position, that retries have a deadline and backoff, and that optional homepage work does not consume the pool needed for playback.
Wrong account returned by a routing change
Run a tenant-isolation test with multiple accounts while changing a route or cache key. The release must fail if one account can read another account’s playback state, and the rollback path must restore the previous routing configuration.
Quick Recap
- Netflix publicly describes Open Connect as an ISP partnership and content-delivery program; the rest of this article is a hypothetical architecture.
- Adaptive bitrate streaming selects quality based on bandwidth and buffer health.
- DRM (Widevine, PlayReady, FairPlay) protects content on each platform.
- Entitlement service enforces subscription tier and concurrent stream limits.
- Session sync allows “continue watching” across devices.
Copy/Paste Checklist
- [ ] Implement ABR with buffer-aware quality selection
- [ ] Use multi-CDN with failover
- [ ] Cache CDN responses aggressively
- [ ] Enforce concurrent stream limits per subscription
- [ ] Implement session sync for continue watching
- [ ] Monitor stream startup time and rebuffer ratio
- [ ] Test ABR on real networks, not just labs
Observability Checklist
Metrics to Capture
stream_startup_time_seconds(histogram) - Time to first framebitrate_selected(histogram) - Quality distributionrebuffer_ratio(gauge) - Time spent rebuffering vs playingcdn_cache_hit_ratio(gauge) - Cache efficiencylicense_request_latency_ms(histogram) - DRM overheadconcurrent_streams(gauge) - Active stream count
Alerts to Configure
| Alert | Threshold | Severity |
|---|---|---|
| Startup time P99 > 3s | 3000ms | Warning |
| Rebuffer ratio > 5% | 5% | Warning |
| CDN cache hit < 90% | 90% | Warning |
| License latency P99 > 200ms | 200ms | Critical |
| Active streams < expected | < 50% baseline | Warning |
Security Checklist
- DRM encryption for all premium content
- Device attestation before issuing licenses
- HDCP enforcement for high-definition outputs
- Screen capture detection and blocking
- Concurrent stream enforcement
- Geographic restrictions per title
- Secure token exchange for session management
- Content signing to prevent tampering
Interview Questions
Netflix describes Open Connect as its content delivery network and says it works with ISPs to localize content delivery. The public overview explains the program and ISP participation; it does not establish a complete current topology or a cost comparison with third-party CDNs. See the Open Connect overview.
In this design exercise, the service prepares a set of renditions and exposes them through a manifest. The player estimates throughput and buffer state, then chooses a rendition. The ladder and switching policy depend on device support and playback measurements.
Define the limit in the product's entitlement rules, then reserve a session atomically when playback starts. If the limit is reached, return a clear conflict response or follow an approved replacement policy. Do not silently terminate an older session unless that behavior is part of the product contract.
Widevine, PlayReady, and FairPlay are platform DRM systems. Device and browser support differs, so a service must check the current provider and platform documentation, select a supported license path, and avoid assuming one encrypted package or license format works everywhere.
You're watching a show on your laptop, switch to your phone, and it resumes from roughly where you left off. This seems simple but requires coordination.
Store position updates with an account, title, device, and server-assigned update version. When a second device opens the title, choose a conflict rule such as the latest accepted update, and tell the user when another device has advanced. A cache can serve recent state, but define its source of truth and recovery behavior first.
A cache can reduce reads for hot playback state, but it is not automatically the source of truth. Decide whether writes go through to durable storage, how stale a position may be, how cache misses recover, and how invalidation works. Measure latency and storage load on the actual access pattern before choosing a cache.
For this exercise, encode each title into renditions supported by the target devices and bandwidth range, then validate playback and quality before publication. Prioritize jobs using an explicit release deadline and content policy. Pre-positioning is useful only where the delivery network supports it and the cache policy is understood.
A private or partner-operated CDN can give an organization more control over placement and traffic engineering, but it requires hardware, ISP relationships, operations, and long-term capacity planning. A third-party CDN reduces that operating burden and usually makes sense until measured traffic or product requirements justify a different model. Compare actual contracts, egress patterns, cacheability, and staff cost; there is no universal break-even point.
A service can begin with catalog metadata, explicit onboarding preferences, or editorial and popularity rankings, then personalize as the user supplies signals. Choose signals the product is allowed to use, disclose their use where required, and evaluate recommendations against a defined user outcome. The fallback and ramp-up are product decisions, not assumptions about Netflix.
Start from the catalog queries, update rate, consistency needs, and operational skills. A relational database can fit normalized catalog relationships and transactions; a distributed store can fit known partitioned access patterns at higher scale. Write down the required queries and consistency behavior, then benchmark representative data before choosing. No query-rate threshold makes one database universally better.
Quality changes can become distracting if the player reacts to noisy measurements. For the hypothetical player, candidate controls include:
- Stability windows: Test a dwell-time rule against measured playback traces; do not assume a fixed interval fits every network.
- Weighted throughput averaging: Recent samples are weighted higher than older ones to respond quickly to actual changes while avoiding noise from temporary fluctuations.
- Safety margins: Choose headroom from the supported network traces and rebuffering target.
- State-based decisions: Different logic for startup vs. steady-state vs. buffer-depleted scenarios.
Key components for multi-CDN failover:
- Health monitoring: Each CDN reports latency, error rates, and throughput continuously.
- Failover triggers: Automatic switch when primary CDN returns errors, latency exceeds threshold, or success rate drops below SLA.
- Client-side logic: Devices retry with exponential backoff, then switch to next CDN in priority order.
- Consistent hashing: Ensure segments are requested from the same CDN to avoid requesting duplicate data from multiple sources.
- Origin fallback: Last resort is direct origin streaming if all CDNs fail.
Preparation starts days before release:
- Priority encoding queue: Predict popularity based on marketing signals, pre-encode high-priority titles first.
- All quality levels up front: Encode 4K, 1080p, 720p, 480p, etc., with both H.264 and H.265 codecs before release.
- CDN pre-positioning: Push encoded content to ISP-level Open Connect appliances before midnight UTC.
- Capacity headroom: Encoding farms scale horizontally, allocate extra capacity for expected burst.
- License server scaling: Size from expected peak license requests and measured service capacity.
For the exercise, model regional rights in the catalog and verify them at playback authorization. Route to a healthy region without bypassing the rights check:
- Entitlement service: Before issuing a DRM license, checks if the user's account has rights for the requested geographic region.
- Content metadata: Each title has geographic availability windows tied to licensing agreements.
- Device IP routing: Latency-based routing considers region; requests for restricted content return error before segment delivery.
- CDN-level blocking: Some CDNs can enforce geographic restrictions at edge nodes before requests hit origin.
A recommendation system can compare candidates with offline evaluation or a controlled experiment. Bandit methods are one option, but the method and guardrails depend on the product objective:
- Exploitation: Show titles similar to what you've watched (high confidence predictions).
- Exploration: Occasionally show new or unpredictable titles to gather data on user preferences.
- Epsilon-greedy: Most of the time use best predictions, but occasionally random selection.
- Thompson sampling: Bayesian approach that balances exploration more intelligently.
- Contextual bandits: Consider time of day, device type, and other context when deciding what to explore.
The session sync system requires:
- Active session tracking: When playback starts, store device ID, timestamp, and position in a durable or recoverable state store.
- Cross-device position queries: When opening the app, query all active sessions for this user, find most recent position across any device.
- Durability: Define how position updates reach durable storage and what loss window is acceptable.
- Conflict resolution: Use a server-assigned version or explicit device precedence; client timestamps can be skewed.
- Session expiration: Sessions expire after heartbeat timeout (e.g., 30 minutes of no activity).
The enforcement process:
- Stream counting: Before starting a new session, count active sessions for this user.
- Limit checking: Compare active reservations with the configured entitlement for that account.
- Conflict policy: Reject a new session or replace an existing one only if product rules define that behavior.
- Graceful notification: Tell affected devices what happened and how to recover.
- State cleanup: Expire reservations safely and retain an audit event for support.
Key streaming health metrics:
- Stream startup time: Time from click to first frame. Target P99 < 3 seconds.
- Rebuffer ratio: Time spent waiting vs. time playing. Target < 5%.
- Bitrate distribution: Histogram of quality levels selected. Higher is better but must not cause rebuffering.
- CDN cache hit ratio: Target > 90% at edge caches.
- License request latency: DRM overhead. Target P99 < 200ms.
- Error rates: By error type (network, DRM, device).
- Concurrent streams gauge: Actual vs. expected for capacity planning.
Detection mechanisms:
- Location tracking: If two sessions have IP geolocations that are physically impossible to reach from one user (e.g., different continents within minutes), flag the account.
- Device fingerprinting: Track device characteristics to identify if multiple devices are being used by different households.
- Behavioral patterns: Different viewing patterns (different times of day, different genres) might indicate shared accounts.
- Explicit enforcement: When stream limit is hit, require email/SMS verification to confirm the primary user.
Netflix's Open Connect overview describes its CDN program and ISP partnerships. Public material describes appliances used to localize content delivery; it is not a full deployment specification:
- Program scope: Netflix describes working with ISPs to localize delivery.
- Placement: Public Open Connect material describes ISP-embedded deployments and interconnection locations.
- Limits of the source: It does not establish current fleet size, cost savings, routing policy, or the full origin and cache-fill design.
Further Reading
- CDN Deep Dive — Content delivery network design
- NoSQL Databases — Cassandra and distributed data stores
- Distributed Caching — EVCache patterns
- Microservices Architecture — Service decomposition patterns
- Circuit Breaker Pattern — Resilience patterns
For more on CDN design, see our CDN Deep Dive guide. For database strategies, see NoSQL Databases. For caching patterns, see Distributed Caching.
Conclusion
The public Open Connect material supports one concrete reference point: Netflix partners with ISPs to localize content delivery. The rest of the article is a design exercise. Replace its targets with measured product traffic, choose consistency and storage from the actual access patterns, and verify each delivery path on the clients and networks the service supports.
Category
Related Posts
System Design: Twitter Feed Architecture and Scalability
A Twitter/X-like feed design exercise covering fan-out, timeline consistency, and capacity estimates from explicit workload assumptions.
System Design: URL Shortener from Scratch
A URL shortener design exercise with collision-safe code allocation, redirect caching semantics, abuse controls, and an explicit capacity worksheet.
Amazon Architecture: History and Service Design
Separate documented Amazon and AWS milestones from popular retellings, then apply the lesson about service boundaries to a current request flow.