Real-Time and Streaming System Design Questions
Designing client-facing, always-on live delivery systems: real-time communication transports (WebSockets, server-sent events, long-polling, WebRTC, MQTT), connection lifecycle and scaling for millions of persistent connections, presence, pub/sub fan-out to online users, chat and notifications, live feeds and tickers, real-time collaboration (CRDT vs OT, offline sync and reconciliation), and live and on-demand video delivery (ingest, transcoding, adaptive bitrate, CDN delivery, low-latency protocols, playback entitlement and content protection). Covers latency budgets, per-client ordering, delivery guarantees across disconnect and reconnect, per-client backpressure, capacity estimation for connection fleets, authentication, authorization, and revocation for real-time channels and premium content, and operational readiness (SLOs and error budgets, observability and incident response, rate limiting, safe rollout, and load and chaos testing) for live-delivery platforms. Data-pipeline stream processing (Kafka or Flink jobs, windowed aggregation, exactly-once pipelines, real-time analytics ingestion) is out of scope.
Explain strategies to provide at-least-once, at-most-once and exactly-once semantics for message delivery in a realtime system. Include practical techniques for ordering (per-client sequencing, partitioned global sequence numbers, vector clocks) and discuss implementation complexity, metadata overhead, and performance trade-offs for each approach.
Sample Answer
Direct answer
The three guarantees differ in when the receiver acknowledges and whether the sender retries. At-most-once: send once, never retry; a message may be lost but never duplicated. At-least-once: persist, retry until acknowledged, and acknowledge only after processing; nothing is lost but duplicates happen. Exactly-once in a real-time system is at-least-once delivery plus idempotent processing (the receiver recognizes and ignores repeats using a message ID or sequence number), sometimes called effectively-once; the network alone cannot provide it, because a sender cannot tell a lost message from a lost acknowledgement. Ordering is a separate choice: per-client sequence numbers (cheap, order per sender only), partitioned global sequence numbers (a total order within each partition, meaning every reader agrees on the exact same before/after ordering of all messages in that partition; one sequencer per partition), or vector clocks (captures cause and effect across many writers, at a metadata cost that grows with the number of writers).
The three delivery semantics
| At-most-once | At-least-once | Exactly-once (effectively) | |
|---|---|---|---|
| Mechanism | Fire and forget, or ack before processing | Durable send log, retry with backoff (each retry waits longer than the last, so a struggling receiver is not hit harder), ack after processing | At-least-once + dedupe store or idempotent operations, or an atomic commit of result and progress |
| Loss | Possible | No | No |
| Duplicates | No | Possible | Suppressed |
| Metadata | None | Message ID, retry state | ID + a dedupe window, or per-stream sequence |
| Cost | Lowest | Retries, storage | Extra lookup or write per message |
| Good for | Typing indicators, cursor positions, telemetry you can lose | Notifications where a rare duplicate is tolerable | Chat messages, payments events, anything a human would notice twice |
Implementation notes:
- At-most-once usually happens by accident: a consumer that acknowledges (or commits its offset, records how far into the stream it has read, so a restart knows where to resume) before processing and then crashes loses that message.
- At-least-once requires the ack to come after the side effect. The duplicates it creates arrive when the ack is lost, the sender times out, or a consumer crashes after processing but before acknowledging.
- Exactly-once, two practical routes:
- Dedupe: the receiver records processed IDs and skips repeats. With a per-sender sequence number this is a single integer per sender ("ignore anything at or below 57"). With random IDs it is a time-windowed set: at 10,000 messages/s, 16-byte IDs and a one-hour window, that is 10,000 x 3,600 x 16 bytes = 576 MB before index overhead. Sequence numbers are far cheaper than ID sets.
- Atomic commit: write the result and the "processed up to here" marker in one transaction, so a crash either did both or neither.
- The boundary matters: a system can be exactly-once internally and still show a duplicate if the last hop (a push notification to a phone) is at-least-once. Carry the ID all the way to the client so it can dedupe too.
Ordering techniques
1. Per-client (per-sender) sequencing. Each sender numbers its own messages 1, 2, 3; the server holds back message 5 from Ana until 4 has arrived. Metadata: one 8-byte counter per message. Guarantees Ana's messages are in Ana's order, says nothing about Ana versus Ben. Good for command streams from one device (a game controller, one user's edits).
2. Partitioned global sequence numbers. A single sequencer per partition (for example per chat room, or per log partition keyed by room) stamps 1, 2, 3 across all senders. Metadata: 8 bytes. Every reader of that partition sees the same total order, and gaps are detectable. Cost: the sequencer is a per-partition throughput limit and a failover concern (it needs leader election, where the sequencers agree on which single instance is currently allowed to hand out numbers, and fencing, a way to guarantee that a former leader which has not yet noticed it lost the election, for example because of a network blip, cannot keep issuing numbers: each leader term gets an increasing epoch number, and the log rejects any write carrying an older epoch, so two sequencers never both hand out 501), and there is no order between partitions. This is the default for chat, feeds and tickers.
3. Vector clocks. Each writer keeps a counter per writer it has heard from; a message carries the whole vector. Comparing two vectors tells you whether one message happened before the other or whether they are concurrent (neither writer had seen the other's message). Runnable illustration:
def happened_before(a, b):
"""a -> b iff a <= b component-wise and a != b."""
keys = a.keys() | b.keys()
return all(a.get(k, 0) <= b.get(k, 0) for k in keys) and a != b
def relation(a, b):
if happened_before(a, b):
return "before"
if happened_before(b, a):
return "after"
return "concurrent"
class Replica:
def __init__(self, name):
self.name, self.clock = name, {}
def send(self, text):
self.clock[self.name] = self.clock.get(self.name, 0) + 1
return {"text": text, "vc": dict(self.clock)}
def receive(self, msg):
for k, v in msg["vc"].items():
self.clock[k] = max(self.clock.get(k, 0), v)
alice, bob, carol = Replica("alice"), Replica("bob"), Replica("carol")
q = alice.send("Lunch at 12?")
bob.receive(q); carol.receive(q)
a1 = bob.send("Yes, 12 works") # bob has seen q
a2 = carol.send("Can we do 1pm?") # carol has seen q, not bob's reply
print("q vs bob :", relation(q["vc"], a1["vc"]))
print("q vs carol:", relation(q["vc"], a2["vc"]))
print("bob vs carol:", relation(a1["vc"], a2["vc"]))
print("bob's clock :", a1["vc"])
print("carol's clock:", a2["vc"])
Output:
q vs bob : before
q vs carol: before
bob vs carol: concurrent
bob's clock : {'alice': 1, 'bob': 1}
carol's clock: {'alice': 1, 'carol': 1}
Both replies correctly come after the question, and the clocks prove Bob's and Carol's replies were written without seeing each other, so no ordering between them is "right": the application must pick a deterministic tie-break or show both as parallel. Metadata grows with the number of writers: 50 participants x 8 bytes = 400 bytes per message, versus 8 bytes for a sequence number, which across a million messages is 400 MB versus 8 MB. Good for multi-leader or offline-first replicas (systems where more than one replica can accept writes without checking with the others first, such as collaborative editing or an app that keeps working offline and syncs later), rarely worth it for server-sequenced chat.
Comparison
| Technique | Order it gives | Metadata per message | Complexity | Performance limit |
|---|---|---|---|---|
| Per-sender seq | Per sender only | 8 bytes | Low | None central |
| Partitioned global seq | Total within a partition | 8 bytes | Medium: sequencer election, fencing | One sequencer per partition |
| Vector clock | Causal across writers, detects concurrency | 8 bytes x writers | High: pruning (discarding old per-writer counters once every replica has caught up, so the vector doesn't grow forever), tie-breaking, merges | Metadata and comparison cost grow with writers |
Worked example: a chat system
- Client sends with a
client_msg_idover at-least-once transport; the server dedupes on it (exactly-once effect for sends). - The room's partition sequencer assigns seq 1, 2, 3 (partitioned global order).
- Delivery to members is at-least-once; clients drop anything at or below their last contiguous seq (exactly-once display).
- Typing indicators skip all of this: at-most-once, no sequence, because a lost "Ana is typing" costs nothing.
Pitfalls
- Claiming exactly-once without naming the dedupe mechanism and its window.
- Using wall-clock timestamps as sequence numbers; server clocks drift, so two messages can swap order.
- Dedupe windows shorter than the longest retry interval, which lets a late retry through as new.
- Paying for vector clocks when a single sequencer per partition would do.
Describe approaches to broadcast a piece of data (e.g., live sports update) to millions of clients with low latency: origin server fan-out, broker-based pub/sub, hierarchical fan-out (multi-level brokers), multicast (on LAN), and CDN-assisted push. For each approach discuss cost, latency, state management, and when it's most appropriate.
Sample Answer
Direct answer
For millions of internet clients I would use hierarchical fan-out: the origin publishes each update once to a broker, a small set of regional relays subscribe, and each relay feeds edge gateways that hold the client connections, so every server sends to at most a few hundred children or its own local clients and no single machine does millions of writes. Plain origin fan-out works only up to what one server can hold. Broker-based pub/sub is the right building block inside a region. Multicast is for networks you control (a data centre or trading floor), not the public internet. CDN-assisted delivery wins when a second or two of latency is acceptable, because the provider's edge absorbs the connection count.
Terms: fan-out is turning one message into many copies, one per recipient; pub/sub (publish/subscribe) lets a sender publish to a named topic while every subscriber receives a copy; a CDN (content delivery network) is a provider's network of edge servers near users that caches or relays content; multicast is IP-level delivery where the network itself copies one packet to every member of a group.
Scenario for the numbers
5 million connected clients, a 300-byte score update, bursts of several updates per minute during a match.
bytes per updateone origin at 10 Gbps=5,000,000×300 B=1.5 GB=1.5×8/10=1.2 s just to serialise the bytesThat 1.2-second floor, before counting 5 million socket writes and TLS encryption on one machine, is why fan-out must be spread.
The five approaches
1. Origin server fan-out
The server that produces the update holds every client connection and loops over them.
- Cost: cheapest to build; no extra infrastructure.
- Latency: fine for thousands of clients; the last client waits for all writes before it, so latency grows with the count.
- State: all connection state on one server (or a few), which is a single point of failure.
- When: internal tools, small apps, up to the tens of thousands of connections one server can hold while also running the application's own logic on each connection. A server dedicated only to holding sockets and forwarding bytes, with no business logic per connection, such as the edge gateways described below, can hold far more, on the order of 100,000 or more; the tens-of-thousands figure here is the cost of doing real work on the connection, not a hard ceiling on sockets.
2. Broker-based pub/sub
The origin publishes once to a broker: Redis Pub/Sub (a lightweight, fire-and-forget publish/subscribe feature built into the Redis in-memory store, with no persistence), NATS (a messaging system built for fast, low-overhead pub/sub), Kafka (a durable, partitioned log-based broker that retains messages), and similar. Many gateway servers subscribe, and each writes to its own connected clients.
- Cost: a broker cluster plus a gateway fleet. With 50 gateways, each serves 100,000 clients: 100,000 x 300 B = 30 MB = 0.24 Gb per update, about 24 ms of wire time on a 10 Gbps NIC (network interface card, the hardware a server uses to send and receive network traffic).
- Latency: one broker hop (a few milliseconds in-region) plus parallel gateway writes.
- State: gateways hold connections; the broker holds subscriptions. Gateways are interchangeable.
- When: the default for a single region up to the point where the broker's own fan-out to gateways, or cross-region traffic, becomes the bottleneck.
3. Hierarchical fan-out (multi-level brokers)
A tree: origin, then regional relays, then edge gateways, then clients. If each level fans out by a factor f, reaching N clients takes about log_f(N) levels:
| Fan-out per level | Levels to reach 5 million |
|---|---|
| 10 | 7 |
| 100 | 4 |
| 1,000 | 3 |
- Cost: more hops and more relay servers, but each relay does bounded work and cross-region traffic carries one copy per region instead of one per client.
- Latency: each level adds a hop. With 3 or 4 levels, most of the latency is geographic (origin to far regions), not the tree.
- State: each level holds only its children's subscriptions, so the tree scales out; a failed relay must be detected and its children re-parented (reassigned to subscribe to a different, healthy relay in the tree).
- When: millions of clients across regions, live events, market data at global scale.
flowchart TB
O[Origin publisher] --> B[Core broker]
B --> R1[Relay: US]
B --> R2[Relay: EU]
B --> R3[Relay: APAC]
R1 --> G1[Edge gateways US]
R2 --> G2[Edge gateways EU]
R3 --> G3[Edge gateways APAC]
G1 --> C1[Clients]
G2 --> C2[Clients]
G3 --> C3[Clients]
4. Multicast (on a LAN)
The sender transmits one packet; switches and routers copy it to every port with a subscriber.
- Cost: near zero bandwidth amplification at the sender; requires multicast-capable network configuration.
- Latency: the lowest possible, one packet, no application hops. This is why exchanges distribute market data this way.
- State: group membership lives in the network (switches and routers track joins); delivery is UDP (User Datagram Protocol, a connectionless protocol that sends packets without TCP's guarantees of delivery or ordering), so lost packets need a separate recovery mechanism (sequence numbers plus a retransmission service).
- When: only inside networks you control. The public internet does not route multicast, and browsers cannot receive it. Inside a data centre it can distribute updates from origin to your own gateway fleet, but many cloud networks do not support it.
5. CDN-assisted push
Two variants:
- Edge-held connections: some edge platforms terminate long-lived connections (SSE, Server-Sent Events, a long-lived one-way HTTP stream from server to browser, or WebSocket, a long-lived two-way connection upgraded from an HTTP request) at their points of presence (PoPs) and let the origin publish once to the platform, which fans out. You pay per connection or per message, but the provider absorbs the 5 million sockets.
- Cached polling: clients poll a small JSON document every 2 seconds through the CDN with a 1-second cache lifetime. Clients generate 5,000,000 / 2 = 2.5 million requests per second, but the CDN serves nearly all of them from its edge cache. When the 1-second cache lifetime expires, several client requests can land on the same PoP within the same instant needing a fresh copy; the CDN coalesces those misses, meaning it sends only one request upstream to the origin per PoP and holds the other waiting clients until that single response comes back, instead of forwarding each one. Because the cache is then valid for another second, that PoP does not need to ask the origin again until it expires, so each PoP originates at most about one request per second: with 300 PoPs, about 300 requests per second.
- Cost: per-request or per-GB CDN pricing; often cheaper than running the equivalent gateway fleet at this scale.
- Latency: the cached variant adds up to the poll interval plus cache lifetime (seconds). Edge-held connections approach broker latency.
- When: very large, read-only audiences where 1 to 3 seconds of delay is acceptable, or when you do not want to operate a connection fleet.
Comparison
| Approach | Build and run cost | Latency | State lives in | Best for |
|---|---|---|---|---|
| Origin fan-out | Lowest | Grows with client count | One server | Under tens of thousands |
| Broker pub/sub | Moderate | Milliseconds in-region | Gateways plus broker | One region, up to millions |
| Hierarchical | Higher, scales linearly | One hop per level | Spread across the tree | Global millions |
| Multicast | Low, needs network support | Lowest | Network devices | Controlled networks only |
| CDN-assisted | Pay per use | Seconds (cached) or milliseconds (edge-held) | Provider | Huge read-only audiences |
Recommendation for the live sports case
Hierarchical: one publish to a core broker, per-region relays, edge gateways at about 100,000 clients each, with SSE to browsers since the flow is one-way. Add the CDN cached-polling path as a fallback for clients that cannot hold a connection. What would change it: if 2 seconds of delay is fine for every client, the CDN polling path alone is cheaper and simpler; if the audience is a few thousand traders on your own network, multicast.
Trade-offs and pitfalls
- Slow clients in any tree: a gateway must not let one slow socket delay the rest; use per-connection bounded queues and conflation (for scores, send only the latest value).
- Reconnect storms: a relay failure disconnects its subtree; stagger reconnection with jittered backoff.
- Ordering: each client should see updates in order. Put a sequence number on each update so clients can detect gaps and fetch the missing one.
Design a multi-CDN traffic-steering architecture to optimize availability and cost. Include real-time telemetry ingestion, a steering decision engine that chooses between failover and load-splitting, your chosen steering mechanism and why, and the metrics you would use to evaluate provider performance.
Sample Answer
Direct answer
Collect performance data from real viewers' players, turn it into a score per CDN per network (per country and per ISP), and have a decision engine publish a steering table every minute or so, driven by hysteresis (a required delay, or a threshold a state must clear and hold, before a decision is allowed to reverse, so a brief improvement cannot instantly flip a decision back). For video, apply that table inside the streaming session using manifest-level content steering (the player is given a manifest, the file listing a video's available quality renditions and where to fetch each segment of each one, plus a list of CDN hosts and a steering server it re-checks periodically), with DNS steering as the coarse default for non-video traffic. The engine runs in two modes: load-splitting by weight in normal operation, driven by cost commitments and quality, and failover when a CDN breaches a health threshold for a network, with hysteresis so traffic does not flap (switch rapidly back and forth between two states) between CDNs.
Terms used here
- CDN (content delivery network): a fleet of edge caches that serve content close to viewers. Multi-CDN means contracting two or more and choosing between them per request or per session.
- Steering: deciding which CDN a given viewer uses.
- RUM (real user monitoring): measurements sent ("beaconed") from actual players, as opposed to synthetic probes run from test machines.
- ASN (autonomous system number): the identifier of an ISP's network. CDN performance varies more by ISP than by country, so ASN is the key dimension.
- QoE (quality of experience): what the viewer feels: start time, rebuffering, picture quality.
- Commit: a contracted minimum monthly volume with a CDN. Traffic under the commit is effectively prepaid; traffic above it is charged as overage.
Architecture
flowchart LR
P[Players] -->|RUM beacons| I[Beacon ingest]
S[Synthetic probes] --> I
L[CDN logs and APIs] --> I
I --> A[1-min aggregates<br/>by CDN, country, ASN]
A --> D[Decision engine]
B[Commits and prices] --> D
D --> T[Steering table]
T --> CS[Content steering server]
T --> DNS[Steering DNS]
CS --> P
1. Real-time telemetry ingestion
- RUM is the primary signal because it measures the exact path a viewer uses. Each beacon carries: CDN host, country, ASN (derived server-side from the IP, not trusted from the client), device class, segment (a short chunk, typically a few seconds, of encoded video that a streaming player fetches one at a time) download time and throughput, HTTP errors, time to first frame, rebuffer events.
- Synthetic probes fill gaps where real traffic is thin (a small ISP at 4 a.m.) and detect an outage on a CDN that currently has no traffic steered to it. Without them, a CDN that was failed away from can never prove it has recovered.
- CDN logs and status APIs are the slowest signal (often minutes behind) and are used for billing reconciliation and confirmation, not for the fast loop.
- Ingest at the edge (a lightweight collector), push into a message queue, and roll up in-stream into 1-minute aggregates keyed by
(cdn, country, asn, device_class). Store percentiles as mergeable sketches (for example t-digest, a compact structure that lets you combine partial percentile summaries without keeping every sample).
2. The decision engine: failover versus load-splitting
Per (country, asn) cell, each minute:
- Health gate (failover decision). A CDN is unhealthy in the cell if, over the last 3 minutes with at least 200 samples: segment error rate is above 2%, or rebuffer ratio is above 3x its own 7-day baseline for that cell. Unhealthy CDNs get weight 0 in that cell.
- Quality score for healthy CDNs: a weighted blend of p90 (90th percentile) segment download throughput, time to first byte, and rebuffer ratio, normalised against the best CDN in the cell.
- Cost-aware split: start from a contract plan (for example 60/40) that is on track to meet each commit by month end, then shift weight toward the higher-quality CDN, capped so that no CDN is pushed into expensive overage unless the quality gap exceeds a threshold. Worked example: CDN A has a 3 PB/month commit, CDN B a 2 PB/month commit. Ten days before month end, CDN A has delivered 2.0 PB (67% of commit, on pace) and CDN B has delivered 2.1 PB (105% of commit, already in overage). The plan shifts weight from a 55/45 split toward something like 70/30, so more traffic lands on CDN A (helping it catch up toward its commit) and CDN B's overage stops growing. If CDN B's quality score is clearly better, for example 20% higher p90 throughput, the engine is still allowed to send it some traffic despite the overage, capped at 110% of commit, rather than cutting it off entirely and risking a QoE cliff for the viewers already on it.
- Hysteresis and damping: a CDN must be healthy for 10 consecutive minutes before it gets traffic back, and weights move at most 20 percentage points per minute. This prevents a feedback loop where moving all traffic to CDN B overloads CDN B's local edge, which then looks worse, which moves traffic back.
So the engine does both: load-splitting is the default, and failover is a per-cell override when the health gate trips. A global "all traffic to CDN B" switch exists only as a manual lever, because most CDN problems are regional or ISP-specific.
3. My chosen steering mechanism and why
| Mechanism | How it works | Granularity and speed | Main weakness |
|---|---|---|---|
| DNS steering | Authoritative DNS (the DNS server that holds the real records for a domain, as opposed to a resolver that just looks them up) returns a different CDN hostname per resolver (the DNS server, often run by the viewer's ISP or a public service, that looks up hostnames on the viewer's behalf) location | Per resolver; changes land after the DNS TTL (time-to-live), plus resolvers and devices that cache beyond it | Sees the resolver, not the viewer; cannot move a session already playing |
| Manifest / content steering | The player gets several CDN base URLs and a steering server URL; it re-fetches steering instructions periodically and switches CDN between segments | Per session, mid-stream, within one steering refresh interval | Needs player support (HLS Content Steering, DASH-IF Content Steering) |
| Pure client-side logic | Player measures and switches itself | Per session, instant | Each client sees one sample; no global view of cost or capacity |
Choice: content steering for video, DNS for everything else. Video sessions last an hour and are where cost and QoE concentrate, so they need mid-session moves: when CDN A degrades on one ISP, playing sessions move at the next segment rather than when they restart. The steering server response is tiny and per session, and it can also carry the CDN priority order the player falls back through if a segment fetch fails (that is the "client-side logic" layer, used only as an instant safety net). DNS steering stays for images, APIs and legacy players, and as the fallback if the steering server itself is down.
Worked example: sizing the loop
Assume a peak of 2 million concurrent viewers averaging 5 Mbit/s.
- Delivery volume: 2,000,000 x 5 Mbit/s = 10 Tbit/s. Per hour: 10 x 10^12 bits/s / 8 x 3,600 s = 4.5 x 10^15 bytes = 4.5 PB per hour. At that volume, shifting 10% of traffic between CDNs moves 450 TB per hour, which is why cost steering matters.
- Beacon rate: one beacon per viewer every 30 s gives 2,000,000 / 30 = about 66,700 beacons/s. At roughly 1 KB each that is about 67 MB/s of ingest, which a modest stream pipeline handles.
- Steering server load: if players re-check steering every 300 s, 2,000,000 / 300 = about 6,700 requests/s, each a small cacheable JSON response keyed by
(country, asn). - Reaction time: 1-minute aggregation + 3-minute health window + up to 300 s for players to re-check = worst case about 9 minutes for playing sessions to move after a subtle degradation. Hard failures are faster, because each player's own fallback kicks in on the first failed segment. If 9 minutes is too slow for the business, shorten the steering refresh (the cost is more steering requests), not the health window (which would make decisions on noise).
Metrics to evaluate provider performance
| Category | Metric | Why |
|---|---|---|
| Availability | Segment request error rate (4xx, 5xx, timeouts) per cell | The direct failover signal |
| Throughput | p50 (median, the 50th percentile) and p90 segment download throughput | Sets the bitrate the player can sustain |
| Latency | Time to first byte, manifest fetch time | Drives start time and live-edge latency |
| QoE | Video start time, rebuffer ratio (stall time divided by watch time), average delivered bitrate | What viewers feel; the tie-breaker between two "healthy" CDNs |
| Cache efficiency | Cache hit ratio (the share of requests an edge server answers from its own cache) and origin egress (the bandwidth pulled from origin, the source server behind the CDNs that holds the content those edge caches pull from when they miss) per CDN | Poor hit ratio costs you origin bandwidth even when viewers are fine |
| Cost | Effective cost per GB including commit shortfall or overage | The quality-per-dollar number that sets split weights |
| Steering accuracy | Share of sessions on the CDN the engine intended | Catches players ignoring steering or DNS resolvers caching |
Compare CDNs within the same cell (same ASN, device class, hour) and always on RUM, because a CDN serving mostly fibre users will look better than one serving mostly mobile users for reasons that have nothing to do with the CDN.
Trade-offs and pitfalls
- Flapping is the classic failure. Hysteresis, damping and minimum-sample rules are not optional.
- Self-inflicted overload: failing all traffic onto one CDN can exceed its capacity in a region. Agree burst capacity in contracts and cap per-cell shifts.
- Stale telemetry looks healthy: if beacons stop arriving from a cell, treat that as unknown, not as good.
- Cache warm-up: moving traffic to a cold CDN causes an origin surge. Protect origin with an origin shield (a mid-tier cache in front of origin) per CDN.
- When to prefer simpler: with one dominant CDN and a backup only for disasters, DNS failover alone is cheaper to build; content steering pays off once you split real volume across CDNs.
How would you implement authentication and authorization for long-lived WebSocket connections in a multi-tenant SaaS product? Cover initial token exchange during the handshake, token refresh for long-lived sessions, per-message authorization checks where needed, handling token revocation or tenant deprovisioning (including third-party API consumers, not just browser clients), and techniques to minimize re-auth overhead while ensuring security.
Sample Answer
Direct answer
Authenticate once at the handshake with a short-lived credential, then treat the connection as a session whose authority expires with the token: the client sends a fresh token over the socket before expiry, and the server closes the connection if it does not. Every message is authorized against the tenant bound to the connection at handshake, never a tenant named in the payload, and subscribe or publish actions on specific resources are checked against a cached permission set. Revocation is pushed, not polled: a revocation event reaches every gateway, which closes matching connections within seconds (immediate revocation), while routine cases just refuse the next refresh (soft revocation). Third-party API consumers use the same model with OAuth client credentials and are revocable by client ID.
Key terms
- Authentication (authn): who is this? Authorization (authz): may they do this, to this resource, in this tenant?
- Multi-tenant: many customer organisations (tenants) share the same servers; the worst failure is one tenant seeing another's data.
- JWT (JSON Web Token): a signed token carrying claims, meaning the individual pieces of information encoded inside it (user, tenant, expiry, token ID
jti), that a server can verify locally with the issuer's public key, with no network call. - Token introspection: asking the identity provider (the service, yours or an external one like Okta or Auth0, that authenticates principals and issues tokens for them) "is this token still valid?" over the network; accurate but costly per call.
- Revocation: withdrawing access before a token naturally expires.
- Principal: whoever the token represents, a human user or a third-party client, the thing being authenticated and authorized.
- Scopes: the specific permissions baked into a token (for example "read messages in tenant t9"), narrower than everything that principal could ever do.
- OAuth 2.0 client-credentials flow: the OAuth grant (the authorization a client has been issued) used when the caller is a backend service, not a human. The service authenticates directly with its own client ID and secret, no user or browser in the loop, and gets back an access token scoped to what that service is allowed to do.
- Key set / key ID: the issuer publishes a set of public keys it may sign tokens with; each token names which one it used via a key ID (
kid), so a verifier fetches the matching key instead of guessing.
1. Initial token exchange during the handshake
Browser clients cannot set an Authorization header on the browser WebSocket API (the browser's built-in interface for opening a persistent, full-duplex connection upgraded from HTTP), so pick one of these:
| Option | How | Verdict |
|---|---|---|
| Single-use ticket | Client calls an authenticated REST endpoint, gets a random ticket valid for 30 s and one use, connects to wss://.../ws?ticket=... | My default for browsers: short-lived and useless once redeemed, so a URL that lands in a log is harmless |
| Session cookie | Browser sends cookies on the handshake automatically | Fine for first-party apps, but you must check the Origin header, otherwise any website can open a socket with the user's cookies (cross-site WebSocket hijacking) |
Token in Sec-WebSocket-Protocol | Smuggle the token as a subprotocol value (this header exists so client and server can agree on an application-level protocol name, for example chat.v2, not to carry credentials; some clients abuse it because it is one of the few headers the browser API lets you set) | Works but abuses the header; avoid |
| Long-lived token in query string | ?token=eyJ... | Avoid: URLs end up in proxy and access logs |
Third-party API consumers (a partner's backend, not a browser) can set headers, so they send Authorization: Bearer <access token> obtained through the OAuth 2.0 client-credentials flow, scoped to one tenant and specific permissions. On success the gateway builds a connection context: user or client ID, tenant ID, token ID, scopes, token expiry, and a permission-set version. Everything later reads from this context.
2. Token refresh for long-lived sessions
- Access tokens live for 5 to 15 minutes; the connection may live for hours.
- About a minute before expiry, the client obtains a new token (browsers through their normal refresh flow, third parties by repeating client credentials) and sends it as an in-band
reauthmessage. - The gateway verifies it, checks it names the same principal and tenant (a different tenant is rejected, not swapped), and updates the context's expiry and scopes.
- If no valid token arrives by expiry plus a short grace period (say 30 s), the gateway closes with an application close code in the 4000 to 4999 range, which RFC 6455 reserves for application use (for example 4001 for "reauthentication required" and 4003 for "access revoked"). The client reconnects through the normal handshake.
3. Per-message authorization
- Tenant isolation is structural: channel names and resource IDs are resolved inside the connection's tenant; a message that names another tenant's resource simply finds nothing. Never read the tenant from the payload.
- Subscribe and publish are authorization points: "join channel
project:88" is checked against the user's permissions for project 88. Subsequent messages on that subscription are pre-authorized until permissions change. - Sensitive actions (admin operations, payments, deletes) are re-checked per message, or better, performed through a normal HTTP API where standard authz and audit already exist.
- Outbound filtering: the fan-out path (where one published event is delivered out to every subscribed connection) checks that each recipient connection's tenant matches the event's tenant before sending, as a second line of defence.
4. Revocation and tenant deprovisioning
Every gateway indexes its live connections by user ID, tenant ID, client ID and token ID. Revocation events travel on a control channel (a pub/sub topic every gateway subscribes to).
| Case | Mode | What happens |
|---|---|---|
| Password reset, user logs out everywhere, suspected compromise | Immediate | Event {user: u1} published; each gateway closes u1's connections now; token IDs added to a deny list until their natural expiry so a reconnect with an old token fails |
| Role changed (lost access to one project) | Immediate, narrow | Permission-version bump; gateways drop the affected subscriptions and reload permissions without closing the socket |
| Plan downgrade, routine offboarding | Soft | Mark the principal; the next refresh is refused; access ends within one token lifetime (at most 15 minutes) |
| Tenant deprovisioned | Immediate | Stop issuing tickets and tokens for the tenant; publish {tenant: t9}; every gateway closes all t9 connections, including third-party clients; queued outbound messages for t9 are discarded |
| Third-party app's access revoked by the tenant admin | Immediate | Revoke the OAuth grant (the permission that client-credentials flow issued to that client, independent of any single still-valid token); publish {client: acme-sync, tenant: t9}; close that client's connections in that tenant only, leaving the same app's connections in other tenants alone |
Revocation events must be durable and replayable (a gateway that restarts or was partitioned must read recent revocations before accepting connections), and the deny list must outlive the longest token lifetime.
sequenceDiagram
participant C as Client
participant A as Auth API
participant G as Gateway
participant R as Revocation topic
C->>A: Request ticket with session
A-->>C: Ticket valid 30 s, single use
C->>G: Handshake with ticket
G-->>C: Welcome, context tenant t9
C->>G: reauth with new token before expiry
R-->>G: Revoke tenant t9
G-->>C: Close 4003 access revoked
5. Minimising re-auth overhead
- Verify JWTs locally: signature check against cached public keys (refetch the issuer's key set on unknown key ID), no network call per refresh.
- Authorize at subscribe time and cache the permission set in the connection context, invalidated by version bumps rather than time-based polling.
- Push revocations instead of re-validating every connection periodically.
- Refresh in band on the existing socket rather than reconnecting.
Worked example: why per-message introspection does not scale
A product has 2,000,000 connections and 15-minute tokens.
- In-band refresh load: 2,000,000 / 900 s = about 2,222 token verifications per second across the fleet, each a local signature check.
- If instead every message were checked by introspection at a traffic level of 50,000 messages per second, the identity provider would take 50,000 calls per second, over 20 times the refresh load, and every message would wait on a network round trip.
- Revocation for a tenant with 3,000 connections spread across 40 gateway nodes: one event broadcast to 40 nodes, each closing its local share from an in-memory index. The cost is proportional to the tenant's connections, not to the fleet.
Pitfalls
- Authenticating the handshake and never again, so a fired employee's socket lives for days.
- Trusting a tenant ID inside the message payload.
- Cookie auth without an
Origincheck. - A revocation broadcast that is fire-and-forget, so a gateway that missed it keeps a revoked session alive.
- Forgetting non-browser API consumers, which often hold the longest-lived connections of all.
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.