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 WebRTC data channels and WebSocket for real-time peer-to-peer data synchronization use cases (e.g., multi-user collaborative whiteboard). Include signaling architecture, NAT traversal (STUN/TURN), expected throughput/latency differences, privacy/security trade-offs, and operational costs/complexity (TURN servers, scaling signaling). When would you choose one over the other?
Sample Answer
Direct answer
For a multi-user collaborative whiteboard I would use WebSocket (a persistent, two-way connection between browser and server that either side can push messages over at any time, unlike a normal request that closes after one reply) through a server as the backbone, because the server must persist the board, serve late joiners, enforce permissions and scale beyond a handful of users. I would add WebRTC data channels only for ephemeral, high-frequency data (live cursor positions) in small rooms, where peer-to-peer delivery and unordered, unreliable mode genuinely help. WebRTC is the right primary choice when rooms are small, latency matters more than persistence, and the data should not pass through your servers (for example, peer-to-peer file transfer or games).
The two technologies
- WebSocket: one long-lived TCP connection between the browser and your server, carrying messages both ways. Everything goes through the server.
- WebRTC data channel: a browser-to-browser channel. It runs on SCTP (a message-oriented transport) inside DTLS (TLS for UDP, so it is always encrypted) over UDP (User Datagram Protocol: packets are sent without any guarantee they arrive, arrive once, or arrive in order, unlike TCP, Transmission Control Protocol, the protocol under WebSocket, which guarantees all of that by resending anything lost, at the cost of waiting for it). Each channel can be reliable and ordered (like TCP) or configured unordered and with limited retransmits (
ordered: false,maxRetransmitsormaxPacketLifeTime), so a lost cursor packet is skipped instead of delaying newer ones.
Signaling architecture
WebRTC has no built-in way for two browsers to find each other. Signaling is the exchange of connection descriptions before the peer connection exists: an SDP offer and answer (Session Description Protocol: what each side supports) and ICE candidates (addresses at which each peer might be reachable). You build signaling yourself, and in practice it is usually a WebSocket server. So choosing WebRTC does not remove the WebSocket server; it adds a second system.
sequenceDiagram
participant A as Browser A
participant S as Signaling server (WebSocket)
participant B as Browser B
participant T as STUN / TURN
A->>T: STUN: what is my public address?
A->>S: SDP offer and ICE candidates
S->>B: forward offer and candidates
B->>S: SDP answer and ICE candidates
S->>A: forward answer and candidates
A-->>B: direct data channel if NAT allows
A-->>T: otherwise relay through TURN
NAT traversal: STUN and TURN
Most devices sit behind NAT (network address translation: a router shares one public IP among many private devices), so a peer's private address is unreachable from outside.
- STUN (Session Traversal Utilities for NAT): a lightweight server that tells a browser its public IP and port. Cheap: a few small packets per session.
- TURN (Traversal Using Relays around NAT): when a direct path is impossible (symmetric NATs, a NAT type that hands out a different public port for every destination a device talks to, so the address a peer discovers via STUN for one connection cannot be reused for another; or strict corporate firewalls), a TURN server relays all the traffic. At that point the connection is no longer peer-to-peer, and you pay for the egress (the cost of data leaving your servers to the internet, billed per GB by most cloud and hosting providers).
- ICE (Interactive Connectivity Establishment) is the procedure that tries direct candidates first and falls back to TURN.
Throughput and latency
- Latency: peer-to-peer saves the server hop only when the peers are close to each other and far from the server. Two colleagues in one office with a server on another continent gain a lot; two users in different countries with a nearby server region gain little. Relayed (TURN) paths add a hop comparable to the WebSocket path.
- Head-of-line blocking: TCP delivers bytes in order, so one lost packet stalls every message behind it until it is retransmitted. An unordered, unreliable data channel avoids that, which is the real advantage for streams where only the newest value matters (cursors).
- Throughput: in a mesh (every peer connected to every other), each peer uploads its data once per other peer, so upload grows with room size; with WebSocket each client uploads once and the server fans out.
- Connection setup: WebSocket is ready after one TCP and TLS handshake; WebRTC needs signaling plus ICE checks, typically noticeably longer, which matters for short sessions.
Privacy and security trade-offs
| Concern | WebSocket via server | WebRTC data channel |
|---|---|---|
| Encryption in transit | TLS (wss://) to the server; server sees plaintext | DTLS mandatory; peers see plaintext, a TURN relay only sees encrypted packets |
| IP address exposure | Peers see only the server | ICE candidates reveal each peer's IP addresses to the other peers; mitigate with iceTransportPolicy: "relay" (TURN only) at the cost of relay bandwidth |
| Authorization and moderation | Server checks every message against permissions | Server is out of the data path: a malicious peer can send anything; each client must validate |
| Persistence, audit, late join | Natural: server stores the operations | Needs a separate path to a server anyway |
Operational cost and complexity
- TURN servers are bandwidth-heavy relays you must run or buy, in several regions, with credentials that expire (short-lived TURN credentials, so a leaked one cannot be reused as a free relay). Their cost is dominated by egress.
- Scaling signaling is a WebSocket fan-out problem you have anyway.
- Debugging WebRTC connectivity failures (which NAT, which candidate failed) is significantly harder than debugging a WebSocket.
- WebSocket at scale costs connection-holding servers and egress for fan-out, both familiar and well-tooled.
Worked example: a 10-person whiteboard
Cursor updates at 30 per second, 40 bytes each.
- WebSocket: each client uploads 30 x 40 = 1,200 bytes/s; the server sends each update to the other 9 users: 10 x 30 x 9 x 40 = 108,000 bytes/s of server egress per room (about 0.86 Mbit/s).
- WebRTC mesh: 10 x 9 / 2 = 45 peer connections per room; each peer uploads 30 x 9 x 40 = 10,800 bytes/s, nine times the WebSocket upload. Fine for 10 people on broadband; at 30 people it becomes 435 connections and 29x upload per peer, which is why meshes stop scaling around small rooms and larger rooms use a server relay (an SFU, selective forwarding unit: a server that receives each peer's stream once and forwards, i.e. selectively relays, a copy to every other peer without decoding or mixing it, so upload no longer grows with room size) anyway.
- If some sessions need TURN, each relayed peer's traffic passes through your TURN server, so its cost scales with the relayed fraction times the mesh traffic. As an illustrative order of magnitude (not a benchmark): production WebRTC deployments commonly report something like one session in five to one in four falling back to TURN, but the real fraction depends heavily on your users' networks, corporate firewalls and mobile carriers. Measure that fraction from ICE statistics in your own user base rather than assuming it.
The drawing strokes themselves (which must persist and be seen by late joiners) go over WebSocket in both designs.
When to choose which
- WebSocket: persistent shared state, more than a few participants, need for authorization, moderation, history or server-side integrations; users behind strict networks.
- WebRTC data channels: small rooms, latency-critical or bulky data between peers (games, file transfer, cursor streams), data you do not want on your servers, or an app already using WebRTC for audio and video.
Trade-offs and pitfalls
- "Peer-to-peer is free" is false once TURN relays and signaling are counted.
- Using WebRTC for the authoritative board state forces you to reinvent ordering and persistence, and a single malicious peer can corrupt others' state.
- Forgetting that ICE candidates leak IP addresses is a real privacy issue in apps with strangers in the same room.
- WebTransport (a newer browser API over HTTP/3 with unreliable datagrams to a server) addresses head-of-line blocking without peer-to-peer; worth evaluating where browser support fits your audience.
You're designing the security posture for a WebSocket/SSE-based realtime platform that accepts connections from third-party clients as well as your own apps. A persistent, bidirectional channel introduces risks a typical stateless API does not. Identify the primary risks such a channel is exposed to, and for each, propose concrete mitigations and explain how you would implement them across the edge, application, and broker layers.
Sample Answer
Direct answer
A persistent channel breaks three assumptions a stateless API relies on: authentication happens once but the connection lives for hours, each connection pins memory and a socket on your servers, and one connection can carry thousands of messages across many channels without any further per-request checks at the edge. So the primary risks are hijacked or stale sessions, resource exhaustion, broken per-message authorization, and abuse that gets amplified by fan-out (one message published once but delivered out to every subscriber of a channel). My posture: short-lived connection tickets with an Origin allowlist at the handshake, hard per-connection and per-principal (the authenticated user or client behind a connection) budgets at the edge, authorization on every subscribe and publish in the application layer, and a broker that is never reachable from outside and enforces its own channel ACLs (access control lists: rules naming exactly which channels each authenticated identity may read or write).
Terms used below: a WebSocket is a long-lived two-way connection that starts as an HTTP request and is "upgraded"; SSE (Server-Sent Events) is a long-lived one-way HTTP response the server streams events down. The edge is your load balancers, WAF (web application firewall) and gateway proxies; the application is the connection servers that hold sockets; the broker is the pub/sub system (Redis, Kafka, NATS or similar) that moves messages between servers.
Why this differs from a REST API
| Property | Stateless API | Persistent channel |
|---|---|---|
| When auth is checked | Every request | Usually once, at the handshake |
| Cost of one client | One short request | A socket, buffers and a subscription set for hours |
| What the edge sees | Every request, inspectable | One upgrade request, then opaque frames |
| Browser protections | CORS (cross-origin resource sharing) preflight on cross-site calls | No preflight on a WebSocket upgrade, and cookies are sent with it |
| Blast of one message | One response | Fan-out to every subscriber of the channel |
Every risk below comes from one of these rows.
The risks and their mitigations
1. Cross-site WebSocket hijacking (CSWSH)
What goes wrong. A malicious page in the victim's browser opens wss://realtime.example.com/ws. The browser attaches the victim's cookies to that upgrade and does not apply a CORS preflight, so if you authenticate by cookie alone the attacker's page now holds a live, authenticated channel and can read the victim's stream.
- Edge: reject upgrades whose
Originheader is not on an allowlist of your own web origins. (Third-party native clients send no browser Origin; they go through the ticket path below, not cookies.) - Application: do not authenticate WebSockets by cookie alone. The client first calls an authenticated HTTPS endpoint (
POST /realtime/ticket) and receives a ticket: a random, single-use value valid for about 30 seconds, bound to the user and, for third parties, to their OAuth client ID (the identifier and secret a third-party service authenticates itself with, standing in for a human login). The upgrade presents the ticket; the server redeems and deletes it. - Broker: nothing specific, but the identity the application attaches to the connection is what the broker ACLs below key on.
2. Credentials that outlive their validity
What goes wrong. A token checked at the handshake expires in 15 minutes, the user is suspended, or a third-party app's access is revoked, and the socket keeps streaming for another 6 hours.
- Edge: a maximum connection lifetime (for example 24 hours) so no socket is immortal; clients reconnect with backoff and jitter.
- Application: record the credential's expiry on the connection. Before expiry the client sends a fresh token over the channel (an in-band re-auth message) or the server closes with an application close code meaning "re-authenticate". Subscribe to a revocation topic so a suspension or token revocation closes that principal's sockets within seconds.
- Token placement: browsers cannot set an
Authorizationheader on a WebSocket upgrade, so tokens end up in the URL query string, which lands in access logs and proxies. The single-use short ticket is the fix: a ticket leaked into a log is already spent.
3. Broken authorization on subscribe and publish
What goes wrong. The handshake proved who the user is, but the client then sends {"op":"subscribe","channel":"tenant-42.orders"} with someone else's tenant ID. This is an IDOR (insecure direct object reference): guessing a name gets you data.
- Application: authorize every subscribe and every publish against the principal, not just the handshake. Derive the tenant from the authenticated identity; never trust a tenant or user ID the client puts in the message. Stamp the sender ID server-side on every outbound message so clients cannot spoof authorship.
- Third-party clients: map OAuth scopes (the specific permissions baked into that client's token, narrower than everything it could ever do) to channel patterns (a partner token scoped
orders:readmay subscribe totenant-42.orders.*and publish nowhere). - Broker: the connection servers authenticate to the broker with their own credentials, and the broker restricts which channel patterns each service may use (Redis ACLs support channel patterns, Kafka has per-topic ACLs, RabbitMQ has per-virtual-host permissions, a virtual host being an isolated namespace inside one RabbitMQ broker with its own queues and permissions). That is defence in depth (a second, independent layer of protection, so one failure is not the only thing standing between an attacker and the data): a bug in the application check does not open every channel.
4. Resource exhaustion (denial of service)
What goes wrong. Connections are cheap for an attacker and expensive for you. Variants: opening hundreds of thousands of idle sockets, completing the TCP handshake and then sending the upgrade one byte at a time (slowloris), sending one enormous frame, sending a compressed frame that inflates to gigabytes, or subscribing and never reading so your outbound queue for that socket grows without bound.
- Edge: per-IP and per-principal connection caps; a handshake timeout of a few seconds; an idle timeout paired with application heartbeats; WAF rules and rate limits on the ticket endpoint.
- Application: a maximum frame and message size (for example 64 KiB); if you enable the
permessage-deflatecompression extension, cap the decompressed size too; a per-connection token bucket (a small budget of message credits that refills at a steady rate; each inbound message spends one credit, and a client sending faster than the refill rate gets throttled) on inbound messages; a bounded outbound queue per connection (backpressure: when a client cannot keep up, drop or disconnect it instead of buffering forever). - Broker: per-client output buffer limits (Redis disconnects a pub/sub subscriber that exceeds its
client-output-buffer-limit), and quotas per producer.
5. Fan-out amplification
What goes wrong. Publishing is where one message becomes many. Worked example: a public channel has 50,000 subscribers and a client may publish 20 messages per second. One abusive client then generates
20×50,000=1,000,000 deliveries per secondfrom a single socket.
- Application: separate permissions for publishing into large channels; per-channel publish rate limits in addition to per-connection limits; for broadcast channels, only a server-side producer may publish.
- Broker: quotas on the publishing service identity, so a compromised application node cannot flood every topic.
6. Malicious payload content
What goes wrong. Real-time payloads flow straight into other users' screens. An unvalidated chat message containing HTML is stored cross-site scripting (XSS: an attacker's script gets saved server-side and later runs in the browser of anyone who views it) delivered live instead of loaded from a page.
- Application: validate every inbound message against a schema (types, lengths, allowed fields); reject unknown operations; encode on render in clients (convert characters like
<and>into safe text equivalents right before displaying user content, so it can never execute as script). Treat third-party client payloads as untrusted to the same degree as a public form.
7. Transport-level exposure
- Edge:
wss://andhttps://only, with modern TLS (Transport Layer Security). Terminate TLS where you can apply the checks above. - Compression side channel: compressing attacker-influenced text together with a secret in the same compression context can leak the secret through message sizes (the CRIME and BREACH class of attacks). The mechanism: compression shrinks repeated substrings, so if an attacker can get their own guesses compressed in the same stream as a secret (say a token echoed back in a message) and watch the resulting size, a guess that overlaps the real secret compresses a few bytes smaller than a wrong one, letting the attacker recover the secret one character at a time by trying all possibilities and keeping whichever shrinks the output. Do not put secrets in compressed frames, or disable
permessage-deflatecontext takeover (the compressor reusing its dictionary of earlier bytes across separate messages on the same connection, which is exactly what lets old traffic influence a new message's compressed size) on channels that carry them. - Internal hops: mTLS (mutual TLS, where both sides present certificates) between connection servers and the broker; the broker lives on a private network with no public listener.
Worked example: the handshake as implemented
sequenceDiagram
participant C as Client
participant E as Edge proxy
participant A as Auth API
participant G as Connection server
participant B as Broker
C->>A: POST /realtime/ticket (bearer token)
A-->>C: ticket (single use, 30 s)
C->>E: GET /ws?ticket=... Upgrade websocket
E->>E: Origin allowlist, per-IP cap, handshake timeout
E->>G: forward upgrade
G->>A: redeem ticket (atomic delete)
A-->>G: user, tenant, scopes, token expiry
G-->>C: 101 Switching Protocols
C->>G: subscribe tenant-42.orders
G->>G: authorize against scopes
G->>B: subscribe (service credentials, channel ACL)
Budgets I would start with and then tune from production telemetry: 20 connections per user, 1,000 per source IP (offices behind NAT, network address translation, share one public IP), 64 KiB maximum message, 20 inbound messages per second with a burst of 40, a 256 KiB outbound queue per socket before the slow client is disconnected, and 24-hour maximum connection lifetime.
Trade-offs and pitfalls
- Checking auth only at the handshake is the most common real defect. The fix is not heavier handshakes; it is carrying expiry and revocation into the connection's lifetime.
- Per-message authorization costs CPU. Cache the principal's permitted channel patterns on the connection and invalidate on the revocation topic, rather than calling the auth service per message.
- Origin checks do not protect non-browser clients and are trivially forged by them. They exist to stop a victim's browser being used against them, which is why third parties use tickets, not cookies.
- Aggressive limits hurt legitimate reconnect storms. After a deploy, 100,000 clients reconnect in a minute; per-IP limits tuned for steady state will reject corporate NAT users. Size limits for the storm, and let jittered backoff smooth it.
- Logging: log connection open and close, auth decisions and limit hits with the principal ID, never the ticket or token value.
Design an architecture to handle 10 million concurrent persistent connections globally across multiple regions, supporting failover, low latency, and broadcasting messages to any subset of users, with regional latency SLOs under 500ms. Discuss regional affinity, global routing (GeoDNS/GSLB), sticky-session implications, edge proxies, how connection state is stored, consistency of presence state, cross-region replication of pub/sub metadata, and failover design.
Sample Answer
Direct answer
I would run the same stateless connection tier in four regions, route each client to its nearest healthy region with latency-based DNS or anycast, and treat every connection as disposable: any gateway in any region can accept any user, and a reconnect resumes from a durable per-user sequence number rather than from server memory. Within a region, a registry maps each user to the gateway holding their socket, and a regional pub/sub bus moves messages between gateways. Across regions, only coarse metadata replicates (which regions have subscribers for which channels, and presence deltas), so a regional publish crosses the ocean only when someone over there is listening. Each region is sized so the other three can absorb it if it fails.
Terms: GeoDNS answers a DNS query with an address chosen by the client's location; GSLB (global server load balancing) is the same idea plus health checks, so a dead region stops being handed out; anycast advertises one IP address from many locations and lets internet routing deliver packets to the nearest. Presence is the "who is online" state. Pub/sub (publish/subscribe) is messaging where senders publish to a named channel and every subscriber receives a copy.
Requirements and numbers
- 10 million concurrent persistent connections (WebSocket), global.
- 1 billion messages per day, delivered to arbitrary subsets of users.
- Regional latency SLO (service-level objective): sender to recipient in the same region under 500 ms.
- Survive the loss of a whole region.
With four regions, each carries 2.5 million connections normally. If one region fails, the other three must hold 10 million / 3, about 3.33 million each. At an assumed 100,000 connections per gateway (a sizing to validate by load test), that is 34 gateways per region, 136 in total, against 100 needed with no failure headroom.
Architecture
flowchart TB
U[Clients] --> D[GeoDNS or anycast GSLB]
D --> EA[Region A edge TCP load balancer]
D --> EB[Region B edge TCP load balancer]
EA --> GA[Gateways A]
EB --> GB[Gateways B]
GA --> RA[(Registry and presence A)]
GA --> BA[Regional pub/sub A]
GB --> BB[Regional pub/sub B]
BA <-->|interest-filtered bridge| BB
GA --> S[(Durable message store)]
GB --> S
Each design question
Regional affinity
A client connects to its nearest region and stays there for the life of the socket. Affinity is a performance preference, not a correctness requirement: nothing breaks if a user in Paris lands in Virginia after a failover; they just pay more latency. User data can still have a home region for storage, but the connection tier does not depend on it.
Global routing (GeoDNS / GSLB)
- Latency-based or geo DNS with health checks and a short TTL (time-to-live), such as 30 to 60 seconds. DNS failover is only as fast as clients honour the TTL, and some ignore it, so it is the coarse layer.
- Anycast in front of it (a managed anycast entry point a cloud provider runs for you, often marketed as a "global accelerator", or your own anycast edge) moves traffic off a dead region at the routing layer within seconds, without waiting for DNS caches.
- Recommendation: anycast entry points if the platform offers them, with GeoDNS as the fallback control. Either way, a failover means existing sockets break and clients reconnect, so the reconnect path (below) is the real failover mechanism.
Sticky-session implications
A WebSocket is inherently sticky: the TCP connection stays on one gateway until it closes. The question is whether a reconnect must return to the same gateway. My answer is no. If reconnects needed the same server, a gateway crash would strand its users and rolling deploys would need cookie routing. Instead, state needed to resume lives outside the gateway: the client sends last_seq on reconnect and the new gateway replays from the durable store. So the edge load balancer can be a plain L4 (TCP-level) balancer with no session affinity.
Edge proxies
L4 load balancers per region pass TCP through; TLS terminates on the gateways (or on a thin TLS-terminating proxy tier if you want certificate handling off the gateways). Two reasons to prefer L4: an L7 proxy (one that reads and understands the HTTP or WebSocket framing itself rather than just passing bytes through, the way the L4 balancer above does) terminating 10 million sockets doubles the socket count (one client side, one backend side), and every proxy restart would drop connections. Edge proxies do enforce the cheap protections: per-IP connection caps, handshake timeouts and idle timeouts aligned with application heartbeats (for example 30-second pings under a 60-second idle timeout).
How connection state is stored
- In gateway memory (ephemeral): the socket, its outbound queue, its subscription list. Lost on crash, by design.
- Regional registry (Redis or similar, replicated within the region):
user_id -> {gateway_id, connection_id}with a TTL refreshed by heartbeat, andchannel -> set of gateways with subscribers. Used to route a message to the right gateway. - Durable store (replicated database or log): per-user or per-conversation sequenced messages for replay on reconnect.
Sending to "any subset of users": for a list of user IDs, look the users up in the registry, group them by gateway, and send one batch per gateway. For channel-based audiences, publish once to the channel and let only gateways with subscribers receive it.
Consistency of presence state
Presence is eventually consistent, and I would say so explicitly in the design review. Per region, presence is a set of live connection IDs per user with a heartbeat TTL (for example 60 seconds). Across regions, each region publishes presence deltas asynchronously, and a user is "online" if any region holds a live connection for them. Modelling it as a set of connection IDs (rather than a single online/offline flag) means two regions changing it concurrently cannot overwrite each other: each region only ever adds its own connection IDs to the set or removes them, it never replaces the whole value, so merging two regions' updates is just a union of adds and removes and lands on the same result no matter what order the updates arrive in. A single online/offline flag has no such property: if region A's copy flips to offline at the same moment region B's copy flips to online, whichever write is applied last wins and silently erases the other. Concretely: a user on a phone in region A and a laptop in region B shows online until both sets are empty. Staleness of a few seconds is acceptable for presence; strong global consistency would cost cross-region round trips on every status change, for no user-visible benefit.
Cross-region replication of pub/sub metadata
Replicate interest, not messages: each region advertises the channels it has at least one subscriber for. When region A publishes to a channel, it forwards to region B only if B has declared interest. Interest changes rarely (when the first subscriber in a region joins or the last leaves), so this is low volume. Message payloads that must be durable go to the durable store, which has its own replication; the live cross-region bridge is best-effort, and the reconnect replay covers anything the bridge drops.
Latency budget for the 500 ms SLO
These are allocations to design against, not measurements:
| Hop | Budget |
|---|---|
| Sender to gateway (in-region network plus the TLS encryption overhead on an already-open connection, not a new handshake) | 50 ms |
| Gateway validation, auth check, sequencing write (writing the message to the durable store with its per-user sequence number, the state a later reconnect resumes from) | 50 ms |
| Registry lookup and regional pub/sub hop | 50 ms |
| Recipient gateway queue and send | 50 ms |
| Gateway to recipient network | 50 ms |
| Reserve for p99 (99th percentile) tail and GC (garbage collection) pauses, the stop-the-world moments a managed-memory runtime spends reclaiming memory | 250 ms |
Cross-region delivery adds the inter-region one-way latency, which is why the SLO is stated as regional.
Failover design
When region A dies, its 2.5 million clients disconnect together. Routing moves them elsewhere, and they reconnect with exponential backoff and jitter:
spread over 60 sspread over 120 s:2,500,000/60≈41,667 new connections per second:2,500,000/120≈20,833 new connections per secondAcross three surviving regions at 120 seconds, that is about 6,944 TLS handshakes per second per region, about 204 per gateway across 34 gateways. The design pieces: pre-provisioned headroom (the 3.33 million per region sizing), admission control (the gateway itself refusing new connections once it is at capacity, with a hint to retry later, instead of accepting every attempt and failing under load) that rejects with a retry hint when a gateway is above its handshake rate, and clients that resume from last_seq so no message is lost, only delayed.
Trade-offs and pitfalls
- What would change the design: if messages mostly go to one huge audience (a live event) the problem becomes broadcast fan-out and a hierarchical relay tree (a small number of relay nodes each fanning out to many more below them, the way a CDN distributes one piece of content, instead of one origin sending to every one of millions of users directly) beats per-user routing; if data residency requires EU users to stay in the EU, regional affinity becomes a hard rule and failover must stay inside the jurisdiction.
- Global strongly consistent presence is the classic over-build. Nobody notices a friend's dot turning green two seconds late.
- Sizing only for steady state is the classic under-build. The reconnect storm after a region loss is the peak you must survive.
- Replicating every message to every region multiplies cross-region egress (traffic leaving a region outbound, the direction cloud providers usually charge for) by the region count for messages nobody there wants. Filter by interest.
What metrics, logs, and traces would you instrument to monitor a realtime streaming platform (WebSocket frontends, message broker, consumers)? Include per-connection metrics, message latency percentiles, backpressure indicators, reconnection rates, auth failures, and queue depths. Propose SLOs, alerting rules, and runbook actions for the common failure modes, and describe how you'd present this in dashboards for an on-call team.
Sample Answer
Direct answer
Instrument each tier (WebSocket gateways, message broker, consumers) with aggregate metrics for health and SLOs (service-level objectives), structured logs for per-connection events such as connects, disconnects and auth failures, and distributed traces for a sample of messages end to end. Never label metrics per connection (a label is a key-value tag attached to a metric, for example connection_id=abc123, and every distinct combination of label values becomes its own stored time series, a separately tracked history of one metric over time): with a million connections that creates millions of time series. Define two user-facing SLOs (connection success and end-to-end delivery latency), alert on error-budget burn rate rather than raw thresholds, back each common failure mode with a runbook, and lay out dashboards top-down from SLO status to per-tier detail.
Terms
- WebSocket: a long-lived two-way connection between browser or app and server, upgraded from an HTTP request.
- Backpressure: a slow receiver forcing the sender to buffer, slow down or drop. In this system it shows up as growing send buffers on gateways and growing lag in the broker.
- Consumer lag / queue depth: how many messages are waiting in the broker for a consumer that has not processed them yet.
- SLI / SLO: an SLI (service-level indicator) is the measured quantity (for example "share of messages delivered within 1 s"); the SLO is the target for it over a window (99% over 30 days). The error budget is what the SLO allows to fail (1%).
- p50/p95/p99: 50th, 95th and 99th percentiles.
Pipeline and where to measure
flowchart LR
PUB[Publisher service] -->|stamp publish time| BRK[(Message broker)]
BRK --> CON[Consumers: route and fan-out]
CON --> GW[WebSocket gateways]
GW --> CL[Clients: sampled delivery acks]
GW -.-> MET[Metrics, logs, traces]
CON -.-> MET
BRK -.-> MET
What to instrument
Gateways: per-connection metrics, aggregated
Record per-connection facts into histograms and counters per node (a histogram buckets the observed values so percentiles like p99 can be computed from the distribution later; a counter only ever increases, such as a running total; a gauge, used just below, is a value that can go up or down, such as how many connections are open right now), not per-connection series:
- open connections (gauge) and connection age (histogram);
- connect attempts, successes, failures by reason (handshake error, auth failure, rate-limited);
- reconnection rate: connects from a client that disconnected within the last N minutes (the client sends a reconnect flag and attempt count);
- disconnects by close code: 1000 normal, 1001 going away, 1006 abnormal (no close frame, the WebSocket message that cleanly announces "this connection is ending"; its absence usually means a network drop), 1008 policy violation, 1011 server error;
- auth failures by reason: expired token, bad signature, revoked;
- backpressure indicators: per-connection send-buffer bytes (histogram), messages dropped or coalesced for slow clients, slow-client disconnects;
- node resources: file descriptors (OS-level handles a process holds open, one per socket; running out blocks new connections), memory, event-loop lag (how far behind a single-threaded server's task queue is running, a sign the process cannot keep up) or scheduler delay, CPU.
Broker and consumers
- queue depth / consumer lag per topic (a named stream of messages in the broker) and partition (one ordered, independently consumed slice of a topic), and its rate of change;
- publish rate, consume rate, publish errors;
- consumer processing time (histogram), retries, dead-letter count (a DLQ, dead-letter queue, holds messages that repeatedly failed).
Message latency percentiles
The publisher stamps a publish timestamp into each message. Gateways record publish-to-send latency in a histogram. For the true end-to-end figure, a sample of clients (say 1%) acknowledges receipt and the gateway records publish-to-ack. Report p50, p95 and p99 from the histograms, never averages of percentiles across nodes.
Logs and traces
- Logs: one structured line per connect and disconnect (connection id, user id hash, node, close code, duration, reason), and per auth failure. This is where per-connection detail lives, queryable when needed without costing a time series each.
- Traces: propagate trace context in message headers from publisher through broker, consumer and gateway, sampled (for example 0.1% plus every message slower than the p99 threshold), so a slow message can be followed hop by hop.
Why not per-connection metrics: the arithmetic
1,000,000 connections × 3 metrics each = 3,000,000 time series, most of them churning as clients reconnect. A time-series database would struggle, and the dashboards would be unreadable anyway. Histograms per node give the same distribution at a few hundred series.
SLOs and alerting
| SLO | SLI | Target (30 days) |
|---|---|---|
| Connection availability | successful connects ÷ attempts (excluding client-side auth errors) | 99.9% |
| Delivery latency | sampled messages acknowledged within 1 s ÷ sampled messages | 99% |
Burn-rate alerting pages when the error budget is being consumed too fast, instead of on any spike. Burn rate is how many times faster than "exactly on budget" you are failing:
burn rate=1−SLOobserved error rateThe thresholds below are not arbitrary: they are solved backward from a policy decision. Decide how much of the 30-day budget a page is allowed to cost (2% within an hour) and how long you are willing to wait to detect that rate, then burn rate = target share ÷ (window ÷ total budget window). Over a 30-day window (720 hours):
- Page when burn rate exceeds 14.4 over both the last 1 hour and the last 5 minutes: solving 2% ÷ (1 h ÷ 720 h) gives 14.4, and 14.4 × 1 h ÷ 720 h = 2% of the monthly budget already gone in an hour.
- Ticket when it exceeds 6 over 6 hours: solving 5% ÷ (6 h ÷ 720 h) gives 6, and 6 × 6 ÷ 720 = 5% of the budget.
The page rule needs both windows to breach together. The long window (1 hour) confirms the failure rate is high enough to matter; the short window (5 minutes) confirms the problem is still happening right now. A long window alone would keep paging for hours after a fix ships, because the bad period is still being averaged in; a short window alone would page on a brief blip that self-resolves before anyone looks. Requiring both is what stops the page from firing long after recovery. The ticket rule uses a single 6-hour window instead of a paired one, because a ticket is not urgent enough to need that same speed of recovery detection. Add cause alerts that do not page but warn: consumer lag growing for 10 minutes, a node above 80% of its file-descriptor limit, send-buffer p99 rising.
Runbooks for the common failure modes
| Failure mode | Signals | Runbook actions |
|---|---|---|
| Reconnect storm after a node or load balancer failure | connects/s spike, 1006 disconnects, CPU on survivors | Confirm clients use jittered exponential backoff (after a failed connect, wait longer on each retry, with a random jitter added so many clients do not retry in lockstep); enable connect-rate limiting at the edge; add capacity before resuming drains. Example: 50,000 clients from one node, reconnecting with random jitter over 30 s, is about 1,667 connects/s spread across the remaining nodes; without jitter it arrives in about one second. |
| Broker lag growing | consumer lag slope positive, delivery latency SLI dropping | Check for a hot partition (one key receiving most traffic); scale consumers up to the partition count; look for a slow downstream dependency in consumer traces |
| Slow clients / backpressure | send-buffer p99 up, drops up, memory up | Enforce per-connection buffer caps; for state-like streams send only the latest value; disconnect persistent laggards with close code 1013 (try again later) |
| Auth failure spike | auth failures by reason | Expired or rotated signing key, identity provider outage, clock skew; roll back the key rotation or extend acceptance of the previous key |
| Gateway memory or file descriptors exhausted | fd usage, memory, event-loop lag | Drain the node gracefully (tell clients to reconnect elsewhere, staggered), then investigate leaks |
Dashboards for on-call
- Top row: SLO status. Current SLIs, error budget remaining, burn rate, with deploy annotations.
- Traffic: open connections, connects/s, reconnect rate, disconnects by close code, messages/s in and out.
- Latency: delivery p50/p95/p99, by region.
- Backpressure and queues: consumer lag by topic, send-buffer distribution, drops.
- Per-node table (sortable): connections, CPU, memory, fds, event-loop lag, to find the one bad node.
- Auth: failures by reason.
Every panel links to the matching logs query and runbook, so on-call moves from "what is red" to "what do I do" in one click.
Pitfalls
- Averaging p99 across nodes (mathematically meaningless: a percentile is a position in a sorted set of values, not a quantity that averages linearly, so the mean of several nodes' p99s is not the p99 of their combined traffic, and can be badly wrong when nodes carry uneven load); aggregate histograms, then compute one percentile over the combined data.
- Measuring latency only up to the broker: most delay in real incidents hides in fan-out (one broker message being delivered out to many gateway connections at once) and slow clients.
- Alerting on open-connection count dropping, which also happens at night and during graceful deploys.
Design how to guarantee message ordering within a chat conversation while accepting at-least-once delivery semantics from the underlying broker. Detail client and server-side strategies including sequence numbers, per-conversation partitions, buffering and reordering on clients, dealing with gaps, and reconciling messages after reconnect. Explain trade-offs between user-visible latency and ordering guarantees.
Sample Answer
Direct answer
Let the server, not the network, define the order: a single sequencer per conversation assigns gap-free sequence numbers (1, 2, 3, ...) when it durably stores each message, and the broker is partitioned by conversation ID so one conversation's messages flow through one ordered lane. Because the broker is at-least-once (it retries until acknowledged, so it can deliver a message twice), the client treats sequence numbers as the truth: it drops anything it has already shown, holds messages that arrive early in a small reorder buffer, and after a short timer fetches any missing range from the server. On reconnect the client sends the last sequence it saw contiguously and the server replays everything after it. The trade-off is a small hold-back delay whenever a gap appears; I would tolerate a few hundred milliseconds before fetching, never hold the screen hostage, and show the sender's own message instantly as "pending".
Why the broker's order is not enough
- At-least-once means redelivery after a lost acknowledgement. The redelivered copy can arrive after newer messages.
- Several server instances publishing for one conversation can interleave.
- A client that reconnects to a different server gets live messages and replayed messages over two paths at once.
So ordering has to be a property of the data (a sequence number), checked at the edge, not a hope about the pipe.
Server-side strategies
- Assign seq at write time. One writer per conversation increments
last_seqand stores the message in the same atomic step (a database transaction, or, on a message broker, a partition leader: the one server responsible for a given partition, the only one allowed to accept writes for it). Timestamps are not an order: two servers' clocks drift apart by milliseconds or more. - Per-conversation partitions. Key broker messages by
conversation_id, so every message of a conversation lands on the same partition (one ordered, independently-processed slice of the broker's overall stream, the "one ordered lane" from the direct answer above) and the same consumer (the one process reading that partition and handling its messages in order), which processes them in order. Different conversations spread across partitions and scale out. - Idempotent sends. The sender's client attaches
client_msg_id(a UUID, a universally unique identifier, a 128-bit random value different clients can each generate independently with negligible chance of collision, generated once and reused on every retry). The server keeps a unique constraint on(conversation_id, client_msg_id), so a retried send returns the original seq instead of creating message 42 twice. - Every delivery carries
seq, and the server answers "latest seq" in heartbeats and on reconnect.
Client-side strategy: dedupe, buffer, fill gaps
A runnable model of one conversation's client view. The simulated network loses 5% of messages (always including the final one, the hardest case), duplicates 20%, and locally reorders deliveries:
import random
class ConversationView:
"""Client-side reorder buffer for ONE conversation.
Server assigns seq 1, 2, 3, ... per conversation; the broker may
duplicate, delay or reorder deliveries (at-least-once)."""
def __init__(self, fetch_range):
self.last_shown = 0 # highest seq rendered contiguously
self.pending = {} # seq -> message, arrived early
self.fetch_range = fetch_range
self.shown = []
self.dupes_dropped = 0
self.gap_fetches = 0
def on_message(self, seq, body):
if seq <= self.last_shown or seq in self.pending:
self.dupes_dropped += 1 # at-least-once duplicate: ignore
return
self.pending[seq] = body
self._drain()
def on_gap_timeout(self, server_latest=None):
# a gap has persisted too long: ask the server for the missing range.
# server_latest comes from a heartbeat or reconnect handshake; it is
# the only way to notice a lost TAIL (nothing later arrives to expose it)
hi = min(self.pending) - 1 if self.pending else server_latest
if hi is not None and hi > self.last_shown:
lo = self.last_shown + 1
self.gap_fetches += 1
for seq, body in self.fetch_range(lo, hi):
self.pending.setdefault(seq, body)
self._drain()
def _drain(self):
while self.last_shown + 1 in self.pending:
self.last_shown += 1
self.shown.append(self.pending.pop(self.last_shown))
random.seed(7)
server_log = {s: f"msg-{s}" for s in range(1, 201)}
fetch = lambda lo, hi: [(s, server_log[s]) for s in range(lo, hi + 1)]
# network: every message duplicated with p=0.2, dropped with p=0.05,
# then the whole stream is locally shuffled (reordering within a window of 5)
wire = []
for s, body in server_log.items():
if random.random() < 0.05 or s == 200:
continue # lost (always lose the last one)
wire.append((s, body))
if random.random() < 0.2:
wire.append((s, body)) # duplicate
wire = sorted(wire, key=lambda m: m[0] + random.uniform(0, 5))
view = ConversationView(fetch)
for i, (seq, body) in enumerate(wire):
view.on_message(seq, body)
if i % 10 == 9:
view.on_gap_timeout() # timer fires periodically
view.on_gap_timeout(server_latest=200) # heartbeat: "latest seq is 200"
print("delivered on wire:", len(wire))
print("shown:", len(view.shown), "in order:", view.shown == [server_log[s] for s in range(1, 201)])
print("duplicates dropped:", view.dupes_dropped, "gap fetches:", view.gap_fetches)
Output:
delivered on wire: 240
shown: 200 in order: True
duplicates dropped: 58 gap fetches: 17
What the model demonstrates:
- Duplicates are free to handle:
seq <= last_shownis already on screen. The 58 dropped include both network duplicates and late copies of messages already fetched to fill a gap. - Early arrivals wait in
pendinguntil the missing seq appears. - Gaps are filled from the server after a timer; that is what
gap fetchescounts. - A lost final message is invisible to gap detection, because nothing later arrives to reveal it. Only an explicit "latest seq is 200" signal (heartbeat or reconnect handshake) exposes it, which is why the server must send one. The model deliberately loses seq 200 and still shows all 200 in order only because of that heartbeat call.
Dealing with gaps in practice
- Short hold (about 200 to 500 ms): most gaps are just reordering and close on their own.
- Then fetch the range
(last_shown, min(pending))over a normal request. Cap the fetch size; if the gap is enormous, fall back to reloading the conversation's latest page. - Never block forever: if the fetch fails, render what you have with a visible "loading earlier messages" marker, and keep retrying.
- Permanent gaps: if a seq was assigned but its write failed, the server stores an explicit tombstone for that seq (a stored marker recording that this sequence number will never have a message, unlike an ordinary row) so clients do not wait for a message that will never exist.
Reconciling after reconnect
- Client reconnects and sends
{conversation_id: last_contiguous_seq}for its open conversations (or, for the inbox list, a single per-user cursor: the highest seq across all of that user's conversations this device has fully processed, so the inbox can catch up in one read instead of one per conversation). - Server replays everything after each cursor, paged, then switches the connection to live delivery. Live messages that arrive during the replay simply go through the same dedupe and buffer, so the overlap is harmless.
- Outbound messages written while offline are resent with their original
client_msg_id. Any that the server had already stored before the disconnect come back with their existing seq rather than being duplicated. - Local echo: a message the user typed is shown immediately at the bottom with a "sending" clock icon. When its seq arrives it is moved to its true position. If someone else's message was sequenced first, the user's message visibly moves up by one: correct, and rare.
Latency versus ordering
| Policy | User-visible latency | Ordering |
|---|---|---|
| Show on arrival | Lowest | Wrong order after any reorder; later reshuffles are jarring |
| Hold until contiguous, forever | Unbounded during a lost message | Perfect |
| Hold up to about 300 ms, then fetch, render with a marker (chosen) | Bounded, usually zero extra | Correct once filled; brief marker at worst |
| Show immediately, re-sort in place when gaps fill | Lowest | Eventually correct but messages jump around |
For chat the right trade is a bounded hold: humans do not notice 300 ms, but they do notice messages rearranging while they read. For a stock ticker or live game state, where only the newest value matters, I would do the opposite: skip stale sequence numbers and never wait.
Pitfalls
- Tracking only "highest seq seen" instead of "highest contiguous seq": the client then silently skips a gap forever.
- Unbounded pending buffers: cap them, and on overflow reload the page of recent messages.
- Relying on the broker's partition order but letting multiple consumer threads process one partition in parallel, which reintroduces reordering after the broker.
- Forgetting that a lost last message has no gap to reveal 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.