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.
Explain the WebSocket opening handshake and how it differs from a typical HTTP request/response flow. Compare WebSocket with HTTP/2 server push and SSE in terms of compatibility with HTTP proxies, TLS termination, connection upgrade requirements, and failure modes when intermediaries interfere. Describe practical mitigations for proxy or firewall incompatibilities.
Sample Answer
Direct answer
A WebSocket starts life as an ordinary HTTP/1.1 GET with an Upgrade: websocket header; if the server agrees it answers 101 Switching Protocols, and from then on the same TCP connection stops being HTTP and carries WebSocket frames in both directions for as long as it lives. A normal HTTP exchange is one request, one response, done. That upgrade is exactly what trips up intermediaries: a proxy that does not understand it strips the header, times out the "idle" connection, or buffers it. SSE avoids the problem by being a plain long HTTP response, and HTTP/2 server push is not an alternative for messaging at all. The main mitigations are always use wss:// on port 443, send heartbeats shorter than any idle timeout, configure your own proxies explicitly, and keep an SSE or long-polling fallback.
The handshake step by step
Client request:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://example.com
Server response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Keyis 16 random bytes, base64-encoded. It is not a security credential; it proves the server really speaks WebSocket (and did not just echo a cached HTTP response).- The server computes
Sec-WebSocket-Accept= base64(SHA-1(key + the fixed GUID258EAFA5-E914-47DA-95CA-C5AB0DC85B11)). This runnable Python reproduces the value above, which is the example from RFC 6455, the WebSocket specification:
import base64, hashlib
key = "dGhlIHNhbXBsZSBub25jZQ=="
guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
print(base64.b64encode(hashlib.sha1((key + guid).encode()).digest()).decode())
s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Originlets the server reject pages from other sites (browsers send it; check it, because cookies are sent automatically on the handshake).- After the 101, both sides exchange frames: small headers plus payload, with ping/pong control frames and a close handshake. Client-to-server frames are masked with a random 4-byte key, which exists to stop a malicious page from making the bytes on the wire look like a valid HTTP request to a confused cache: without masking, JavaScript on an attacker's page could choose a payload that, byte for byte, reads as a second HTTP request smuggled inside the stream, and a shared cache sitting in front of the server could mistake that smuggled request's response for real traffic and serve the attacker's chosen content to other users.
How it differs from a normal HTTP request/response: normal HTTP is request-driven and finished after each response; the connection may be reused but every exchange is independent and visible to intermediaries as requests. After a WebSocket upgrade there are no more requests, no status codes, no per-message headers; the server can send at any moment, and a proxy sees one very long opaque exchange.
Compatibility comparison
| Concern | WebSocket | SSE | HTTP/2 server push |
|---|---|---|---|
| HTTP proxies | Upgrade and Connection are hop-by-hop headers (meant only for the very next proxy, not copied through automatically the way most headers are, so passing them on is opt-in): every proxy must deliberately forward them. Transparent proxies (proxies a client never configured and does not know exist, inserted into the path by a network operator) on plain ws:// often strip them or break the stream | Plain HTTP GET with a streamed response; passes through nearly all proxies, but buffering proxies delay events until the response "finishes" (never) | Only works hop by hop if every intermediary speaks HTTP/2 end to end; most CDNs do not forward push |
| TLS termination | TLS termination is the point in the network where encrypted traffic is decrypted back to plain bytes; only the box that terminates TLS can read or rewrite the handshake, everything downstream of it just sees plaintext. With wss:// a plain proxy sees only an encrypted tunnel it cannot read (opened with the HTTP CONNECT method, which asks the proxy to stop parsing and just relay raw bytes to the destination) and cannot interfere, unless it deliberately intercepts TLS (terminates it itself with its own certificate so it can read and modify the decrypted traffic, a common corporate-network setup). The terminating load balancer must support upgrades and long idle timeouts | Terminates like any HTTPS request; the load balancer needs streaming (no buffering) and a long idle timeout | Push is sent from the server that terminated TLS; anything behind that is invisible to the browser |
| Upgrade requirement | Yes (HTTP/1.1 Upgrade, or RFC 8441 extended CONNECT on HTTP/2, which fewer intermediaries support) | None | None, but only in response to a client request |
| Failure modes when intermediaries interfere | Handshake rejected (400, 403), upgrade silently stripped (response is a normal 200), connection accepted then frames dropped, idle connection killed at a fixed interval (close code 1006, abnormal closure) | Events arrive in bursts or never, due to buffering; stream cut at idle timeout; browser auto-reconnects | Pushes ignored or refused by the browser; disabled by default in Chrome since version 106 |
| Use for messaging | Yes, bidirectional | Yes, server to client | No: pushed responses go into the cache, not to your application code |
Practical mitigations
- Use
wss://on port 443 always. Encrypted traffic on the standard HTTPS port is the most likely to pass untouched; plainws://on port 80 is the most likely to be mangled. - Heartbeats below every idle timeout. Many load balancers and proxies drop idle connections after about 60 s by default (nginx's
proxy_read_timeoutdefaults to 60 s, for example). Send an application ping every 20 to 30 s, and raise the timeouts on infrastructure you control. - Configure your own proxies explicitly. In nginx, a WebSocket location needs
proxy_http_version 1.1;plusproxy_set_headerdirectives that pass the client'sUpgradeheader through and setConnection: upgrade, otherwise the upgrade headers are dropped. For SSE, disable response buffering (nginx honours anX-Accel-Buffering: noresponse header). - Detect and fall back. Treat the connection as working only after a first application message arrives; after repeated failures on a network, fall back to SSE plus
POST, then long polling. - Authentication through the handshake. Browsers cannot set custom headers on the WebSocket constructor, so use a cookie (and check
Originto prevent cross-site WebSocket hijacking, where a malicious page on another site opens a socket to your server and the browser attaches the victim's cookies automatically, handing the attacker a live authenticated connection) or a short-lived single-use ticket. - Deploys and draining: close connections gradually with a proper close frame, and have clients reconnect with jittered backoff (wait a random, growing amount of time before retrying, instead of a fixed delay, so thousands of clients do not all retry in the same instant), so a deploy does not look like a proxy failure to thousands of clients at once.
Worked example
A customer reports the chat widget "connects then dies every minute" from their office. Server logs show connections closing with 1006 at about 60 s on that customer's IP range only. Their proxy has a 60 s idle timeout and your app pings every 90 s. Dropping the ping interval to 25 s fixes it without a fallback. A second customer's proxy strips Upgrade entirely: the handshake gets a plain 200 response, the client never receives a welcome message, and it falls back to SSE, which also turns out to be buffered, so it lands on long polling. Both are "WebSocket doesn't work" tickets with completely different fixes.
Outline a comprehensive security design to protect premium streaming content against unauthorized access and piracy, across ingest, storage, and playback. Address how you would verify a legitimate viewer and device before playback, prevent stream ripping or credential sharing, and give operations visibility into abuse and enforcement. Discuss the operational touchpoints for monitoring and takedown.
Sample Answer
Direct answer
Protect content in layers, because every single control can be defeated. Keep the source files locked down at ingest and in storage; encrypt every delivered stream with multi-DRM so the bytes on the CDN are useless without a licence; hand out licences only after checking the account, the entitlement (the record that says this account is allowed to watch this title: subscription tier, purchase, region rights), the device and its security level; bind URLs to short-lived signed tokens; enforce concurrent-stream and device limits to stop credential sharing; and put an invisible forensic watermark in premium streams so a leaked copy can be traced to the account that leaked it. Operations then watch licence and token failures, sharing signals and pirate sites, and act through revocation and takedown.
Terms
- DRM (digital rights management): content is encrypted with a content key; a licence server gives the key only to approved players, inside a protected component (the CDM, content decryption module) so the app never sees the key. The three systems are Widevine (Google), FairPlay (Apple) and PlayReady (Microsoft). Multi-DRM means one encryption serving all three, using CENC (Common Encryption).
- Widevine security levels: L1 decrypts and decodes inside hardware (a trusted execution environment); L3 does it in software, which is easier to attack. PlayReady has similar SL3000 (hardware) and SL2000 (software) levels.
- HDCP (High-bandwidth Digital Content Protection): encryption on the HDMI cable, so the signal to the TV cannot be captured by a cheap recorder.
- Forensic watermarking: an invisible, per-session mark in the video that survives re-encoding and screen recording, identifying which session produced a pirated copy.
- CDN (content delivery network); KMS (key management service): a managed service that stores keys and performs encryption so keys never sit in application config.
Architecture by stage
flowchart LR
I[Ingest<br/>mTLS, encrypted contribution] --> S[(Mezzanine store<br/>encrypted, restricted)]
S --> P[Encode and package<br/>CENC multi-DRM, watermark variants]
K[Key server backed by KMS] --> P
P --> C[CDN<br/>signed-token check]
A[Auth, entitlement,<br/>device registry] --> T[Playback API]
T -->|token + licence URL| PL[Player]
PL --> C
PL --> LS[Licence server]
LS --> K
LS --> A
Ingest
- Content arrives from studios or live venues over encrypted transport: SRT (Secure Reliable Transport, a live contribution protocol) with AES (Advanced Encryption Standard, the standard cipher used to scramble the data) encryption for live feeds, and mTLS (mutual TLS, where both sides present certificates) or a dedicated file-transfer service for files.
- The ingest network is isolated; only the ingest service can write to the source bucket, and every file is checksummed on arrival.
Storage
- Mezzanine files (the high-quality masters) are the crown jewels: an unencrypted 4K master is a perfect pirate source. Encrypt at rest with KMS-managed keys, restrict read access to the encode pipeline's identity, deny human access by default (break-glass access, an emergency manual override for genuine incidents, is logged and time-boxed), and keep access logs in a separate account.
- Content keys live in the key server, never beside the media.
Packaging
- Encode, then encrypt with CENC
cbcsmode (one specific way of applying Common Encryption to the video, chosen because it is the one mode all three DRM systems accept), so one encrypted copy serves every device. - Use key rotation per title and, for live, periodically during the event, so one leaked key exposes only a slice.
- For premium titles and live sports, produce A/B watermark variants: every segment is encoded twice with invisible marks A and B; each session receives a unique A/B sequence, which spells out a session identifier. How that actually encodes an id: each dual-encoded segment is one bit (A = 0, B = 1), so N such segments give 2^N possible sequences. 2^20 = 1,048,576, so 20 dual-encoded segments are enough to uniquely tag over a million concurrent sessions: session id 500,000 gets the 20-bit binary pattern of 500000, which is
01111010000100100000(checked by runningformat(500000, '020b')), i.e. the watermark sequenceABBBBABAAAABAABAAAAA. Because only the first 20 segments (roughly the first minute or two of a 4 s-segment stream) need the extra encoding pass, tagging a whole 2-hour title costs far less than double-encoding every segment in it; a leaked copy is read back through those first segments and matched against the assignment table on file.
Verifying a legitimate viewer and device before playback
- User signs in; the playback API checks the entitlement (subscription tier, pay-per-view purchase, region rights).
- The device presents its registration id and platform attestation (a platform-signed statement that the app and device are genuine and unmodified, such as Play Integrity on Android or App Attest on iOS). Rooted devices (phones where the owner has removed the manufacturer's software restrictions, which also removes the protections DRM relies on) or emulated devices can be restricted to lower quality.
- The API issues a short-lived signed playback token scoped to that title's path, plus a licence request token.
- The licence server re-checks the entitlement, the device's DRM security level and the concurrency count, then returns a licence with a policy: for example, 4K and HDR (high dynamic range: a wider range of brightness and colour than standard video) only for hardware (L1 or SL3000) with HDCP 2.2, HD for hardware without the newest HDCP, SD for software-only DRM.
Preventing stream ripping and credential sharing
- Ripping (saving the stream to a file) is blocked by DRM for the downloaded bytes and by hardware security levels for the decoded picture. Software DRM is the weak point, which is why premium resolutions are held back from it.
- Screen and HDMI capture: HDCP on output; OS-level secure surfaces that show black in screenshots and screen recordings.
- Restreaming a legitimate session to a pirate site cannot be fully prevented; that is what the watermark is for.
- Credential sharing:
- Concurrent-stream limit enforced by the licence server: each playback holds a slot and renews it with a heartbeat; a new stream over the plan's limit is refused.
- Device limit: a maximum number of registered devices per account, with a cooldown on removing and re-adding.
- Anomaly signals: many distinct networks per hour, impossible travel (sessions in two countries 10 minutes apart), large numbers of devices, all feeding a risk score that triggers step-up checks (re-authentication, verification code) rather than silent blocks.
Worked example: licence-server load
For 1,000,000 concurrent live viewers whose licences must be renewed every 10 minutes (so concurrency limits and revocations take effect quickly), renewals alone are 1,000,000 / 600 s = about 1,667 requests/s. Add the start-of-event surge: if 1,000,000 viewers start in the 5 minutes before kickoff, that is 1,000,000 / 300 = about 3,333 new licences/s on top. Size the licence and concurrency services for roughly 5,000 requests/s plus headroom, pre-scale before the event, and keep the concurrency store in a fast in-memory database with per-account keys.
Operations visibility, monitoring and takedown
Dashboards and alerts
- Licence denials by reason (no entitlement, security level, concurrency, revoked device), token validation failures at the CDN by reason, attestation failures, concurrency-limit hits per account.
- Spikes are signals: a rise in token failures on one title can mean someone is replaying stolen URLs.
Piracy monitoring
- A monitoring function (in-house or a vendor) crawls pirate sites, social platforms and restream services for your titles and live events.
- For each pirate copy found, extract the watermark to get the session id, and map that to the account and device.
Enforcement and takedown touchpoints
| Finding | Action | Owner |
|---|---|---|
| Leaking session identified during a live event | Revoke that session's licence and token immediately; the stream stops at next renewal | Security operations, automated with approval |
| Account repeatedly leaking | Suspend account, block device ids | Trust and safety |
| Pirate site hosting copies | Send takedown notices (for example DMCA, US Digital Millennium Copyright Act, notices) to host, CDN and search engines | Legal or anti-piracy vendor |
| Key or DRM compromise suspected | Rotate keys, re-package affected titles, raise the minimum security level | Platform security |
Every enforcement action is logged with evidence (watermark extract, timestamps) so disputes and legal action have a record.
Trade-offs and pitfalls
- Tight concurrency and device limits cut sharing and also frustrate honest families; roll out with generous limits and measure support contacts.
- Short licence renewals make revocation fast but add load and a failure dependency: if the licence server is down, viewers stop. Provide a grace period on renewal failure.
- Watermarking adds encode and storage cost (two variants per segment); reserve it for titles where leak value justifies it.
- Security by obscurity (hidden URLs, client-side checks) is not protection; anything in the app can be read.
Design an authentication and authorization system for real-time channels that supports device-level revocation, instantaneous permission changes, token rotation, and auditing at scale. Discuss token lifetimes, refresh strategies, revocation mechanisms (push vs token versioning), performance trade-offs, and how to revoke millions of active sessions quickly if needed.
Sample Answer
Direct answer
Separate authentication at connect time from authorization that stays live for the life of the connection. The client connects with a short-lived access token (5 minutes) bound to a device session (one session record per device), and re-authenticates in-band over the open socket before the token expires, so rotation never forces a reconnect. For instant changes I use push revocation: a revocation or permission-change event goes on an event bus (a broadcast channel where every subscriber, here each gateway, gets a copy of each message), every gateway receives it, and the gateway holding the affected connections closes them or drops their subscriptions within seconds. Token versioning (a per-user or per-tenant "revoked before" timestamp or counter) is the backstop that makes the push safe to miss, and it is also how you revoke millions of sessions with one write instead of millions. Every auth decision (connect, subscribe, deny, revoke) is written to an append-only audit stream.
Terms
- Access token: a signed credential (typically a JWT, JSON Web Token) the gateway can verify locally with a public key, with no database lookup.
- Refresh token: a long-lived, server-tracked credential used only to obtain new access tokens.
- Revocation: making a still-unexpired credential stop working.
- Push vs token versioning: push means the server actively tells gateways "kill these connections now"; versioning means every credential carries a version and anything below the current version is rejected the next time it is checked.
Architecture
flowchart LR
DEV[Device] -->|access token| GW[Realtime gateways]
DEV -->|refresh token| AUTH[Auth service]
AUTH --> SES[(Session store)]
AUTH -->|revoke and permission events| BUS[Event bus]
BUS --> GW
GW --> AUD[(Audit log)]
AUTH --> AUD
Working numbers: 5,000,000 concurrent connections over 100 gateway nodes = 50,000 per node.
Token lifetimes and refresh
| Credential | Lifetime | Why |
|---|---|---|
| Access token | 5 minutes | Limits the damage if one leaks; short enough that a missed revocation push expires on its own quickly |
| Refresh token | 30 days, sliding, one per device session | The device stays logged in (sliding: each use resets the 30-day countdown, so an active device never expires while an idle one does); revocable server-side because it is looked up on every use |
| Channel grant (optional) | Duration of the subscription | Result of an authorization check, cached on the connection |
Rotation without reconnecting. At about 4 minutes, the client refreshes over HTTPS and sends an auth frame with the new access token on the open socket. The gateway verifies it and updates the connection's expiry. If no valid token arrives by expiry plus a short grace, the gateway closes the socket. Load: 5,000,000 connections refreshing every 240 s is 5,000,000 / 240, about 20,833 refreshes per second at the auth service, which is the dominant steady-state cost of short lifetimes and the number to size the auth service against.
Refresh-token rotation with reuse detection. Each refresh returns a new refresh token and invalidates the old one. If an old one is ever presented again, someone copied it: revoke that whole device session.
Device-level revocation
Each access token carries sid (the device session id), sub (user) and tid (tenant). The gateway indexes open connections by all three. "Log out my lost phone" = the auth service marks that session revoked (so its refresh token stops working) and publishes revoke {sid}. Every gateway looks up sid in its local index; the one holding it closes the connection with an application close code (RFC 6455, the WebSocket standard, reserves 4000-4999 for private application use; for example 4401 meaning "re-login required") so the client does not auto-reconnect in a loop. Time to effect: one bus hop plus a map lookup, typically well under a second, rather than waiting up to 5 minutes for the token to expire.
Instantaneous permission changes
Authentication says who you are; authorization says which channels you may read or write. Authorization is checked at subscribe time and the result is cached on the connection, because checking the policy service on every message at 50,000 connections per node would put the policy service on the hot path. When a permission changes (removed from a team channel), the auth or membership service publishes perm_changed {sub, channel}; gateways drop that subscription immediately and send the client an unsubscribed frame with a reason. Messages for that channel stop at the gateway on the next event.
For publishes (client-to-server messages), the gateway re-checks the cached grant per message, which is a local memory lookup, so a revoked writer is stopped at once.
Push vs token versioning: when each wins
| Push revocation | Token versioning | |
|---|---|---|
| Speed | Sub-second for connected devices | Takes effect at the next check (next refresh or re-auth, within 5 minutes) |
| Failure if message lost | Connection stays open until the token expires | Nothing to lose; state is pulled |
| Cost | One bus message per revocation, fan-out to all gateways | One lookup per re-auth (cacheable) |
| Mass revocation | Needs one message per session unless scoped | One write revokes everything below a version |
I use both: push for speed, versioning for correctness. A gateway that missed a push (restarting, partitioned from the bus, meaning a network split cut it off from the event bus so it could not receive the broadcast) still rejects the token at the next re-auth because its version is stale.
Revoking millions of active sessions quickly
Scenario: a signing key is suspected leaked, or a tenant's admin clicks "sign everyone out". Revoking 5,000,000 sessions one by one is 5,000,000 writes and 5,000,000 bus messages. Instead:
- One write: set
revoked_before = nowat the right scope (global, tenant, or user). For a leaked key, also rotate the signing key so tokens it signed fail signature verification everywhere. - One broadcast:
revoke_all {scope, revoked_before}to every gateway. - Local sweep: each gateway scans its 50,000 connections and marks those with token issued-at (
iat) older thanrevoked_before. - Paced close: close them in batches, for example 2,000 per second per node: 50,000 / 2,000 = 25 seconds to clear the fleet, all nodes in parallel. Stop delivering messages to marked connections immediately, even before the close, so the security effect is instant and only the socket teardown is paced.
- Prevent a reconnect storm into the auth service: 5,000,000 clients re-authenticating within 60 s is 5,000,000 / 60, about 83,333 logins per second. The close code tells clients to back off with jitter (wait a random extra amount of time before retrying, so reconnect attempts do not all land in the same instant) and, for a forced logout, to require a user sign-in rather than an automatic refresh, which naturally spreads the load over minutes.
Auditing at scale
- Log decisions, not traffic: connect, auth refresh, subscribe allowed or denied, permission change, revoke, forced close. Each event: timestamp,
sub,sid,tid, device, IP, channel, decision, reason, gateway id, correlation id. - Volume estimate: 5,000,000 sessions x 20 events per day x 300 bytes = 30 GB per day, which is ordinary for a log pipeline (a partitioned stream into object storage, queryable by tenant and user).
- Write to an append-only stream asynchronously from the gateway, so auditing never adds latency to the connection; buffer locally if the stream is slow, and alert if the buffer drops anything, because gaps in an audit log are themselves a finding.
Performance trade-offs
- Shorter access tokens mean faster natural expiry but more refresh load (20,833/s at 5 minutes; 1-minute tokens would be 5 times that).
- Local JWT verification keeps connect cheap; the price is that a token is valid until expiry unless push or versioning intervenes, which is why both exist.
- Per-message policy checks would be the most precise but put a network call on every message; cached grants plus change events give near-instant effect at memory-lookup cost.
Pitfalls
- Putting the token in the WebSocket URL query string leaks it into proxy and server logs; send it in the first frame or a subprotocol header (a field in the WebSocket handshake, such as
Sec-WebSocket-Protocol, that the client can use to pass a value without it appearing in the URL or default request logs), and keep the upgrade short. - Forgetting that revoking a refresh token does nothing to an already-open socket: the socket must be closed by push.
- Revoke events that fan out to one gateway per message do not scale; broadcast scoped events and let each gateway filter locally.
How would you design message retention and replay capabilities for a realtime platform where clients may disconnect for minutes or hours? Cover retention window sizing, storage tier choices across hot and cold storage, replay API design, access controls for replay, and cost and operational trade-offs.
Sample Answer
Direct answer
Size retention from how long clients actually stay away, not from a round number, and serve replay from tiers matched to how often each age of data is requested: a short in-memory buffer for the common few-second or few-minute reconnect, a durable hot log covering the tail of normal disconnects (I would start at 24 hours), and cheap object storage for older history that is fetched through a slower path. Replay is a cursor-based API (give me everything after cursor X) that returns an explicit "cursor expired, take a snapshot" answer when the client has been gone longer than the window, instead of silently skipping data. Access is checked at replay time against the client's membership history, so a user removed from a channel cannot replay what they are no longer entitled to. The main cost lever is the hot window: every extra hot hour costs replicated fast storage, while most clients only ever need the last few minutes.
Retention window sizing
- Measure the disconnect distribution. Log reconnect gaps (time between disconnect and resume). Typically most are seconds (network switches, tunnels), a smaller share are minutes to hours (phone backgrounded, laptop lid closed), and a long tail never resumes.
- Pick the hot window to cover a high percentile, for example the 99.9th percentile of gaps for clients that resume. Concretely, a typical distribution might show 90% of gaps resolving in under 10 seconds (a network blip), 99% under 5 minutes (the app was briefly backgrounded), and 99.9% under about 20 hours (a phone off overnight, or a laptop closed over a long commute), with a long tail beyond that which never reconnects at all; picking 24 hours as the hot window covers that 99.9th percentile with a little headroom. (These figures are illustrative, to show how the percentile choice turns into a window size; measure the real distribution for your product.) Clients beyond it get a snapshot plus recent history rather than a full replay, which is usually a better experience anyway (nobody wants to scroll through 30 hours of deltas).
- Size the bytes. Assumptions: 20,000 messages/s average across the platform, 600 bytes each.
- Per hour: 20,000 x 600 B x 3,600 s = 43.2 GB.
- 24-hour hot window: 43.2 x 24 = 1.04 TB, or 3.11 TB with three replicas.
- 90 days of cold history, compressed 4:1: 43.2 GB x 24 x 90 / 4 = 23.3 TB.
- Memory buffer for the last 5 minutes of the whole stream: 20,000 x 600 B x 300 s = 3.6 GB, spread across relay nodes.
Storage tiers
flowchart LR
LIVE[Live stream] --> MEM[Memory ring buffer, minutes]
LIVE --> HOT[[Replicated hot log, 24 h]]
HOT -- hourly segments --> COLD[(Object storage, 90 days)]
API[Replay API] --> MEM
API --> HOT
API --> COLD
API --> SNAP[Snapshot service]
| Tier | Holds | Serves | Why this tier |
|---|---|---|---|
| Memory ring buffer (a fixed-size buffer that, once full, overwrites its oldest entries with new ones, so memory use never grows) on relays | Last few minutes per channel | Most reconnects | Zero disk reads; reconnect storms (many clients reconnecting and replaying at once, for example after a regional outage) stay cheap |
| Hot log (replicated SSD, for example a partitioned log with time-based retention: the same append-only, ordered storage design as the live stream, but configured to auto-delete data older than the window) | 24 hours | Laptop-lid and backgrounded-app returns | Ordered reads by offset (each message's position number in the log, so "everything after offset 500" is a precise request), fast sequential scans |
| Object storage | 90 days, compressed segments (the log cut into hour-long chunks and compressed independently, rather than kept as one huge file) | History browsing, audit, compliance export | Cheapest per GB, but slower and priced per request |
| Snapshot service | Current state only | Anyone beyond the hot window | Bounded cost however long the client was away |
Cost, with assumed prices (plug in your provider's current rates): at $0.10 per GB-month for replicated fast storage, a 24-hour hot tier is 3,110 GB x $0.10 = about $311/month; stretching it to 7 days is 7 x 3,110 GB x $0.10 = about $2,177/month. At $0.02 per GB-month, 23.3 TB of cold history is about $467/month. So each extra hot day is roughly two-thirds of the entire 90-day cold archive's monthly cost; extend the hot window only if the measured gap distribution says clients need it.
Per-request cost is the other half of "priced per request." At roughly $0.0004 per 1,000 GET requests (a typical object-storage price order of magnitude; check your provider), one request per individual event during a reconnect storm of 20,000 events/s system-wide would cost about 20,000 x $0.0004 / 1,000 = $0.008/s, or roughly $29/hour, in request fees alone, on top of the storage cost above. Batching into hourly segments, one request returns an hour of history instead of one event, cuts that by roughly three orders of magnitude, which is why cold reads stay batched and never sit on the live reconnect path.
Replay API design
GET /v1/channels/{channel_id}/events?after={cursor}&limit=500
200 { "events": [...], "next_cursor": "c_8Hq...", "has_more": true }
410 { "error": "cursor_expired", "snapshot_url": "/v1/channels/{channel_id}/snapshot" }
- Opaque cursors (they encode partition and offset internally) so the storage layout can change without breaking clients.
- Paged and bounded:
limitcapped; the client loops untilhas_moreis false, then resumes live delivery from the last cursor on its WebSocket (a persistent two-way connection). Live events that overlap the replay are dropped by sequence number on the client. - Explicit expiry: HTTP 410 Gone with a snapshot link when the cursor is older than the retained window. Silently returning "the oldest we have" would create an invisible gap.
- Resume on connect: the socket handshake itself accepts
resume_from: cursor, so the common short reconnect needs no separate HTTP call; the server replays from memory and switches to live. - Tier routing is invisible: the API reads memory, then the hot log, and sends requests for old ranges to the cold tier with a lower rate limit.
Access controls for replay
- Authorize at replay time, not at original delivery. A user's rights may have changed while disconnected.
- Membership intervals: store when each user joined and left each channel; replay returns only events inside the intervals they were a member. A newly added member does not automatically get pre-join history unless the channel allows it; a removed member gets nothing after removal.
- Scoped tokens: replay tokens are bound to user and channel, short-lived, and rate-limited per user, so a stolen token cannot bulk-export history.
- Deletions and redactions must apply to every tier. Rewriting 90 days of cold segments per deletion request is costly; encrypting data with per-channel or per-user keys and destroying the key (crypto-shredding) makes deletion cheap.
- Audit cold-tier and bulk replays: who pulled which channel's history and when.
Operational trade-offs
- Reconnect storms: after a regional outage, millions of clients replay at once. Serve from memory where possible, jitter reconnects (have each client wait a small random extra delay before retrying, so they don't all hit at the exact same second), and move clients beyond a threshold straight to snapshots.
- Cold reads are slow and priced per request: batch history in hourly segments so one request returns many events, and never put cold reads on the live reconnect path.
- Retention changes are one-way: shortening the window is instant; lengthening it only helps future data.
- Monitor: replay requests by tier, share of reconnects that hit
cursor_expired, replay lag, and cold-tier request cost.
Pitfalls
- A single retention number for every channel: a busy public channel and a quiet private one have very different replay needs; set retention per channel class.
- Replaying deltas for hours when a snapshot is cheaper for both server and client.
- Checking permissions only when subscribing, which lets removed members replay.
Design and provide pseudocode for a server-side backpressure policy that, upon crossing a memory threshold, selectively drops, compresses, or aggregates messages per-client priority. The policy should preserve high-priority messages, emit metrics for dropped messages, and support graceful degradation. Explain rollout strategy and safety guards to avoid broad customer impact.
Sample Answer
Direct answer
I would make the policy a small, pure decision function of two inputs: the message's priority class and the current pressure level (for this client and for the whole node). High-priority messages are always kept; normal messages are compressed and coalesced (only the latest value per key survives) under soft pressure and dropped under hard pressure; low-priority messages are folded into a single "N updates skipped" summary. Every non-keep decision increments a labelled counter. The policy ships first in shadow mode (it decides and counts but does not act), then behind a percentage rollout, with a guard that switches it back to shadow automatically if it starts degrading too many clients at once.
Backpressure is what happens when a producer (here, the server fanning out messages) is faster than a consumer (a client on a slow phone network): unsent data queues up in server memory. Without a policy, one slow client can grow its queue until the process runs out of memory, which then disconnects every client on the node.
The policy
Priority classes (a contract with product teams)
| Class | Examples | Under soft pressure | Under hard pressure |
|---|---|---|---|
| High | chat messages, payment and order status, security events | keep | keep; if the client's queue still exceeds a last-resort cap, disconnect with a "resync" instruction |
| Normal | stock price ticks, typing indicators, score updates (state where the newest value replaces older ones) | compress and coalesce by key | drop, counted |
| Low | view counters, presence churn, analytics echoes | aggregate into one summary | aggregate into one summary |
The key design point is that "normal" means state-like: a newer tick for the same symbol makes the older one worthless, so coalescing loses nothing the user would see. High-priority messages are event-like (each one matters), so they are never dropped silently; the only escape valve is an honest disconnect that makes the client refetch.
Pressure levels
- ok: client's queued bytes below its soft limit and node total below the node soft limit.
- soft: client above its soft limit, or node above its soft limit (then every client degrades a little, which is fairer than evicting one).
- hard: client above its hard limit.
- last-resort cap: independent of the policy, a per-client ceiling that forces disconnect-and-resync. It exists today; the policy's job is to make it fire less often.
Pseudocode (runnable Python simulation)
The program below simulates 10 clients (8 fast, 2 slow) for 300 ticks with a 3x upstream burst between ticks 50 and 120. It runs the same seeded traffic three times: shadow mode, enforce mode, and enforce mode with an over-tight guard.
import random
from collections import Counter, deque
HIGH, NORMAL, LOW = "high", "normal", "low"
class Policy:
client_soft = 1_500 # bytes queued for one client before it degrades
client_hard = 3_000 # above this, normal traffic is shed too
client_kill = 20_000 # last-resort cap (exists with or without the policy)
node_soft = 12_000 # node-wide queued bytes: every client degrades above this
compress_ratio = 0.5 # modelled on deflate (the compression algorithm behind gzip/zlib), a rough ratio for a compressed normal payload
max_degraded_frac = 0.4 # guard: more degraded clients than this = suspect the policy
enforce = True # False = shadow mode: decide and count, never act
class Client:
def __init__(self, cid, drain_bytes):
self.cid, self.drain_bytes = cid, drain_bytes
self.q = {HIGH: deque(), NORMAL: deque(), LOW: deque()} # items: (key, bytes)
self.skipped = 0 # low messages folded into one "N updates skipped" summary
self.bytes = self.peak = 0
def level_for(c, node_bytes, p):
if c.bytes > p.client_hard: return "hard"
if c.bytes > p.client_soft or node_bytes > p.node_soft: return "soft"
return "ok"
def decide(prio, level):
if prio == HIGH or level == "ok": return "keep"
if prio == LOW: return "aggregate"
return "drop" if level == "hard" else "compress"
def offer(c, prio, key, n, level, act, p, m):
d = decide(prio, level)
if d != "keep":
m[f"{d}{{prio={prio},level={level}}}"] += 1 # counted in shadow AND enforce
if not act: d = "keep"
if d == "aggregate": c.skipped += 1; return
if d == "drop": return
q = c.q[prio]
if d == "compress": # coalesce: latest value per key wins
for item in [x for x in q if x[0] == key]:
q.remove(item); c.bytes -= item[1]
n = int(n * p.compress_ratio)
q.append((key, n)); c.bytes += n
def drain(c, m):
budget = c.drain_bytes
for prio in (HIGH, NORMAL, LOW): # strict priority order on the wire
q = c.q[prio]
while q and budget >= q[0][1]:
_, n = q.popleft(); budget -= n; c.bytes -= n; m[f"delivered_{prio}"] += 1
if c.skipped and budget >= 20:
m["summary_sent"] += 1; c.skipped = 0
def run(p, seed=42, ticks=300):
rng, m = random.Random(seed), Counter()
clients = [Client(i, 500) for i in range(8)] + [Client(8, 90), Client(9, 90)]
for t in range(ticks):
burst = 50 <= t < 120 # upstream burst: 3x traffic
node = sum(c.bytes for c in clients)
levels = [level_for(c, node, p) for c in clients]
frac = sum(l != "ok" for l in levels) / len(clients)
act = p.enforce and frac <= p.max_degraded_frac
if p.enforce and not act: m["guard_fell_back_to_shadow_ticks"] += 1
for c, lvl in zip(clients, levels):
for _ in range(rng.randint(2, 5) * (3 if burst else 1)):
r = rng.random()
prio = HIGH if r < 0.05 else NORMAL if r < 0.6 else LOW
offer(c, prio, f"k{rng.randint(0, 7)}", rng.randint(20, 60), lvl, act, p, m)
drain(c, m)
if c.bytes > p.client_kill: # cannot keep promises: force resync
m["disconnect_resync"] += 1
for q in c.q.values(): q.clear()
c.bytes = 0
c.peak = max(c.peak, c.bytes)
m["node_peak_bytes"] = max(m["node_peak_bytes"], sum(c.bytes for c in clients))
m["slow_client_peak_bytes"] = max(c.peak for c in clients[8:])
m["fast_client_peak_bytes"] = max(c.peak for c in clients[:8])
return m
for label, enforce, frac in (("SHADOW", False, 0.4), ("ENFORCE", True, 0.4), ("ENFORCE, guard at 10%", True, 0.1)):
p = Policy(); p.enforce = enforce; p.max_degraded_frac = frac
res = run(p)
print(label)
for k in sorted(res): print(f" {k} = {res[k]}")
Output of python3 bp.py:
SHADOW
aggregate{prio=low,level=hard} = 997
aggregate{prio=low,level=soft} = 3838
compress{prio=normal,level=soft} = 5288
delivered_high = 834
delivered_low = 4961
delivered_normal = 7690
disconnect_resync = 4
drop{prio=normal,level=hard} = 1351
fast_client_peak_bytes = 1069
node_peak_bytes = 38085
slow_client_peak_bytes = 19999
ENFORCE
aggregate{prio=low,level=soft} = 990
compress{prio=normal,level=soft} = 1362
delivered_high = 834
delivered_low = 5110
delivered_normal = 8026
fast_client_peak_bytes = 1069
node_peak_bytes = 5383
slow_client_peak_bytes = 2043
summary_sent = 186
ENFORCE, guard at 10%
aggregate{prio=low,level=hard} = 1037
aggregate{prio=low,level=soft} = 3722
compress{prio=normal,level=soft} = 5188
delivered_high = 834
delivered_low = 4965
delivered_normal = 7694
disconnect_resync = 3
drop{prio=normal,level=hard} = 1381
fast_client_peak_bytes = 1069
guard_fell_back_to_shadow_ticks = 269
node_peak_bytes = 38580
slow_client_peak_bytes = 19986
summary_sent = 5
Reading the code
Four pieces do different jobs. decide(prio, level) IS the policy: priority and pressure level in, one action out; everything else in the file exists to exercise it. level_for() turns a client's and the node's queued bytes into ok / soft / hard. offer() wraps decide for accounting: it always counts what the policy WOULD do first (so shadow and enforce log identically), then, only if act is true, actually applies it. drain() is not the policy either: it is the traffic model's delivery step, draining each client's queues in strict HIGH, NORMAL, LOW order up to a fixed per-tick byte budget. Inside run(), the two lines frac = sum(l != "ok" for l in levels) / len(clients) and act = p.enforce and frac <= p.max_degraded_frac ARE the blast-radius guard: frac is the fraction of clients currently degraded, and act turns off real enforcement for that tick if too many are degraded at once. Everything else inside the for t in range(ticks) loop, the rng.randint calls choosing how many messages, which priority, which key, is the synthetic traffic model, not the policy under test.
Reading the result
- Shadow reproduces today's behaviour (the policy only counts what it would do): the two slow clients reach 19,999 bytes, the node peaks at 38,085 bytes, and the last-resort cap disconnects slow clients 4 times. The counters tell you, before any user is affected, how much would have been dropped and in which class. Shadow's
if not act: d = "keep"line means nothing is ever actually shrunk here, so a client's queue keeps growing across ticks exactly as if no policy existed, and it lingers above the soft (and often hard) threshold for many ticks in a row, generating a decision on every offer made while it is there. - Enforce keeps the node peak at 5,383 bytes (about 7x lower) and the slow clients at 2,043 bytes, with zero disconnects. No normal message was dropped outright: the slow clients never reached the hard level, so the policy only compressed, coalesced and aggregated. All 834 high-priority messages were delivered in every run (834 were offered, which I checked by also counting offers). This is also why enforce records far fewer soft/hard-level decisions than shadow (990 + 1,362 = 2,352 versus shadow's 997 + 3,838 + 5,288 + 1,351 = 11,474): compression and aggregation immediately shrink
c.bytes, so a client crosses back under the soft threshold much sooner and stops generating decisions until it backs up again, and it is also why enforce never reaches the hard level at all (nodropor hard-levelaggregatein its output) while shadow does.
Why enforce delivers more normal messages than shadow despite compressing them (8,026 versus 7,690): two things compound. First, shadow's four last-resort disconnects each wipe a client's whole queue, discarding messages that would otherwise eventually have been delivered and counted; enforce has zero disconnects, so nothing is wiped. Second, a compressed message is half the size (compress_ratio = 0.5), so more of them fit through the same per-tick drain budget, which is fixed in bytes, not in message count.
- Guard at 10%: 2 of 10 clients are slow, so 20% degraded exceeds the 10% guard; the policy falls back to shadow on 269 of 300 ticks and the outcome looks like shadow again (3 disconnects). This is the guard doing its job, and the cost of setting it too tight.
The numbers are from a toy model (bytes, not real sockets, and a modelled 50% compression ratio); the point is the shape of the comparison, which is what a staging load test should confirm with real traffic.
Metrics the policy emits
backpressure_decisions_total{decision, priority, level}: counter for aggregate, compress and drop decisions, emitted in both modes so shadow data is comparable.backpressure_disconnects_total{reason}: last-resort resyncs.backpressure_guard_fallback_totaland a gaugebackpressure_degraded_client_fraction.- Per-node gauge of queued bytes and a histogram of per-client queue bytes (for choosing the limits).
- A per-client "you missed N updates" summary message, so the degradation is visible to the user and not only to the operator.
Keep label cardinality bounded (the number of distinct label-value combinations a metrics system tracks: each combination becomes its own stored time series, a series of timestamped values for one specific combination): never put a client ID in a metric label (millions of time series, since there are millions of distinct client IDs); put it in a sampled log line instead.
Rollout strategy and safety guards
- Shadow mode in production for a week. Decide and count, never act. Compare
decisions_totalby class against expectation; if "drop, normal" is non-zero on a node where no client is slow, the thresholds are wrong. - Dark launch (turn the new behavior on for real traffic without changing what users see, so you can observe it safely before it visibly matters) per priority class. Enable aggregation of low first (the least visible change), then compression and coalescing of normal, then normal drops last.
- Percentage rollout by hashing the tenant (a customer or account whose traffic is grouped separately) or connection ID into 1%, 10%, 50%, 100% cohorts (the separate buckets of traffic that get the new behavior at each rollout stage), one region at a time, with at least one full traffic peak between steps.
- Kill switch: a runtime flag (read on each decision, not at startup) that returns the node to shadow within seconds without a deploy.
- Blast-radius guard (shown in the code): if more than a set fraction of clients are degraded at once, the problem is probably the server or an upstream burst, not slow clients. Fall back to shadow, page someone (alert the on-call engineer immediately, not just log the incident), and rely on the last-resort cap.
- Priority is server-assigned. Clients or tenants must not be able to label their own traffic high, or the policy collapses under pressure.
- SLO (service-level objective) tie-in: gate each rollout step on the delivery-latency and message-loss SLOs not regressing for the cohort versus control.
Trade-offs and pitfalls
- Compression costs CPU exactly when the node is stressed. Only compress once a client is already at the soft level, and cap the CPU spent on it; if CPU is the bottleneck, skip straight to coalescing.
- Coalescing needs a key. Messages without a natural key (chat text) cannot be coalesced, which is why they are classed high and protected rather than normal.
- Node-level soft pressure degrades innocent clients. That is deliberate (fairness), but it must be short-lived; if the node is persistently above its soft limit, the fix is capacity, not policy.
- Dropping silently breaks client state. Every dropped or aggregated class must either be state the client can re-derive or be followed by a summary or a resync signal.
- Thresholds from a simulation are placeholders. Derive real limits from the shadow-mode histogram of per-client queue bytes (for example, soft at the 99th percentile, hard at a multiple of it).
Unlock Full Question Bank
Get access to all Real-Time and Streaming System Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.