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.
You're asked to migrate long-running generative requests from synchronous request/response to asynchronous streaming (progressive token delivery) without breaking SLAs for short, latency-sensitive requests. Design the architecture: client contract, correlation ids, streaming protocols, backpressure, cancellation, and how you would run a staged migration.
Sample Answer
Direct answer
Add streaming as a new, opt-in response mode of the same endpoint, not a replacement: the client asks for it ("stream": true or Accept: text/event-stream) and receives the tokens as Server-Sent Events (SSE), a one-way stream of events over a normal HTTP response. Every request carries a correlation ID that ties together retries, logs and cancellation. Protect short requests by separating the two workloads before they compete: separate admission queues and concurrency budgets at the gateway, and a cap on how much model capacity long streams may hold. Then migrate in stages behind a flag (a feature flag: a runtime on/off switch for a piece of functionality, changeable without a new deploy), per client, with automatic fallback to the synchronous path, and gate each stage on the short-request p99 (99th-percentile latency) staying inside its SLA (service-level agreement).
Requirements and working numbers
- Today: synchronous request/response. Long generations (30 to 120 s) hold a connection open with no output, so clients time out and users stare at a spinner.
- Short, latency-sensitive requests (classification, autocomplete) must keep their SLA; assume p99 under 1.5 s at 800 requests per second.
- Assume 40 long requests per second, averaging 45 s each.
By Little's law (concurrent work = arrival rate x time each item spends in the system): 40 x 45 = 1,800 concurrent open streams, versus 800 x 1.5 = at most 1,200 concurrent short requests in flight even at the p99 duration. The long workload is small in requests per second but dominant in held connections and held model capacity. That asymmetry is the core risk: without separation, 1,800 long streams can occupy the model servers' batch slots (most LLM-serving engines process many requests together in one GPU batch to use the hardware efficiently; each concurrent generation holds one of a fixed number of these slots per GPU, and once they are full, new requests queue) and push short requests into a queue.
sequenceDiagram
participant C as Client
participant G as API gateway
participant O as Orchestrator
participant M as Model server
C->>G: POST /v1/generate stream=true, Idempotency-Key
G->>O: admit to long-request pool, request_id
O->>M: start generation
G-->>C: event start (request_id)
M-->>O: tokens
O-->>G: tokens
G-->>C: event delta (seq=1..n)
C->>G: disconnect or DELETE /v1/generate/request_id
G->>O: cancel request_id
O->>M: abort, free batch slot
1. Client contract
- Request: unchanged body plus
stream: true. Old clients that omit it get the old synchronous behaviour, byte for byte. This is what makes the migration non-breaking. - Response:
200withContent-Type: text/event-stream, then typed events:startwithrequest_idand the model and limits in force;deltaevents, each with a monotonically increasingseqand a token chunk;heartbeatevery 15 s when no tokens flow (queueing, long tool calls), because many proxies and load balancers close idle connections (AWS Application Load Balancer's default idle timeout is 60 s);- exactly one terminal event:
done(with usage and finish reason) orerror(with a code and whether it is retryable).
- Errors before the first byte use ordinary HTTP status codes (400, 429, 503). Once the
200has been sent, errors can only be in-banderrorevents; document this, because clients that only check the status code will treat a mid-stream failure as success. - Very long or offline work (over a few minutes, batch jobs) gets a third mode:
202 Acceptedwith a job id, then poll or webhook (a webhook: the server calls back to a URL you gave it when the job finishes, instead of you polling for it). Streaming is for a human watching; do not hold connections for jobs nobody is watching.
2. Correlation IDs
Idempotency-Key(client-generated, per logical request): if the client retries after a dropped connection, the server finds the existing generation instead of starting a second one and paying for it twice.request_id(server-generated, returned in thestartevent and a response header): the key for logs, traces, cancellation and resume, propagated through gateway, orchestrator (the internal service between the gateway and the model servers that tracks each request's state and routes its tokens back) and model server.- Resume: the server buffers the generated tokens for a short time (for example 5 minutes) keyed by
request_id. A reconnecting client sendsLast-Event-ID: <seq>(the SSE standard's resume header) and receives only events after that sequence number.
3. Streaming protocol choice
SSE over HTTP/2 is my choice: output is one-way (server to client), it works through proxies and CDNs (content delivery networks) as plain HTTP, and resume via Last-Event-ID is built into the standard. WebSockets (a two-way connection) only earn their extra complexity if the client must send mid-generation input, such as interrupting a voice agent. gRPC server streaming (a gRPC mode where one request gets back a stream of many responses, well suited to one internal call producing a token stream) fits internal service-to-service hops (gateway to orchestrator to model server), where both ends are ours. One practical detail: the browser's built-in EventSource (the browser API that consumes a Server-Sent Events stream) only issues GET requests, so a POST-based stream is read with fetch and a stream reader, and the SDK sends Last-Event-ID itself when it reconnects.
4. Backpressure
Backpressure is how a slow reader slows down a fast writer instead of forcing it to buffer without limit. Tokens are small, so bandwidth is rarely the problem: 1,800 streams at about 4 KB/s each is 1,800 x 4,000 = 7.2 MB/s. The problem is memory and model time held for clients that are not reading.
- Bounded per-stream buffer at the gateway (for example 256 KiB). Worst case across 1,800 streams: 1,800 x 256 KiB = 0.44 GiB, which is safe to reserve.
- When a buffer fills, the client is not reading (a frozen tab, a dead mobile connection). Pausing the model is usually not possible in batched inference: the engine advances every sequence in the batch together each step, so there is no cheap way to freeze just one client's generation in place while leaving its slot reserved, the realistic choices are to keep spending compute on it or to free the slot by cancelling. So the choice is to keep generating into the resume buffer (bounded by
max_tokens, the client-set cap on how many tokens one generation may produce) or to cancel. I would let generation finish into the resume store if it is within a small token budget and cancel otherwise, because an abandoned generation wastes model capacity that short requests need. - Internal hops use the transport's flow control (HTTP/2 and gRPC windows: each side advertises how many unread bytes it will tolerate before the sender must pause, so a slow internal reader throttles its own upstream automatically), so the orchestrator never buffers without bound either.
5. Cancellation
- Explicit:
DELETE /v1/generate/{request_id}or an abort from the client SDK. - Implicit: the gateway detects client disconnect (TCP close, or failed writes) and, after a short grace period for reconnect-and-resume (for example 10 s), sends cancel downstream.
- Propagation all the way to the model server, which removes the sequence from its batch. This is the step teams forget: cancelling at the gateway alone leaves the model computing tokens nobody will read. Track "tokens generated after client disconnect" as a metric; it measures cancellation leakage directly.
- Billing: charge for tokens actually generated up to the cancel, so users are not punished for stopping a bad answer.
Protecting the SLA for short requests
- Classify at admission by the request's route and
max_tokens: short and long go to separate queues with separate concurrency limits. - Reserve capacity: long streams may use at most, say, 60% of model batch slots; the rest is guaranteed to short requests. Measure the split from traffic, not guesswork.
- Priority scheduling in the model server: short requests jump the queue ahead of new long ones (existing long streams keep running).
- Separate gateway pools if connection count is the bottleneck, so 1,800 long-held connections never exhaust the short path's connection slots.
- Metrics that match the new contract: for streams, time to first token (TTFT) and inter-token latency replace total latency; the short path keeps its p99.
Staged migration
- Build dual-mode: streaming exists behind a server-side feature flag, off. Synchronous path untouched.
- Internal dogfood (dogfooding: using the feature on our own internal traffic before any external client sees it): first-party clients only, synthetic load at the 1,800-stream level to confirm the short p99 does not move.
- Opt-in beta per API client; compare TTFT, error rate, cancellation leakage, cost per request.
- Default for new SDK versions, with automatic fallback: if the stream fails before the first token, the SDK retries once synchronously with the same
Idempotency-Key. - Gate each ramp step (1%, 10%, 50%) on: short-request p99 within SLA, stream error rate, and model utilization. Roll back is flipping the flag.
- Keep the synchronous mode indefinitely for clients that cannot consume streams; deprecate it only with usage data showing nobody needs it.
Trade-offs and pitfalls
- Streaming does not make the model faster. It moves the wait from "blank screen for 45 s" to "text appears in under a second". Total latency and cost are unchanged; perceived latency drops sharply.
- Proxy buffering (nginx, some CDNs) holds SSE output until the response ends, which silently turns streaming back into synchronous; disable response buffering on the streaming route and test through the real edge.
- Content moderation on partial output: if output must be filtered, decide whether to check chunks as they stream (lower latency, may need to retract) or to hold a short window before emitting.
- What would change the design: if most long requests were machine-to-machine batch work, the async job mode (202 plus polling or webhook) should be the main path, and streaming would only serve interactive users.
Explain optimistic updates in client-server real-time applications. Describe how optimistic updates improve perceived latency, the consistency risks they introduce, and common reconciliation or undo strategies you would design (e.g., operation IDs, server ack, rollback UX patterns). Provide examples such as UI toggles, chat 'sent' states, or like buttons.
Sample Answer
Direct answer
An optimistic update shows the result of a user's action immediately, before the server has confirmed it, on the bet that the server will say yes. It improves perceived latency because the user sees their action land in one frame (about 16 ms) instead of waiting a full network round trip. The price is that, for a moment, the screen can show something that is not true. The design work is deciding what happens when the bet loses: every optimistic change carries an operation ID, waits for a server acknowledgement (ACK), and has a defined way to be rolled back or reconciled (brought back into agreement with the server's true state), with UX that makes the correction understandable rather than jarring.
How it improves perceived latency
Without optimism, a tap costs one round trip plus server processing before anything changes. On a mobile network with a 150 ms round trip and 50 ms of server work, the user waits about 200 ms, which is past the roughly 100 ms point where people stop perceiving a response as instant. With optimism, the change renders on the next frame and the 200 ms happen in the background. The action has the same actual latency; only the perceived latency drops.
It pays off most when three things are true: the action succeeds almost always (a like, a toggle, sending a message), the result is easy for the client to predict, and undoing it is cheap.
The consistency risks it introduces
| Risk | What the user sees | Example |
|---|---|---|
| Rejected action | Something appears, then disappears | Liking a post that was just deleted |
| Lost acknowledgement | Action looks saved but the client cannot tell | ACK dropped on a flaky network, client retries |
| Duplicate apply | Action happens twice | Retry of "send message" creates two messages |
| Concurrent edit | Local value overwritten or overwriting | Two people rename the same card |
| Wrong derived value | Counters drift | Client shows 101 likes; server's true count is 108 |
| Ordering | Items jump position | Optimistic chat message sorted by local clock, then re-sorted by server time |
Reconciliation and undo strategies
- Operation IDs. The client generates a unique ID per user action (a UUID) and sends it with the request. The server records IDs it has processed; a retry with the same ID returns the original result instead of applying twice. This fixes duplicate apply and makes it safe to retry after a lost ACK.
- Server ACK as the commit point. Keep the confirmed state separately from pending changes. On ACK, the change becomes confirmed. On NACK (a rejection), drop the pending change and re-render; that is the rollback. Recomputing the view from "confirmed plus pending" is safer than hand-written undo when several changes are in flight.
- Server state wins for derived data. For counters, the client shows
server_count + my_pending_delta, and every server update replacesserver_count. The user's own +1 never disappears, but the total converges to truth. - Rebase on conflict. If the server says "your change was based on an older version", take the server's state and re-apply the local change on top (fine for independent fields), or surface the conflict (for text where both edits matter).
- Idempotent operation shape. Prefer "set liked = true" over "toggle like". A retried "set" is harmless; a retried "toggle" flips it back.
Rollback UX patterns
- Pending indicator: a subtle state (a greyed timestamp, a single tick) until ACK. The user knows it is in flight without being blocked.
- Quiet revert for trivial actions: a like that fails can revert with a short toast ("Couldn't like this post").
- Inline failure with retry for valuable content: a chat message never silently disappears. It stays in place with "Not sent. Tap to retry", because the user's typed text is worth more than visual tidiness.
- Undo window: for destructive actions (archive, delete), show the result optimistically plus an "Undo" snackbar for a few seconds and send the request when the window closes. This is optimism in the other direction: the user gets instant feedback and a cheap undo.
Worked examples
UI toggle (notifications on/off). Flip the switch immediately and send PUT /settings {notifications: true, opId}. On NACK, flip it back and show a short error. Because the payload is "set to true", a retry cannot flip it the wrong way. If the user taps three times quickly, only the last intended value matters: debounce, or send each with a version so the server can ignore stale ones.
Chat "sent" states. The message appears at once with state sending, keyed by a client ID such as c-7f3a. States move sending -> sent (server ACK, which returns the permanent message ID and server timestamp) -> delivered -> read (later events). When the ACK arrives, the client swaps c-7f3a for the server ID and re-sorts by server timestamp, which is why a message can nudge one position. If the socket dropped and the client resends, the server sees c-7f3a again and returns the same message instead of creating a duplicate.
Like button with counter. Server says 107 likes. User taps like: show filled heart and 108 (107 + 1 pending). Meanwhile a real-time event reports 110 (others liked too); the client shows 110 + 1 = 111 while pending, then on ACK the pending delta is folded in and the server's next count is shown as-is. The user never sees their own like vanish, and the number never goes backwards because of their action.
Trade-offs and pitfalls
- Do not be optimistic about actions that often fail or that have outside effects: payments, booking the last seat, anything the user would act on if it looked confirmed. Show a pending state and wait.
- Generate IDs on the client, not with auto-increment on the server, or the client cannot refer to the item before the ACK.
- Remember pending operations across reloads if losing them would lose user work (store them locally and resend with the same IDs).
- Do not trust the local clock for ordering. Sort by server time once known, and keep pending messages at the bottom until then.
- Failure paths are the feature. Most teams build the happy path and never test the NACK and the lost-ACK paths; those are the paths that decide whether users trust the app.
Architect a globally distributed real-time chat system supporting 100 million daily active users, 200 million daily messages, and peaks of 10k-100k messages per second. Address user presence, message routing and partitioning, ordering guarantees, offline delivery and reconciliation, moderation and abuse controls, multi-region replication, network-partition handling and client reconnection, latency targets, and capacity planning.
Sample Answer
Direct answer
I would build it as regional edge gateways holding WebSockets (a single, long-lived, two-way connection between client and server, opened once and reused instead of one connection per request), a conversation service that gives every conversation a single home region and a single writer (one component, shown as the sequencer in the diagram below, that alone assigns the next sequence number for that conversation, so two nodes can never hand out the same number), and a durable message store partitioned by conversation ID (split into independently stored chunks, one chunk per conversation, so no single chunk carries the whole system's traffic). Ordering is guaranteed per conversation by a sequence number assigned by that single writer, never globally. Delivery to online users goes through gateway routing; offline users catch up by syncing from their last sequence number, with an OS push notification to wake them. The numbers that drive the design are 20 million peak connections and a peak-to-average message ratio of about 43, which means provisioning for peak rather than autoscaling into it.
Requirements and assumptions
- 100 million daily active users (DAU), 200 million messages per day, peaks of 10,000 to 100,000 messages per second.
- Assumptions to state out loud (not given): 20% of DAU online at the global peak; average stored message about 1 KB including metadata and indexes; average 3 recipients per message (mostly one-to-one, some groups).
- Latency targets (targets I would propose, not measurements): send-to-acknowledgement p99 (99th percentile) under 200 ms in-region; delivery to an online recipient in the same region p99 under 300 ms; cross-region under 500 ms.
Capacity planning (arithmetic shown)
| Quantity | Calculation | Result |
|---|---|---|
| Average message rate | 200,000,000 / 86,400 s | about 2,315 per second |
| Peak-to-average ratio | 100,000 / 2,315 | about 43x |
| Peak concurrent connections | 20% × 100,000,000 | 20,000,000 |
| Gateways at 50,000 connections each (ESTIMATE, load-test it) | 20,000,000 / 50,000 | 400, run about 600 for failure and deploy headroom (1.5x) |
| Peak deliveries | 100,000 × 3 recipients | 300,000 per second |
| Peak payload bandwidth | 100,000 × 1 KB in; 300,000 × 1 KB out | 0.8 Gbps in, 2.4 Gbps out (payload only) |
| Storage per day | 200,000,000 × 1 KB | 200 GB raw; 600 GB with 3 replicas |
| Storage per year | 600 GB × 365 | about 219 TB replicated |
The 43x ratio matters: connection-holding gateways cannot be autoscaled in seconds (new nodes get no existing connections). Because each connection lives on exactly one gateway for its whole life, a freshly started node can only take brand-new connections; it cannot take over message traffic for the 20 million sockets already pinned to other nodes, the way a stateless HTTP fleet could add a node and have it immediately share all existing traffic. So the gateway fleet and the write path are sized for the 100,000 per second peak.
Architecture
flowchart LR
C[Clients] --> GW[Regional gateways]
GW --> CS[Conversation service]
CS --> SEQ[Per-conversation sequencer]
SEQ --> MS[(Message store by conversation)]
CS --> MOD[Inline moderation checks]
SEQ --> RT[Delivery router]
RT --> REG[(Routing registry)]
RT --> GW
RT --> PUSH[OS push for offline users]
MS --> REP[Cross-region replication]
Presence
Presence (the online, idle or offline status other users see) is derived from gateway connections: each gateway records user -> gateway in a regional routing registry (with expiry) and publishes online/idle/offline transitions. Clients subscribe only to the presence of people on screen, so presence traffic scales with what users are viewing, not with contact-list size.
Message routing and partitioning
- Partition key: conversation ID. All messages of one conversation live on one partition of the message store and are sequenced by one owner. Hashing by sender would spread one conversation across partitions and destroy its order.
- Send path: client sends
{conversation_id, client_msg_id, body}over its WebSocket. The gateway forwards to the conversation service in the conversation's home region. The owner assigns the next sequence number, writes to the store, acknowledges the sender, then hands the message to the delivery router. - Delivery: the router looks up each recipient's gateway in the registry (in each region) and publishes to that gateway's inbox channel on a pub/sub (publish/subscribe) bus; the gateway writes to the socket.
- Large groups: above, say, 1,000 members, stop per-recipient pushes. Send a lightweight "conversation X has new messages up to sequence N" signal to online members and let clients pull (fan-out on read: the server does not push a copy to every member; each client pulls the actual messages itself when ready, unlike the per-recipient push used above for smaller conversations, which is fan-out on write).
Ordering guarantees
- Per-conversation total order: every participant sees messages in sequence-number order. Clients hold a small reorder buffer (a local holding area for messages that arrived out of order, kept until the missing earlier one shows up) and request any gap.
- Idempotent sends:
client_msg_idis an idempotency key (a client-generated ID that lets the server recognize a retry). If the acknowledgement is lost and the client resends, the server returns the original sequence number instead of storing a duplicate. - No global order. A global sequencer across 100,000 messages per second and several regions would be a single bottleneck and a cross-region latency tax for no user-visible benefit.
Offline delivery and reconciliation
- Each client stores, per conversation, the last sequence it has. On reconnect it sends
sync(cursors); the server returns missed messages (paged), plus updated unread counts and read receipts. - For a user with no live connection, the router enqueues a push notification (APNs or FCM, the Apple and Google push services) carrying a short preview or just "new message", which wakes the app to sync.
- A per-user inbox index (conversation list ordered by last activity with each conversation's latest sequence) lets a client that was offline for a week find what changed without scanning every conversation.
Moderation and abuse controls
- Inline, fast (under about 20 ms budget): per-user rate limits with a token bucket (a counter refilled at a steady rate; each message spends one token, and an empty bucket means reject; for example a burst of 10 messages per second, lower for accounts under 24 hours old), block lists, link reputation lookups, and a check that the sender is a member of the conversation.
- Asynchronous, heavier: machine-learning classifiers for spam, harassment and illegal content run after delivery; a violation publishes a "retract message" event that removes it from clients and the store, and feeds account-level penalties.
- User reports go to a review queue with the reported message and nearby context.
- If the product adopts end-to-end encryption (only endpoints can read content), server-side content classification is impossible; moderation then relies on metadata signals, rate limits and user reports. Decide this early because it changes the whole moderation design.
Multi-region replication
- Users connect to the nearest region. Each conversation has a home region (chosen at creation, for example the creator's region, and movable later if most participants are elsewhere). Writes for that conversation are sequenced in the home region, so ordering needs no cross-region coordination.
- Messages replicate asynchronously to other regions where participants live, so reads and syncs are served locally.
- A user in Tokyo writing to a conversation homed in Frankfurt pays one cross-region hop on send, which is why the cross-region delivery target is 500 ms rather than 300 ms.
Network-partition handling and client reconnection
("Partition" shifts meaning in this section: a network partition is a break in connectivity, for example between two regions, not a data partition of the message store described above.)
- Client side: outgoing messages go into a local outbox (a small per-device queue holding the user's own messages that have been sent but not yet acknowledged) and show "sending" until acknowledged; retries reuse the same
client_msg_id, so a flaky network can never double-post. Reconnect uses exponential backoff with jitter, then resyncs from cursors. - Region partition: if a conversation's home region is unreachable, sends to that conversation queue in client outboxes (reads of already-replicated history still work). I choose ordering and correctness over accepting writes in two regions at once, because two writers would assign conflicting sequence numbers.
- Region failure: after the region is declared down (a deliberate control-plane decision: a considered call made by the system's management layer over minutes, not an automatic reflex to one dropped packet), the conversation's home moves to a surviving region with a higher epoch number (a version stamped on the ownership). The old owner's writes carry a stale epoch and are rejected by the message store, which records the current epoch for each conversation and refuses any write stamped with an older one, which prevents split brain (two regions both believing they own the conversation). Messages that were acknowledged but not yet replicated when the region died are the recovery-point risk (data confirmed to the sender but copied nowhere else yet, so it is lost if that one copy is destroyed): keep replication lag (how far behind the copy in another region trails the latest acknowledged write) monitored and small.
Trade-offs and pitfalls
- Partitioning by user instead of conversation makes ordering and group delivery much harder.
- Global ordering is expensive and rarely needed; per-conversation order is what users perceive.
- Relying on the socket for delivery loses messages on every disconnect; the durable store plus cursors is the guarantee.
- Autoscaling a connection fleet reactively fails at a 43x peak; provision for it.
- Active-active writes (both regions accepting and assigning sequence numbers for the same conversation at the same time, instead of one region owning it) for the same conversation in two regions trade a small latency win for sequence conflicts and user-visible reordering.
Describe techniques for handling backpressure when a server streams events to many clients with different consumption rates. Discuss per-client buffering and eviction policies, adaptive rate-limiting, batching and windowing, drop/trim strategies, and how to surface client feedback so the server knows a client is falling behind. Explain the memory and CPU trade-offs and the monitoring signals you would use to detect backpressure, including how you would manage the underlying per-connection buffer memory (pooling, eviction, soft/hard limits) to avoid OOM during traffic spikes.
Sample Answer
Direct answer
The server must never let one slow client's backlog become everyone's problem. My default stack is: a bounded per-client queue with byte limits, a per-stream eviction rule chosen by what the data means (coalesce state, never silently drop events), batching within a short window to cut per-message cost, and explicit flow-control signals (the socket's own "write buffer full" signal plus application-level acknowledgements) so the server knows who is behind. Memory is protected with shared, reference-counted payloads, pooled buffers, and soft/hard limits at both the connection and node level.
Backpressure means the consumer cannot keep up with the producer, so data piles up somewhere. On a streaming server that "somewhere" is the per-connection send buffer, and if it is unbounded the process eventually runs out of memory (OOM) and every connection on it drops.
How the server learns a client is falling behind
Strongest signals first:
- Transport signal. When a client reads slowly, the kernel's TCP send buffer (a small chunk of memory the operating system holds per connection to stage outgoing bytes before the network card sends them) for that socket fills, and a non-blocking write (a write call that returns immediately with however many bytes it could accept, instead of pausing the program until all of them fit) accepts fewer bytes. In Node.js (a JavaScript server runtime),
socket.write()returnsfalseand a'drain'event fires once the buffer empties; in Go or Netty (a networking library for Java) the equivalent is a write that blocks or a channel that reports not-writable (the library's own signal that the underlying socket buffer is full). This is free and always available, so treat it as the primary detector. - Application acknowledgements. The client periodically sends "processed up to sequence 18,204". The gap between the latest sent and the latest acknowledged sequence number is the client's lag in messages, which also covers a client whose network is fine but whose app is slow (a busy UI thread).
- Credit-based flow control. The client grants N messages (credits); the server stops sending when credits run out and resumes when the client grants more. This is the most precise and is how protocols like HTTP/2 (the HTTP version that multiplexes many streams over one connection) and gRPC (a remote-procedure-call framework built on HTTP/2) streams work, but it costs a round of client messages.
- Client-reported health, for example a browser can read
WebSocket.bufferedAmountfor its outgoing queue and report frame-render lag. Useful for diagnosis, not for control.
My choice: transport signal plus cumulative acknowledgements. Add credits only for streams where each message is expensive to render.
Techniques, and when each is the right one
| Technique | What it does | Use it for | Memory / CPU cost |
|---|---|---|---|
| Bounded per-client buffer | Cap queued bytes per connection | Every stream, always | Caps memory; no CPU cost |
| Eviction: drop-oldest | New data pushes out old | Feeds where freshness matters | None |
| Eviction: coalesce by key | Keep only latest value per key (per stock symbol, per document cursor) | State-like streams | Small hash map per client |
| Eviction: drop-newest / reject | Refuse new data when full | Rarely right for fan-out; OK for uploads | None |
| Disconnect and resync | Close with a "refetch state" reason | Event streams where every message matters (chat) | Resync load on the backend |
| Adaptive rate limiting | Lower the send rate to the measured drain rate; raise it slowly when the client keeps up (additive increase, multiplicative decrease: add a fixed amount to the send rate each time the client keeps up, for example +10 msg/s, but cut it by a fraction, for example to half, the moment it falls behind; the same idea TCP uses to find a safe rate without a fixed number to tune) | Tickers, telemetry dashboards | Per-client timer and rate estimate |
| Batching and windowing | Collect messages for, say, 50 ms and send them in one frame | High message rates with small messages | Adds up to one window of latency; saves per-frame syscalls (the per-write calls a program makes into the operating system to push bytes onto the network; each one has a small fixed cost, so fewer, bigger writes are cheaper than many tiny ones) and headers |
| Conflation window | Within each window send only the latest value per key | Market data, live scores | Latency of one window; large CPU saving |
Commitment: for a mixed stream I classify messages up front. State-like messages get coalescing plus a conflation window that widens as the client falls behind (0 ms when healthy, 250 ms when lagging, 1 s when far behind). Event-like messages get a bounded queue; when it overflows, the client is disconnected with a resync instruction rather than silently losing events. Drop-oldest is used only for streams where the product explicitly says gaps are acceptable.
Managing buffer memory so a spike cannot OOM the node
- Serialize once, share the bytes. In a fan-out, the same message goes to thousands of clients. Encode it once into an immutable buffer and let each client queue hold a reference. The buffer is freed when the last reference is released (reference counting).
- Pool and size-class buffers. Allocate network buffers from a pool (pre-allocated, reused memory) organised in fixed size classes, like a slab allocator (for example 1 KB, 4 KB, 16 KB, 64 KB slabs). Reuse avoids allocation churn (the CPU cost of constantly asking the runtime for new memory and then freeing it moments later) and garbage-collector pauses (a pause the runtime takes to reclaim memory automatically, during which that thread does no other work), and fixed classes avoid fragmentation, where free memory exists but in pieces too small to use. Netty's (a networking library for Java) pooled allocator and Go's
sync.Pool(a standard-library object pool built into the Go language) are common implementations of this idea. - Soft and hard limits at two levels. Per connection: soft limit starts degradation (coalescing, wider windows), hard limit triggers disconnect-and-resync. Per node: a soft limit makes every client degrade a little and stops accepting new connections (admission control); a hard limit evicts the slowest clients first, largest queue first.
- Keep headroom for the kernel. Each TCP socket also has a kernel send buffer outside your process heap; include it when budgeting memory per connection.
Worked example
A node holds 50,000 WebSocket connections and has 16 GiB of RAM, of which I budget 4 GiB for send queues.
naive hard limit 256 KiB:50,000×256 KiB=12,800,000 KiB≈12.2 GiBThat worst case blows the 4 GiB budget, which is why the node limit, not the per-connection limit, is what actually protects memory: per-connection limits bound the damage from one client, the node limit bounds the sum.
Committing to actual numbers for this node: keep the per-connection hard limit at 256 KiB (it still bounds any one client), but add a per-connection soft limit of 64 KiB, where coalescing and wider conflation windows kick in, well before a client is disconnected. Then set the node-wide soft limit at 2.5 GiB (about 62% of the 4 GiB budget, leaving headroom for kernel send buffers and process overhead) where every client starts degrading and new connections stop being admitted, and a node-wide hard limit at 3.5 GiB where the node evicts the largest queues first. That node hard limit is reached once about 3.5 GiB / 256 KiB = 14,336 connections, under 29% of the fleet, are simultaneously sitting at their per-connection cap, which is exactly why the per-connection limit alone cannot protect the node: the node-level guard has to fire long before all 50,000 clients could ever get there.
Now a 1 KB price update fanned out to all 50,000 clients:
- Copy per client: 50,000 x 1,024 bytes = 51.2 MB for one message.
- Shared buffer: 1 KB plus 50,000 8-byte references = about 400 KB.
During a market-open spike of 100 messages per second with 10% of clients lagging by 5 seconds, copying costs 5,000 lagging clients x 500 messages x 1 KB = about 2.5 GB, while sharing costs only the 500 distinct messages (about 0.5 MB) plus references (5,000 x 500 x 8 bytes = 20 MB). The 5-second lag is exactly where coalescing earns its keep: if those 500 messages cover 50 symbols, each lagging client needs only 50 of them.
Monitoring signals
- Per-connection queued bytes and age of the oldest queued message (lag in seconds is what users feel), as histograms, never per-client labels.
- Node total queued bytes vs the soft and hard limits; process resident memory (RSS) vs the container limit.
- Counters: coalesced, dropped, and disconnected-for-resync, by stream class and reason.
- Kernel view: per-socket send queue, the Linux command
ss -tm(which lists TCP sockets with memory detail) showsSend-Q, the bytes still queued to be sent for that socket, useful when process metrics look healthy. - Garbage-collector pause time (see above) and buffer-pool hit rate (pool misses mean allocation churn).
- Acknowledgement lag distribution (sent seq minus acked seq).
Alert on the fraction of clients lagging, not on one: one slow client is normal; 30% lagging means the server or the upstream is the bottleneck.
Trade-offs and pitfalls
- Batching trades latency for throughput. A 50 ms window is invisible in a dashboard and ruinous in a game; tie window size to lag, not to a constant.
- Compression helps bandwidth, costs CPU, and per-message compression with a shared buffer means compressing once, not once per client.
- Unbounded queues "because memory is cheap" is the most common production OOM in streaming servers.
- Slow-client eviction must be visible. A disconnect-and-resync without a clear reason code looks like a flaky network and triggers aggressive client reconnect loops; send a reason and a suggested backoff.
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.