Real-Time and Streaming System Design Questions
Designing client-facing, always-on live delivery systems: real-time communication transports (WebSockets, server-sent events, long-polling, WebRTC, MQTT), connection lifecycle and scaling for millions of persistent connections, presence, pub/sub fan-out to online users, chat and notifications, live feeds and tickers, real-time collaboration (CRDT vs OT, offline sync and reconciliation), and live and on-demand video delivery (ingest, transcoding, adaptive bitrate, CDN delivery, low-latency protocols, playback entitlement and content protection). Covers latency budgets, per-client ordering, delivery guarantees across disconnect and reconnect, per-client backpressure, capacity estimation for connection fleets, authentication, authorization, and revocation for real-time channels and premium content, and operational readiness (SLOs and error budgets, observability and incident response, rate limiting, safe rollout, and load and chaos testing) for live-delivery platforms. Data-pipeline stream processing (Kafka or Flink jobs, windowed aggregation, exactly-once pipelines, real-time analytics ingestion) is out of scope.
Compare Kafka, Redis (Pub/Sub and Streams), and RabbitMQ as the messaging backbone for a real-time system across three use cases: fan-out notifications to many subscribers, ordered per-conversation chat, and ephemeral presence events. For each broker evaluate throughput, persistence and retention, delivery semantics, latency, consumer model, and operational complexity, and recommend a fit per use case, including for a notification service with a sub-100ms tail-latency requirement.
Sample Answer
Direct answer
These are three different tools, and the right answer uses more than one. Kafka (a distributed, durable message broker) is a durable, partitioned log (a topic is split into several ordered, append-only partitions; a message's key always hashes to the same partition, so same-key messages land together and keep their order): best when you need retention, replay and ordering by key, so it fits ordered per-conversation chat. Redis Pub/Sub is fire-and-forget broadcast with no storage: best for ephemeral presence events where a lost update is harmless. Redis Streams adds a stored log with acknowledgements to Redis, a lighter middle ground. RabbitMQ (a widely used open-source message broker) is a routing message broker with per-message acknowledgements and flexible exchanges (routing rules a publisher sends to, which decide which queues get a copy of each message), strongest for task-style delivery and moderate-scale fan-out. For a notification service with a sub-100 ms tail-latency requirement, I would deliver the live copy over Redis Pub/Sub for speed while writing the durable copy to Kafka (or a database inbox) so nothing is lost when a client is offline.
Terms: delivery semantics are the guarantee about duplicates and loss: at-most-once (may be lost, never duplicated), at-least-once (never lost once accepted, may be duplicated), exactly-once (processed as if it happened exactly one time: no loss and no duplicate effect, usually built by combining at-least-once delivery with deduplication or transactions). A consumer group is a set of consumers that share a topic's work, each message going to one member. Tail latency means the slow end of the latency distribution, usually p99 (the 99th percentile: 99% of messages are faster). An offset is a message's position number within its partition; because Kafka retains the log, a consumer can replay from any earlier offset.
Two Redis features that behave very differently
Redis Pub/Sub delivers a message only to subscribers connected at that instant; nothing is stored. Redis Streams appends entries to a stored log that consumer groups read and acknowledge. A runnable demonstration (Docker and Redis 7):
docker run -d --name redis-demo redis:7-alpine
sleep 2
docker exec redis-demo sh -c '
redis-cli PUBLISH scores "GOAL 1-0" # nobody subscribed yet
redis-cli XADD scores "*" event "GOAL 1-0" >/dev/null
redis-cli XADD scores "*" event "GOAL 2-0" >/dev/null
redis-cli XLEN scores
redis-cli XGROUP CREATE scores gw 0
redis-cli XREADGROUP GROUP gw gw-1 COUNT 10 STREAMS scores ">" | grep GOAL
redis-cli XPENDING scores gw | head -1'
docker rm -f redis-demo
Output (the image resolved to Redis 7.4.11):
0
2
OK
GOAL 1-0
GOAL 2-0
2
PUBLISH returned 0: zero subscribers received it, and the message is gone. The stream kept both entries, a consumer group that joined afterwards read them, and XPENDING shows 2 entries delivered but not yet acknowledged with XACK, which is what makes redelivery (at-least-once) possible. XGROUP CREATE scores gw 0 creates a consumer group named gw starting from offset 0 (the beginning of the stream), which is why this group can see entries written before it existed; creating it with $ instead would only show entries from that point on. In XREADGROUP, the > argument means give this consumer only entries no member of the group has been delivered yet, as opposed to passing a specific ID, which would replay that consumer's own still-pending entries.
Broker comparison
| Criterion | Kafka | Redis Pub/Sub | Redis Streams | RabbitMQ |
|---|---|---|---|---|
| Throughput | Very high; scales by adding partitions and brokers; batching amortises cost | High, bounded by one Redis node per channel (sharded pub/sub in Redis 7 spreads channels across a cluster) | High, bounded by memory of the node holding the stream | Good; per-queue throughput is limited by a single queue's process, scale by spreading queues |
| Persistence and retention | Disk log retained by time or size; replay from any offset | None | In memory, persisted via Redis snapshots or append-only file; trim with MAXLEN | Durable queues on disk; a message is removed once acknowledged (RabbitMQ Streams add log-style retention) |
| Delivery semantics | At-least-once by default; exactly-once processing within Kafka via idempotent producers and transactions | At-most-once | At-least-once via pending list and XACK | At-least-once with acknowledgements; at-most-once with auto-ack |
| Latency | Low milliseconds achievable, but producer batching and replicated writes trade latency for throughput; tail depends on tuning | Lowest: in-memory, no storage | Low: in-memory append | Low for lightly loaded queues; rises when queues back up |
| Consumer model | Pull; consumer groups, one consumer per partition within a group; order guaranteed per partition | Push to every connected subscriber | Pull by consumer group, or plain reads by offset | Push with a prefetch limit; exchanges (fanout, topic, direct) route to queues |
| Operational complexity | Highest: partitions, replication, rebalancing (managed services help) | Low | Low to moderate; memory planning for retention | Moderate: replication via quorum queues, memory and disk alarms |
Terms in the table: a prefetch limit caps how many unacknowledged messages RabbitMQ hands one consumer at once, so a single slow consumer cannot be buried in work no one else can pick up. Fanout exchanges copy a message to every bound queue, topic exchanges route by a wildcard pattern on a routing key, and direct exchanges route by an exact match. Quorum queues are RabbitMQ's replicated, crash-safe queue type. Auto-ack means the broker marks a message delivered the instant it sends it, before the consumer confirms it did anything with it, so a consumer that crashes mid-processing loses it silently. Memory and disk alarms are thresholds that make RabbitMQ block new publishes once a node is close to running out of RAM or disk, to protect it from falling over. A snapshot is a periodic full copy of Redis's in-memory data to disk; an append-only file (AOF) is a log of every write, replayed to rebuild memory on restart; MAXLEN caps a stream's length, discarding its oldest entries once it is exceeded. Idempotent producers and transactions are Kafka features that let a producer retry a send without creating a duplicate, and group several writes so they all become visible together or not at all, which is how Kafka reaches exactly-once for consumers that also use them.
Recommendation per use case
Fan-out notifications to many subscribers
Kafka as the durable entry point (the notification event is written once and can be replayed), consumed by a notification service that resolves recipients and hands each message to the gateway holding that user's connection. RabbitMQ with a fanout or topic exchange is a sound choice at moderate scale if the team already runs it; its weakness is that every subscriber needs its own queue, which grows costly with very many subscribers.
Ordered per-conversation chat
Kafka, keyed by conversation_id. Every message of one conversation hashes to the same partition, so they are stored and consumed in order, and the log supports replay when a client reconnects. You do not create a topic per conversation (millions of topics is not a Kafka pattern); millions of conversations share, say, 64 partitions. Assign each message a per-conversation sequence number when it is written, so clients can order and de-duplicate even if delivery retries. Redis Streams with one stream per conversation also works at smaller scale, but holding all history in memory limits retention.
Ephemeral presence events
Redis Pub/Sub for the "user went online/offline/typing" broadcasts, with the current state in Redis keys that carry a TTL (time-to-live) refreshed by heartbeats. Losing a presence event is harmless because the next heartbeat corrects it, so paying for durable storage (Kafka) buys nothing, and Kafka's retention would store millions of worthless "typing" events.
Notification service with a sub-100 ms tail-latency requirement
Split the path:
- Live path: the producer publishes to Redis (sharded) Pub/Sub on a channel per gateway or per user shard; the gateway holding the user's socket pushes immediately. In-memory, no disk write, the fastest option.
- Durable path, in parallel: the same notification is written to Kafka (or a per-user inbox table). If the user was offline, or the live publish was lost, the client fetches missed notifications from the inbox on reconnect.
A budget to design against (allocations, not measurements): 10 ms producer to Redis, 10 ms Redis to gateway, 20 ms gateway queue and write, 40 ms network to the client in-region, 20 ms reserve for the tail. Why not Kafka alone on the live path: it can meet sub-100 ms, but only with low producer batching, and its p99 is exposed to replication, consumer-group rebalances (Kafka briefly pausing a group's consumers while it reassigns partitions among them) and poll intervals (how often a consumer asks the broker for more records). Putting durability beside the latency-critical path, rather than in it, removes that risk. Verify the p99 end to end with synthetic probe notifications, not broker-internal metrics.
Trade-offs and pitfalls
- Using Redis Pub/Sub for anything that must not be lost is the classic mistake; a gateway restart silently drops every message published during it.
- A slow Pub/Sub subscriber is disconnected by Redis when its output buffer passes the configured limit, which is protective but means the gateway must resubscribe and resync.
- Kafka ordering holds only within a partition. Increasing the partition count remaps keys and can reorder in-flight messages for a conversation during the change.
- RabbitMQ ordering holds per queue with a single consumer; multiple competing consumers on one queue process messages in parallel and lose strict order.
- Three brokers is a real operational cost. A smaller team might run Kafka plus Redis only, and drop RabbitMQ unless task routing needs it.
Design a multi-CDN traffic-steering architecture to optimize availability and cost. Include real-time telemetry ingestion, a steering decision engine that chooses between failover and load-splitting, your chosen steering mechanism and why, and the metrics you would use to evaluate provider performance.
Sample Answer
Direct answer
Collect performance data from real viewers' players, turn it into a score per CDN per network (per country and per ISP), and have a decision engine publish a steering table every minute or so, driven by hysteresis (a required delay, or a threshold a state must clear and hold, before a decision is allowed to reverse, so a brief improvement cannot instantly flip a decision back). For video, apply that table inside the streaming session using manifest-level content steering (the player is given a manifest, the file listing a video's available quality renditions and where to fetch each segment of each one, plus a list of CDN hosts and a steering server it re-checks periodically), with DNS steering as the coarse default for non-video traffic. The engine runs in two modes: load-splitting by weight in normal operation, driven by cost commitments and quality, and failover when a CDN breaches a health threshold for a network, with hysteresis so traffic does not flap (switch rapidly back and forth between two states) between CDNs.
Terms used here
- CDN (content delivery network): a fleet of edge caches that serve content close to viewers. Multi-CDN means contracting two or more and choosing between them per request or per session.
- Steering: deciding which CDN a given viewer uses.
- RUM (real user monitoring): measurements sent ("beaconed") from actual players, as opposed to synthetic probes run from test machines.
- ASN (autonomous system number): the identifier of an ISP's network. CDN performance varies more by ISP than by country, so ASN is the key dimension.
- QoE (quality of experience): what the viewer feels: start time, rebuffering, picture quality.
- Commit: a contracted minimum monthly volume with a CDN. Traffic under the commit is effectively prepaid; traffic above it is charged as overage.
Architecture
flowchart LR
P[Players] -->|RUM beacons| I[Beacon ingest]
S[Synthetic probes] --> I
L[CDN logs and APIs] --> I
I --> A[1-min aggregates<br/>by CDN, country, ASN]
A --> D[Decision engine]
B[Commits and prices] --> D
D --> T[Steering table]
T --> CS[Content steering server]
T --> DNS[Steering DNS]
CS --> P
1. Real-time telemetry ingestion
- RUM is the primary signal because it measures the exact path a viewer uses. Each beacon carries: CDN host, country, ASN (derived server-side from the IP, not trusted from the client), device class, segment (a short chunk, typically a few seconds, of encoded video that a streaming player fetches one at a time) download time and throughput, HTTP errors, time to first frame, rebuffer events.
- Synthetic probes fill gaps where real traffic is thin (a small ISP at 4 a.m.) and detect an outage on a CDN that currently has no traffic steered to it. Without them, a CDN that was failed away from can never prove it has recovered.
- CDN logs and status APIs are the slowest signal (often minutes behind) and are used for billing reconciliation and confirmation, not for the fast loop.
- Ingest at the edge (a lightweight collector), push into a message queue, and roll up in-stream into 1-minute aggregates keyed by
(cdn, country, asn, device_class). Store percentiles as mergeable sketches (for example t-digest, a compact structure that lets you combine partial percentile summaries without keeping every sample).
2. The decision engine: failover versus load-splitting
Per (country, asn) cell, each minute:
- Health gate (failover decision). A CDN is unhealthy in the cell if, over the last 3 minutes with at least 200 samples: segment error rate is above 2%, or rebuffer ratio is above 3x its own 7-day baseline for that cell. Unhealthy CDNs get weight 0 in that cell.
- Quality score for healthy CDNs: a weighted blend of p90 (90th percentile) segment download throughput, time to first byte, and rebuffer ratio, normalised against the best CDN in the cell.
- Cost-aware split: start from a contract plan (for example 60/40) that is on track to meet each commit by month end, then shift weight toward the higher-quality CDN, capped so that no CDN is pushed into expensive overage unless the quality gap exceeds a threshold. Worked example: CDN A has a 3 PB/month commit, CDN B a 2 PB/month commit. Ten days before month end, CDN A has delivered 2.0 PB (67% of commit, on pace) and CDN B has delivered 2.1 PB (105% of commit, already in overage). The plan shifts weight from a 55/45 split toward something like 70/30, so more traffic lands on CDN A (helping it catch up toward its commit) and CDN B's overage stops growing. If CDN B's quality score is clearly better, for example 20% higher p90 throughput, the engine is still allowed to send it some traffic despite the overage, capped at 110% of commit, rather than cutting it off entirely and risking a QoE cliff for the viewers already on it.
- Hysteresis and damping: a CDN must be healthy for 10 consecutive minutes before it gets traffic back, and weights move at most 20 percentage points per minute. This prevents a feedback loop where moving all traffic to CDN B overloads CDN B's local edge, which then looks worse, which moves traffic back.
So the engine does both: load-splitting is the default, and failover is a per-cell override when the health gate trips. A global "all traffic to CDN B" switch exists only as a manual lever, because most CDN problems are regional or ISP-specific.
3. My chosen steering mechanism and why
| Mechanism | How it works | Granularity and speed | Main weakness |
|---|---|---|---|
| DNS steering | Authoritative DNS (the DNS server that holds the real records for a domain, as opposed to a resolver that just looks them up) returns a different CDN hostname per resolver (the DNS server, often run by the viewer's ISP or a public service, that looks up hostnames on the viewer's behalf) location | Per resolver; changes land after the DNS TTL (time-to-live), plus resolvers and devices that cache beyond it | Sees the resolver, not the viewer; cannot move a session already playing |
| Manifest / content steering | The player gets several CDN base URLs and a steering server URL; it re-fetches steering instructions periodically and switches CDN between segments | Per session, mid-stream, within one steering refresh interval | Needs player support (HLS Content Steering, DASH-IF Content Steering) |
| Pure client-side logic | Player measures and switches itself | Per session, instant | Each client sees one sample; no global view of cost or capacity |
Choice: content steering for video, DNS for everything else. Video sessions last an hour and are where cost and QoE concentrate, so they need mid-session moves: when CDN A degrades on one ISP, playing sessions move at the next segment rather than when they restart. The steering server response is tiny and per session, and it can also carry the CDN priority order the player falls back through if a segment fetch fails (that is the "client-side logic" layer, used only as an instant safety net). DNS steering stays for images, APIs and legacy players, and as the fallback if the steering server itself is down.
Worked example: sizing the loop
Assume a peak of 2 million concurrent viewers averaging 5 Mbit/s.
- Delivery volume: 2,000,000 x 5 Mbit/s = 10 Tbit/s. Per hour: 10 x 10^12 bits/s / 8 x 3,600 s = 4.5 x 10^15 bytes = 4.5 PB per hour. At that volume, shifting 10% of traffic between CDNs moves 450 TB per hour, which is why cost steering matters.
- Beacon rate: one beacon per viewer every 30 s gives 2,000,000 / 30 = about 66,700 beacons/s. At roughly 1 KB each that is about 67 MB/s of ingest, which a modest stream pipeline handles.
- Steering server load: if players re-check steering every 300 s, 2,000,000 / 300 = about 6,700 requests/s, each a small cacheable JSON response keyed by
(country, asn). - Reaction time: 1-minute aggregation + 3-minute health window + up to 300 s for players to re-check = worst case about 9 minutes for playing sessions to move after a subtle degradation. Hard failures are faster, because each player's own fallback kicks in on the first failed segment. If 9 minutes is too slow for the business, shorten the steering refresh (the cost is more steering requests), not the health window (which would make decisions on noise).
Metrics to evaluate provider performance
| Category | Metric | Why |
|---|---|---|
| Availability | Segment request error rate (4xx, 5xx, timeouts) per cell | The direct failover signal |
| Throughput | p50 (median, the 50th percentile) and p90 segment download throughput | Sets the bitrate the player can sustain |
| Latency | Time to first byte, manifest fetch time | Drives start time and live-edge latency |
| QoE | Video start time, rebuffer ratio (stall time divided by watch time), average delivered bitrate | What viewers feel; the tie-breaker between two "healthy" CDNs |
| Cache efficiency | Cache hit ratio (the share of requests an edge server answers from its own cache) and origin egress (the bandwidth pulled from origin, the source server behind the CDNs that holds the content those edge caches pull from when they miss) per CDN | Poor hit ratio costs you origin bandwidth even when viewers are fine |
| Cost | Effective cost per GB including commit shortfall or overage | The quality-per-dollar number that sets split weights |
| Steering accuracy | Share of sessions on the CDN the engine intended | Catches players ignoring steering or DNS resolvers caching |
Compare CDNs within the same cell (same ASN, device class, hour) and always on RUM, because a CDN serving mostly fibre users will look better than one serving mostly mobile users for reasons that have nothing to do with the CDN.
Trade-offs and pitfalls
- Flapping is the classic failure. Hysteresis, damping and minimum-sample rules are not optional.
- Self-inflicted overload: failing all traffic onto one CDN can exceed its capacity in a region. Agree burst capacity in contracts and cap per-cell shifts.
- Stale telemetry looks healthy: if beacons stop arriving from a cell, treat that as unknown, not as good.
- Cache warm-up: moving traffic to a cold CDN causes an origin surge. Protect origin with an origin shield (a mid-tier cache in front of origin) per CDN.
- When to prefer simpler: with one dominant CDN and a backup only for disasters, DNS failover alone is cheaper to build; content steering pays off once you split real volume across CDNs.
Estimate and compare the per-connection server resource implications (file descriptors, memory per connection, CPU context switching or event-loop overhead) and request pattern characteristics for: (a) persistent WebSocket connections, (b) Server-Sent Events (SSE), and (c) short polling every 5 seconds. Provide a back-of-envelope calculation for 1M concurrent clients and discuss the main bottlenecks and mitigation strategies.
Sample Answer
Direct answer
For 1 million clients, WebSockets and SSE (Server-Sent Events, a long-lived one-way HTTP stream from server to browser) have almost the same server shape: 1 million long-lived sockets, so 1 million file descriptors and a memory cost per idle connection, but almost no CPU while nothing is happening. Short polling every 5 seconds flips the cost: few sockets need to be open at any instant, but the fleet must answer 200,000 HTTP requests per second, almost all of them empty, which burns CPU and bandwidth on headers. My recommendation: SSE when traffic is server-to-client only, WebSockets when clients also send frequently, and short polling only as a fallback or when updates are rare and 5 seconds of staleness is acceptable.
Terms: WebSocket is a single TCP connection that starts as a normal HTTP request and is upgraded (the client and server agree, via an Upgrade header, to reuse that same connection as a long-lived, two-way channel instead of closing it after one response) into a channel either side can write to at any time; SSE (Server-Sent Events) is one long HTTP response the server keeps open and writes events into; a file descriptor (FD) is the kernel handle a process holds per open socket; an event loop is a single thread that waits on thousands of sockets at once (epoll on Linux) and runs code only for sockets that have data, instead of dedicating a thread per connection.
Assumptions (stated so the numbers can be checked)
- 1,000,000 concurrent clients, updates are infrequent (the typical case for notifications).
- Idle memory per long-lived connection: 8 KiB across kernel socket, TLS and application state (a budget to validate by measurement, not a benchmark).
- Poll request headers about 800 bytes (cookies, auth token, user agent), empty response about 200 bytes including headers.
- Poll request service time about 20 ms.
- Heartbeat on long-lived connections every 30 seconds.
Back-of-envelope for 1M clients
Short polling at 5 seconds
request rateper dayheader bandwidthin-flight requests (Little’s law)=1,000,000/5=200,000 requests per second=200,000×86,400=17.28 billion requests=200,000×(800+200) B=200 MB/s=1.6 Gbps=200,000×0.020 s=4,000Little's law says the average number of requests in the system equals arrival rate times time each spends inside. So only about 4,000 requests are being processed at any moment, but 200,000 per second must be parsed, authenticated and answered.
WebSocket or SSE
open socketsidle memoryheartbeats=1,000,000 (one FD each)=1,000,000×8 KiB≈7.63 GiB=1,000,000/30≈33,333 small frames per secondAt 16 KiB per connection the memory doubles to about 15.26 GiB; at 4 KiB it is about 3.81 GiB. Either way it spreads across a handful of servers.
Side-by-side comparison
| Dimension | WebSocket | SSE | Short polling (5 s) |
|---|---|---|---|
| FDs held | 1M, permanent | 1M, permanent | About 4,000 in flight; up to 1M if clients keep idle keep-alive connections open |
| Memory per client | Socket, TLS, small app state | Same as WebSocket | Near zero between polls |
| CPU when idle | Near zero with an event loop; heartbeats only | Same; a comment line (: keepalive) as heartbeat | 200,000 requests per second of parsing, auth and empty responses, continuously |
| Context switching | Low with event loop; a thread per connection would be 1M threads, unworkable | Same | Normal request-per-thread or async servers handle it; the load is request volume |
| Request pattern | One upgrade, then small frames both ways | One request, then a stream server-to-client; client sends via separate HTTP calls | A full HTTP request and response every 5 s per client |
| Latency to deliver an update | One network trip | One network trip | About 2.5 s average, up to 5 s |
| Reconnect behaviour | Client code must implement backoff | Browser EventSource reconnects automatically and sends Last-Event-ID (a header naming the last event it received, so the server can resume the stream instead of starting over) | Each poll is independent |
| Proxy and browser concerns | Upgrade must be allowed; idle timeouts | Response buffering by proxies must be off; HTTP/1.1 limits browsers to about 6 connections per origin, so serve over HTTP/2, which multiplexes many logical streams over one TCP connection and removes that per-origin cap | Works everywhere |
Main bottlenecks and mitigations
WebSocket and SSE
- Memory per connection dominates. Allocate read and write buffers only while data is moving, keep app state compact, and cap connections per server from a measured budget.
- FD limits: raise
ulimit -nand the kernel limits; run more than one process per host past about a million. - Reconnect storms after a deploy or failure: 1M reconnects in 60 seconds is about 16,667 TLS handshakes per second. Clients use exponential backoff with jitter (each retry waits longer than the last, up to a cap, with a random amount added so many clients don't all retry at the same instant); servers drain gradually and enforce an accept-rate cap (a limit on new connections accepted per second, so the surge queues instead of overwhelming the process).
- Load balancer idle timeouts kill quiet connections; heartbeat more often than the shortest timeout in the path.
- Fan-out (turning one update into one outbound write per connected client): a broadcast to 1M sockets is 1M writes. Distribute across gateways via pub/sub (publish/subscribe: one publish reaches every subscriber without the publisher knowing who or how many they are) so each server writes only to its own clients.
Short polling
- Request rate and header overhead: 1.6 Gbps of mostly headers to say "nothing new". Mitigate with conditional requests (
ETagandIf-None-Match, which let the server answer "304 Not Modified" with no body), a CDN (content delivery network) or cache in front for shared data, and longer intervals for background tabs. - TLS handshakes: if clients do not reuse connections, 200,000 new TLS handshakes per second would dominate CPU; enforce keep-alive, which pushes FD counts back toward the long-lived models.
- Database load: each poll that checks "anything new since X?" against a database is 200,000 queries per second; serve polls from a cache holding the latest version per user or channel.
- Synchronised polling: clients started together poll together; add random jitter to the interval.
Worked choice
A sports app pushing score updates to 1M fans, with clients never sending: SSE. Same socket cost as WebSockets, automatic reconnection with resume in the browser, plain HTTP that works through ordinary proxies. A collaborative editor where every client sends keystrokes: WebSockets. A dashboard refreshed every few minutes: short polling at a longer interval with ETag, because 1M clients at 5 minutes is only about 3,333 requests per second and no persistent-connection infrastructure is needed.
Trade-offs and pitfalls
- Counting only memory misses that polling's cost is CPU and bandwidth, while persistent connections' cost is memory and FDs. Compare each on its own bottleneck.
- Assuming SSE is cheaper than WebSockets per connection: server-side it is roughly the same. SSE's gains are simplicity and built-in resume, not resources.
- Forgetting mobile: long-lived connections are killed when apps go to the background; mobile clients combine a socket while in the foreground with push notifications otherwise.
Design a packaging strategy using CMAF to serve both HLS and DASH while minimizing storage duplication. Explain how manifests will be generated, chunking strategy, ad insertion considerations, and fallback logic for older clients that do not support CMAF.
Sample Answer
Direct answer
Encode each title once, package it once into CMAF (Common Media Application Format: a standard, ISO/IEC 23000-19, for fragmented MP4 media segments that both HLS and DASH can reference), encrypt it once with the cbcs scheme, and store that single set of segments. Then generate two thin text manifests over the same files: an HLS playlist (.m3u8) and a DASH MPD (Media Presentation Description, the XML manifest DASH uses). Storage is paid once instead of twice. Old clients that cannot play fragmented MP4 are served by a just-in-time (JIT) remuxer that repackages the CMAF segments into MPEG-TS on request, cached by the CDN (content delivery network) but never stored as a second library. Ads are inserted server-side at SCTE-35 cue points with ads conditioned to the same ladder.
Terms you need first
- HLS (HTTP Live Streaming, Apple) and DASH (Dynamic Adaptive Streaming over HTTP, MPEG) are two ways of describing the same idea: a manifest lists renditions (the same video at several bitrates and resolutions, called the ABR ladder, ABR meaning adaptive bitrate) and the short media files ("segments") the player downloads one after another.
- Historically HLS used MPEG-TS (MPEG transport stream) segments (
.ts) and DASH used fragmented MP4 (fMP4), so a service that supported both stored every title twice. CMAF standardises one fMP4 segment format that both can point at. - An init segment (
init.mp4) holds codec setup once per rendition; each media segment then carries only samples. - A CMAF chunk is a small piece of a segment (for example 0.5 s) that can be sent before the whole segment is finished. Chunks matter only for low-latency live.
- DRM (digital rights management) encryption comes in two incompatible Common Encryption modes. cenc uses AES-CTR: a way of encrypting the stream so any block can be decrypted on its own, without needing the blocks before it, which matters because a player must be able to jump straight into the middle of a segment. cbcs uses AES-CBC with a sample pattern: CBC must be decrypted in the exact order it was encrypted, so cbcs applies it to only a minority of the data, a defined pattern of 16-byte blocks (typically 1 encrypted block followed by 9 clear blocks, a 1:9 pattern), leaving the rest unencrypted. Encrypting roughly a tenth of the payload cuts a decoder's decryption work by about the same factor, which is the actual reason for the pattern: it matters most on battery-powered and lower-power hardware decoding 4K video, where full encryption would cost more compute and battery than the device can spare. The content stays unplayable without the key regardless, since the clear blocks alone do not reconstruct a usable frame. A secondary side effect is that the untouched NAL headers stay readable, so a decoder can still parse the bitstream's frame structure without decrypting first, but that is a consequence of the pattern, not its purpose. A device's DRM stack is built to decrypt one of these modes, not both, so one copy works for everyone only if every target DRM accepts the same mode.
Architecture
flowchart LR
ENC[Encoder: one ABR ladder] --> PKG[CMAF packager: fMP4 + cbcs]
PKG --> STORE[(Object storage: one segment set)]
PKG --> META[(Presentation record: renditions, codecs, timeline)]
META --> MAN[Manifest service: HLS and DASH]
STORE --> CDN[CDN]
MAN --> CDN
STORE --> JIT[JIT remuxer: fMP4 to TS]
JIT --> CDN
CUE[SCTE-35 cues] --> SSAI[Ad stitcher]
SSAI --> CDN
1. Manifest generation
Treat the manifests as views over one source of truth. The packager writes a presentation record per title: each rendition's bandwidth, resolution, codec string (for example avc1.64001f, mp4a.40.2), init segment URL, segment duration and timeline. The manifest service renders two protocol-specific views of that one record (the tag names below are the literal syntax your packager emits, useful once you implement this; the idea that matters for the design is that both views come from the same record and so cannot drift apart):
- HLS: a multivariant playlist with one
#EXT-X-STREAM-INFper rendition (including theCODECSandBANDWIDTHattributes), plus one media playlist per rendition that uses#EXT-X-MAPto point atinit.mp4and lists the same.m4ssegments. - DASH: an MPD with one
AdaptationSetfor video and one per audio language, usingSegmentTemplate(withSegmentTimelinefor live) that resolves to the identical.m4sURLs.
For VOD (video on demand) render both once at publish time and cache them with long TTLs (time-to-live). For live, the manifest service updates both every time a segment lands. Because both are generated from one record, they cannot drift apart (one of the classic bugs of dual pipelines is an HLS rendition that DASH lacks).
2. Chunking strategy
- Segments of 4 s, closed GOPs of 2 s, aligned across every rendition. A GOP (group of pictures) is closed when none of its frames reference any frame outside the GOP, so it decodes on its own; an open GOP can borrow frames from the next one, which is fine mid-stream but breaks a clean split at a segment or ad boundary. A GOP must start with a keyframe exactly at each segment boundary in every rendition, or the player cannot switch rungs cleanly. 4 s balances request count (shorter means more requests and more manifest churn) against switching agility and live latency (longer means slower reaction and higher latency).
- Demuxed audio: audio in its own tracks, so two audio languages serve all six video rungs instead of being copied into each.
- Low-latency live only: split each segment into 0.5 to 1 s CMAF chunks. The same chunks become LL-HLS (Low-Latency HLS) partial segments (
#EXT-X-PART) and LL-DASH chunked-transfer delivery (DASH's equivalent: the server starts sending a segment's bytes over an HTTP connection that stays open while the segment is still being encoded, instead of waiting for the whole file). VOD does not need chunks. - Where the 20 s to 4 s in the follow-up comes from: with ordinary 4 s segments, a player that conservatively buffers three whole segments before it starts playing is already 4 x 3 = 12 s behind real time, and on top of that it cannot even request a segment until the encoder has finished producing the entire 4 s of video, then packaged and pushed it through the origin and CDN, which adds roughly another segment's worth of production latency plus a few seconds of network and CDN overhead, landing around 20 s behind live in total. CMAF chunking cuts both halves together, not just one: buffering three 0.5 s chunks instead of three 4 s segments shrinks the buffer to about 1.5 s, and because a single chunk, not the whole segment, can be requested and delivered as soon as it is encoded, the production-and-delivery latency shrinks from roughly a segment's worth to roughly a chunk's worth too, landing the total around 4 s behind live.
3. Ad insertion considerations
- Signal: carry SCTE-35 cue messages (the broadcast standard marker for "ad break starts here, lasts N seconds") from the source into the packager. Emit them in HLS as
#EXT-X-DATERANGEand in DASH as an event stream so both manifests mark the same break. (The manifest tag names in this section, like#EXT-X-DATERANGE, are the literal syntax your packager emits; the idea that matters for the design is "both manifests carry the same ad-break signal," not memorizing the tags.) - Server-side ad insertion (SSAI): an ad stitcher rewrites the manifest per viewer session, swapping content segments for ad segments. HLS marks the splice with
#EXT-X-DISCONTINUITY(timestamps and possibly encoding change here); DASH starts a newPeriod. - Condition the ads: ads must be transcoded into the same ladder, codecs and audio sample rate, and packaged as CMAF. An ad arriving as a single 1080p file with 48 kHz audio against a 44.1 kHz programme causes decoder resets and audio glitches on some devices.
- Caching consequence: per-session manifests become uncacheable (or cached per session), but segments stay shared and cacheable. Budget manifest-service capacity for one request per viewer per segment duration during live events.
- Encryption boundaries: content is usually encrypted and ads are often clear. Clear-to-encrypted transitions are a known source of playback failures on older devices; encrypting ads with the same scheme, or testing the transition on the device matrix, removes the surprise.
4. Fallback logic for clients without CMAF
- Detect capability at manifest request time, not at segment time. The manifest service classifies the device (app build, player version, device model; user-agent only as a last resort) against a capability table.
- Modern HLS players (fMP4 support arrived in HLS in 2016) get the CMAF playlist. DASH players already use fMP4, so they need no fallback for the container, only for encryption mode.
- Legacy HLS players get a playlist whose segment URLs point at the JIT remuxer. It reads the CMAF segment, rewrites the container to MPEG-TS (no re-encode: same frames, different wrapper, so it is cheap), and returns it with the same cache headers. The CDN caches the TS output behind a shield (a regional mid-tier cache that every edge in that region routes through before reaching origin, so a cache miss at ten different edges still only asks the origin, or here the remuxer, once), so the remux happens roughly once per segment per shield rather than once per viewer.
- DRM fallback: devices whose DRM only accepts cenc cannot play cbcs. Either JIT re-encrypt for that cohort, which means every edge doing the re-encryption needs the encryption keys itself and those keys must be distributed and rotated out at every one of those locations instead of staying centralized at one packager, multiplying the places a key can leak or go stale (this is the "key-management complexity at the edge"), or, if the cohort is large, store a second cenc copy of the top renditions only. Measure the cohort before choosing.
- Runtime fallback: if a player errors on the CMAF path (decoder or DRM error codes), the client retries once on the legacy path and reports the device model, which feeds back into the capability table.
Worked example: what storage duplication costs
Ladder of six video renditions: 0.4, 0.8, 1.6, 3.0, 4.5 and 7.8 Mbps, summing to 18.1 Mbps.
- One hour of all renditions: 18.1 Mbps × 3,600 s ÷ 8 = 8,145 MB, about 8.145 GB per hour.
- A 10,000-hour library: 8.145 × 10,000 = 81,450 GB, about 81.45 TB.
- Separate TS for HLS and fMP4 for DASH: 2 × 81.45 = 162.9 TB. CMAF removes one full copy: 81.45 TB saved, before counting the CDN benefit that one cached object now serves both protocols (hit ratio improves because HLS and DASH viewers share cache entries).
- If 5% of plays come from legacy HLS clients, the JIT path costs remux compute for the segments those viewers actually request and stores nothing permanently. That is the right trade while the cohort is small.
Trade-offs and pitfalls
| Choice | Pick it when | Cost |
|---|---|---|
| Static CMAF + static manifests | VOD, predictable catalogue | Re-package the library to change a manifest feature |
| JIT packaging for everything | Many output variants, frequent format changes | Origin compute on every cache miss; packager outage = playback outage |
| Static CMAF + JIT only for legacy | Legacy cohort under roughly 10 to 20% | Two code paths to test |
- Unaligned keyframes across renditions is the most common reason "one set of segments" fails: switching produces visual glitches.
- Assuming one encryption mode works everywhere without checking the device matrix. cbcs is the mode that FairPlay (Apple's DRM, used on iOS, tvOS and Safari) requires; older Widevine (Google's DRM, used on Android and Chrome) and PlayReady (Microsoft's DRM, used on Windows and many smart TVs) devices may only support cenc.
- Letting HLS and DASH manifests be produced by different code paths reintroduces drift.
- Forgetting that SSAI makes manifests per-session: the origin load model changes from per-title to per-viewer.
- What would change the design: a legacy cohort above roughly a fifth of plays, or a DRM cohort that only accepts cenc, would justify storing a second copy of the most-watched titles rather than paying remux or re-encrypt compute on every miss.
Estimate capacity and monthly cost for a service that keeps 10 million persistent WebSocket connections open, each sending 1KB/s on average. Show calculations for sustained bandwidth requirements, TLS overhead, server instance sizing (connections per server), proxy/gateway sizing, redundancy, and cloud egress cost assumptions. State assumptions clearly.
Sample Answer
Direct answer
10 million connections at 1 KB per second each is 10 GB per second, 80 Gbps of payload, about 87 Gbps on the wire after WebSocket (a long-lived, two-way connection upgraded from a single HTTP request, so the client and server exchange small frames on it instead of repeated requests), TLS and TCP/IP headers. At an assumed 100,000 connections per server that is 100 servers, 150 once you can lose one of three availability zones (AZs: physically separate data centres within one region, used so that one zone failing does not take the whole service down). The decisive cost question is direction: client-to-server traffic is inbound, and inbound internet data transfer is free on AWS, so if the 1 KB/s is only upstream, compute dominates the bill. If the service also sends a similar 1 KB/s back down to each client, that is about 25,920 TB per month of egress and roughly $1.2 to 1.3 million per month at AWS list prices, using AWS's own binary GB (2^30 bytes) billing unit, which dwarfs the servers (tens of thousands to around a hundred thousand dollars) and makes egress pricing the thing to negotiate.
Assumptions
- "Sending 1 KB/s" means each client sends 1,000 bytes of payload per second, as one message per second. I also cost the case where the server sends the same volume back.
- Decimal units for bandwidth (1 KB = 1,000 bytes) when describing raw traffic. For the AWS bill itself, AWS's own S3 pricing page states outright that AWS "storage usage is calculated in binary gigabytes (GB), where 1 GB is 2^30 bytes... 1 TB is 2^40 bytes, i.e. 1024 GBs," and data-transfer metering uses that same GB, not a decimal 10^9-byte one. The cost section below uses that binary GB, and separately shows what the total would be under the (wrong, for AWS) decimal assumption, since that is an easy mistake to make and worth pricing out.
- One month = 30 days = 2,592,000 seconds.
- 100,000 connections per server (a sizing to validate by load test; memory and CPU both fit comfortably at this rate, see below).
- Three availability zones, sized to survive losing one.
- Egress prices from the AWS public price list for us-east-1 (published 2026-09-16): internet egress $0.09/GB for the first 10 TB, $0.085/GB for the next 40 TB, $0.07/GB for the next 100 TB, $0.05/GB beyond 150 TB; inbound $0.00/GB.
Sustained bandwidth
payload10 GB/s×8=107×1,000 B/s=1010 B/s=10 GB/s=80 GbpsProtocol and TLS overhead
Per 1,000-byte message sent by a client:
| Layer | Bytes | Why |
|---|---|---|
| WebSocket frame header | 8 | 2 base bytes, 2 bytes extended length (payload 126 to 65,535 bytes), 4-byte mask required on client-to-server frames |
| TLS 1.3 record | 22 | 5-byte record header, 1-byte inner content type, 16-byte authentication tag from the AES-GCM cipher (the common authenticated-encryption mode) |
| TCP/IP headers | 52 | 20 IPv4, 20 TCP, 12 TCP timestamp option; 1,082 bytes fits in one packet |
| Total on the wire | 1,082 | 8.2% overhead |
(The mask is a 4-byte key the client XORs into its frame's payload bytes; the WebSocket spec requires it only on client-to-server frames, to stop an attacker's page from crafting bytes that look like a plain HTTP request to a misconfigured shared proxy. The TCP timestamp option is 12 bytes some stacks add to every segment to measure round-trip time and reject old duplicate packets.) Server-to-client frames carry no mask, so a downstream 1,000-byte message is 1,078 bytes (1,082 minus the 4-byte mask). The overhead percentage rises sharply if the same 1 KB/s is sent as many small messages: ten 100-byte messages per second would carry ten sets of headers. Batching small updates is a real cost lever. TLS handshakes themselves are negligible on long-lived connections but matter during reconnect storms (CPU, not bandwidth).
Server sizing
base serversper-server trafficper-server message rate=10,000,000/100,000=100=100,000×1,082×8≈0.87 Gbps=100,000 messages per secondBandwidth per server is well under a 10 or 25 Gbps NIC (network interface card). The real per-server limit is CPU: decrypting, parsing and routing 100,000 messages per second, so the 100,000 figure must come from a load test on the chosen instance type. Memory at, say, 20 KiB per connection is about 1.9 GiB for 100,000 connections, not binding.
Redundancy. To survive one AZ failing, the remaining two must carry everything:
per AZtotal=⌈100/2⌉=50=50×3=150 serversThat is 50% over base, the price of zone-failure tolerance without overload.
Proxy and gateway sizing
Two options for the front door:
- Managed L4 load balancer (a Layer 4 load balancer routes on IP address and port only, without reading application data; for example AWS's Network Load Balancer, a managed TCP/UDP load-balancing service) passing TCP through (it forwards each client's TCP connection on to a server without opening or reading it itself), with TLS terminated on the servers (the application servers hold the TLS session and do the decryption, not the balancer). No extra fleet to size; the balancer bills on capacity units (a hardware-abstracted billing metric that blends new connections, active connections and bytes processed into one hourly number), so at this scale the bytes-processed component needs to be priced from the current price list. My recommendation, because it does not add a second socket per client.
- Self-run proxy tier (Envoy or HAProxy, two widely used open-source reverse proxies) terminating TLS (the proxy itself decrypts the client's TLS connection, then opens a separate, new connection to talk to a backend server). Each client connection becomes two sockets (client side and backend side), because the proxy is acting as a server to the client and, independently, as a client to the backend, rather than just passing bytes through, so 20 million sockets fleet-wide. Bandwidth sizing: 86.56 Gbps in each direction, and planning each proxy at 50% of a 25 Gbps NIC (12.5 Gbps):
But after an AZ loss 8 proxies would each hold 1.25 million client sockets plus 1.25 million backend sockets, so memory and FD limits, not bandwidth, push the count higher, likely toward 20 to 30 proxies. That extra fleet is the main argument for the managed L4 path.
Cost
Egress, if the server sends 1 KB/s back to each client:
AWS's billing GB is binary: 1 GB is $2^{30} = 1{,}073{,}741{,}824$ bytes (a gibibyte, GiB), per AWS's own S3 pricing page, and AWS states its TB as 1,024 of that same GB, so the price list's tier boundaries (10 TB, 40 TB, 100 TB, 150 TB) are already 10,240 / 40,960 / 102,400 / 153,600 of that binary GB. The byte volume below is converted with that same binary GB so the comparison is apples to apples.
monthly volumefirst 150 TB (153,600 GB)remaindertotal=1010 B/s×2,592,000 s=2.592×1016 B=2.592×1016/230≈24,139,881 GB (AWS binary GB)=10,240×0.09+40,960×0.085+102,400×0.07=$11,571.20=(24,139,881−153,600)×0.05≈$1,199,314.06≈$1,210,885 per monthIncluding the 1,078-byte downstream wire size, the monthly volume is $10^7 \times 1{,}078 \text{ B/s} \times 2{,}592{,}000 \text{ s} = 2.794176 \times 10^{16} \text{ B} \approx 26{,}022{,}792 \text{ GB (AWS binary GB)}$; the same tiers (unchanged $11,571.20 for the first 153,600 GB, plus $(26{,}022{,}792 - 153{,}600) \times $0.05 \approx $1{,}293{,}459.59$ for the remainder) give about $1,305,031 per month.
If instead you priced this the way it is easy to get wrong, treating AWS's billed GB as the decimal $10^9$-byte GB that raw-bandwidth figures like "80 Gbps" use: the monthly volume comes out to 25,920,000 (payload-only) or 27,941,760 (wire-inclusive) of that smaller, decimal GB, and the same tier rates give about $1,299,891 and $1,400,979 per month respectively, about 7% higher than the correct binary-GB total. The gap is exactly the 7.4% difference between a decimal gigabyte and a binary one, and it lands almost entirely in the 5-cent tier where nearly all the volume sits, since $10^9 / 1{,}073{,}741{,}824 \approx 0.931$, i.e. treating bytes as decimal GB overcounts billed units by about 1/0.931 - 1 \approx 7.4%.
Ingress: the 1 KB/s upstream costs $0 in data transfer.
Instances: 150 servers x 720 hours. At an illustrative $0.40 per instance-hour this is $43,200 per month; at $1.00 per hour, $108,000. Plug in the current on-demand or committed rate for the instance type your load test selects. Either way, if downstream traffic exists, egress is more than 10 times the compute bill.
What to do with that
- Negotiate committed-use egress pricing (a lower per-GB rate in exchange for committing to a minimum monthly spend, the egress equivalent of a reserved-instance compute discount) or use a CDN (content delivery network) or edge platform with lower per-GB rates for the downstream path; at $1.2 million per month list, this is the highest-return conversation.
- Cut bytes: binary encoding instead of JSON, delta updates instead of full state, batching several small updates into one frame.
- Keep traffic in-zone: cross-AZ traffic inside AWS adds $0.01/GB on each side.
Trade-offs and pitfalls
- Forgetting direction: costing "1 KB/s" as egress when it is upload overstates the bill by a million dollars a month; costing it as upload only, when the product echoes or fans out messages, understates it by the same.
- Ignoring headers on small messages: at 100-byte messages overhead is closer to 80% than 8%.
- Sizing on bandwidth alone: 0.87 Gbps per server looks trivial, but 100,000 messages per second per server is a CPU number that must be measured.
Unlock Full Question Bank
Get access to all 20 Real-Time and Streaming System Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.