Skip to content

Pattern: Pushing Realtime Updates

Advanced 57 min read Part 11 of 18

Push changes to users as they happen: pick a protocol, route events to connection servers, track presence, keep order, resume after drops and scale out.

Summary#

Many products must show a change to a user the moment it happens. Examples are a chat message, a new bid, a driver moving on a map, a comment on a live video, a colleague's cursor in a document, or a stock price tick. Pushing realtime updates is the pattern for building this, and every design has two hops. The first hop runs from a connection server to the client. It uses a protocol: polling, long polling, server-sent events (SSE), WebSockets or, for media, WebRTC. The second hop runs from wherever the change happened to the connection server that holds the right client's connection. That hop uses one of three methods. The server can poll a database or log. The system can route by consistent hashing, so everyone knows which server owns which user or room. Or the system can publish to a pub/sub layer, such as Redis Pub/Sub, NATS or Kafka, which the connection servers subscribe to. Around these two hops sit the hard parts:

  • Presence: who is online, and on which server.
  • Ordering and catch-up: sequence numbers, cursors and a durable store, so that a client that drops for ten seconds misses nothing.
  • Scale: millions of long-lived connections, reconnect storms, slow consumers, and "celebrity" fan-out, where one event must reach millions of people.

The golden rule is to store first, then push. The live connection is a fast path, and the durable store is the truth.

Why It Exists#

Normal web traffic is request-response: the client asks and the server answers. That model has no way for the server to speak first. Suppose a user is looking at an auction page and someone else outbids them. The server knows at once, but it cannot tell the user until the user's browser asks again. The product requirement "users see new bids within a second" turns into an engineering question with two parts:

  • How does the server reach a client that did not ask?
  • How does the change, which happened on some other machine, find the one server among hundreds that holds that client's connection?

The simple answers fail quickly at scale.

  • Polling every second is wasteful. Ten million clients polling once a second is 10 million requests per second. Each one carries full HTTP headers, a TLS session, an authentication check and a database or cache lookup, and almost all of them return "nothing new". Polling every 30 seconds is cheap, but it misses the requirement.
  • One server cannot hold everyone. A well-tuned server holds perhaps 100,000 to 1 million mostly idle connections, so 50 million concurrent users need hundreds of servers. Once there are many servers, the sender and the receiver are usually on different machines.
  • Connections are fragile. Phones switch networks, walk into lifts and get suspended by the operating system. Laptops sleep. Load balancers time out idle connections. Servers are redeployed. A realtime design that only works while connections stay up does not work.
  • Fan-out is uneven. Most chats have two members, but some rooms have 100,000. Most streams have 50 viewers, but a World Cup final has tens of millions. A design sized for the average case collapses on the tail.

The pattern exists to answer all of these with a small set of reusable parts. Those parts are a connection tier, a routing tier, a durable store with sequence numbers, and a presence registry, plus rules for ordering, resuming and degrading under load. The same parts appear in WhatsApp, Slack, Discord, Uber's driver app, Figma, Google Docs, trading apps and live-comment systems. That is why interviewers treat realtime updates as a core pattern rather than a niche topic.

How It Works#

Every realtime feature is built from the same pieces, whatever the product. The diagram shows them for a typical chat or notification system.

The flow has a fixed order, and it never changes:

  1. A client sends a change, such as a message, through an ordinary request, either over the socket or as an HTTP POST, to a stateless API service.
  2. The service writes it durably and assigns a sequence number, so the change exists even if every socket is down.
  3. The service, or a change-data-capture process on the database, publishes an event to the routing tier.
  4. The routing tier delivers it to the connection servers that hold the interested clients.
  5. Each connection server writes it to its local sockets.
  6. A client that was offline, or whose socket dropped, catches up from the durable store using its last sequence number when it reconnects. A user with no live connection at all gets a mobile push notification instead.

The rest of this section climbs through each piece. It covers the client protocol, the routing tier, consistent hashing, presence, ordering and catch-up, the connection tier at scale, and huge fan-out. It ends with a worked example.

Hop one: the client protocol, a recap#

The protocols are covered in full in Real-time Communication. Here is the short version, with the server-side consequence of each choice, because that consequence is what matters for the pattern.

ProtocolHow it worksDirectionServer-side consequenceFits
Short pollingClient asks every N secondsClient pullsStateless servers; load grows with clients ÷ interval, whether or not anything changedLow-rate updates, dashboards, MVPs
Long pollingServer holds the request until there is news or a timeout of about 30 s, then the client asks againServer answers lateA held request per client; looks like normal HTTP to proxiesFallback when sockets are blocked; moderate rates
Server-sent eventsOne long HTTP response that streams data: lines; the browser reconnects itself and sends Last-Event-IDServer to client onlyA long-lived stream per client; resume is built into the protocolFeeds, live comments, scores, token streaming for chatbots
WebSocketHTTP upgrade to a full-duplex framed TCP connectionBoth waysA stateful socket per client; you write heartbeats, resume and routing yourselfChat, games, collaboration, trading
WebRTCPeer-to-peer UDP-based media and data channels, after signalling through a serverPeer to peerServers only for signalling, STUN and TURN relays, or an SFU for group callsVoice, video, low-latency peer data

Three rules of thumb guide the choice:

  • Start with polling if the update rate and the latency target allow it. Polling every 5 to 10 seconds against a cached endpoint is cheap and very robust. It survives every proxy, and it needs no connection tier at all.
  • Choose SSE when updates flow mostly one way, from server to client, and the client's own actions are rare enough to send as normal HTTP requests. Live comments, price feeds, notifications and LLM token streams fit this shape. SSE runs over plain HTTP, so it passes through most infrastructure, and HTTP/2 lets many streams share one connection.
  • Choose WebSockets when both sides talk often, as in chat with typing indicators and read receipts, multiplayer games, or collaborative editing with cursor positions.

Hop one, in depth#

Why SSE often beats WebSockets for read-heavy feeds. A live-comment system might have 1 million viewers and 500 comments per second. Almost all the traffic flows from server to viewers, and a viewer posts a comment perhaps once an hour. A bidirectional socket per viewer pays for a capability the viewer almost never uses. SSE keeps the hot path one-way. It also gives automatic reconnection with Last-Event-ID for free, and it is plain HTTP that ordinary CDNs, proxies and observability tools understand. Comments are posted with an ordinary POST, which can be rate-limited, authenticated and cached like any other API call. SSE has costs too:

  • Some proxies buffer streaming responses, so nothing reaches the client until a buffer fills. You need to disable buffering, for example with X-Accel-Buffering: no on NGINX, and send periodic comment lines as keepalives.
  • Over HTTP/1.1, browsers allow about six connections per domain. A user with several tabs, each holding a stream, can exhaust them. HTTP/2 multiplexing removes this limit.
  • SSE carries only UTF-8 text, so binary payloads must be encoded.

What WebSockets make you build. A WebSocket gives you a raw, ordered, bidirectional pipe and nothing else. In practice every production WebSocket system adds the same layer on top:

  • An application protocol: message types, request IDs to match replies to requests, and versioning.
  • Heartbeats: application-level ping and pong. The WebSocket protocol has control-frame pings, but browsers cannot send them from JavaScript, and many systems prefer application messages they can see and measure.
  • Acknowledgements and resume: per-message or per-batch acks, and a cursor on reconnect.
  • Authentication refresh: a token sent at connect time may expire while the socket lives for hours. The server must re-check, or the client must send a new token over the socket.
  • Backoff and jitter on reconnect.

Libraries such as Socket.IO, Phoenix Channels, SignalR and Centrifugo package these pieces. Managed services such as Pusher, Ably, AWS API Gateway WebSockets, AWS AppSync and Firebase sell them as a service.

Mobile is different. iOS and Android suspend background apps and close their sockets after a short time to save battery. A persistent connection therefore exists only while the app is in the foreground. Delivery to a phone in a pocket must go through the platform push services: Apple Push Notification service (APNs) and Firebase Cloud Messaging (FCM). Every mobile realtime design needs both paths: the socket for the foreground, and push notifications for the background. The presence registry decides which one to use.

Protocols beyond the browser. Facebook has said publicly that Messenger used MQTT, a lightweight publish-subscribe protocol designed for unreliable networks, on its mobile apps, to save battery and bandwidth. Internal service-to-service streaming often uses gRPC streams over HTTP/2. Uber's engineering blog has described a push platform for its apps that moved from SSE to gRPC bidirectional streaming. Newer options include WebTransport, a successor-style API over HTTP/3 and QUIC that offers multiple streams and unreliable datagrams. These choices change the hop-one framing, but not the architecture behind it.

The cost of polling, worked out. Polling is not wrong; it is a trade of load for latency. Suppose there are 2 million active users and the target is that updates appear within 10 seconds:

  • Polling every 10 seconds is 200,000 requests per second. With a 1 KB request and response and an edge cache absorbing most of them, that is manageable. It may well be cheaper than running a connection tier.
  • To get 1-second freshness, polling costs 2 million requests per second, ten times more, while a push design delivers only the actual changes.

The crossover depends on how often anything changes. If most polls would return data, polling is efficient. If most return nothing, push wins. This is why the reference advice is to start with polling and move to SSE or WebSockets when polling stops serving the need.

Hop two: getting the event to the right connection server#

Once there is more than one connection server, the central problem is routing. User A's message lands on an API server. User B is connected to gateway 47 of 300. How does the message get to gateway 47? Two tempting answers fail first.

  • "Just add servers behind a load balancer." A load balancer spreads connections, but it does nothing to route a later event to the server that holds a given connection. The server that accepts A's message usually does not hold B's socket. The message is simply undeliverable. Never propose this on its own.
  • "A Kafka topic per user." Kafka keeps metadata, files and replication state for every partition, so it is built for thousands of topics and partitions, not billions. The WhatsApp reference estimates tens of kilobytes of overhead per topic, which would mean tens of terabytes of overhead for a billion users before a single message is stored. Grouping users into "super topics" per gateway starts to rebuild one of the real solutions below, badly.

The workable answers are three. They differ in who knows where a user is.

Option 1: pull, where connection servers poll the source#

The simplest routing is none at all. Each gateway periodically asks the source "anything new for the keys I hold since my last check?". The source can be a database table, a cache, or a log. The client protocol can still be a push protocol: the gateway polls, and then pushes to its sockets.

  • When it fits: updates are infrequent, a delay of seconds is acceptable, or the source is a partitioned log such as Kafka that gateways can tail cheaply. Examples are job-status dashboards, order tracking, and a gateway serving one stock exchange feed.
  • Why it breaks: the load is gateways × keys per gateway ÷ interval, and it does not depend on how many changes actually happen. Three hundred gateways each holding 100,000 users and polling every second generate a 30-million-key read load per second, nearly all empty. Batching keys per query helps, but the latency floor is still the poll interval.

Option 2: push via pub/sub#

Here a pub/sub system sits between the publishers and the gateways, and the publishers never need to know where a user is.

  1. On connect, the gateway subscribes to a channel for the user, such as user:B, or for each room or video the client watches. The gateway keeps an in-memory map from channel to local sockets.
  2. On an event, the publisher sends it to channel user:B. The pub/sub layer forwards it to every subscribed gateway, which is usually one, or several if B has several devices on different gateways.
  3. The gateway looks up its local sockets for that channel and writes the event to each.
  4. On disconnect, the gateway unsubscribes.

The strength of this design is that gateways are interchangeable. A client can connect to any gateway, so plain least-connections load balancing works. Losing a gateway only means its clients reconnect elsewhere and resubscribe. Adding gateways needs no coordination. Its costs are an extra network hop, usually a millisecond or two inside a data centre, and a pub/sub cluster that must scale with the total message rate and the number of subscriptions.

The pub/sub layer is deliberately "dumb", and that is a feature. Redis Pub/Sub keeps no messages. A channel is little more than an in-memory list of subscriber connections, so creating a billion channels over time costs almost nothing, and a publish is a hash lookup plus a socket write. The price is at-most-once delivery. If a gateway is not subscribed at the moment of the publish, because it is reconnecting, restarting or slow, the message is gone. This is acceptable only because the message was written durably before it was published. A client that misses a live push gets the message from the store on its next sync. The write path is therefore always:

  1. Write the message and inbox entries durably.
  2. Acknowledge the sender.
  3. Publish for live delivery, as a best effort.

If step 3 fails, nothing is lost; delivery is only delayed. The reference cites a Canva engineering benchmark of about 100,000 cursor-position updates per second on one Redis host at roughly a quarter of its CPU. That is a reminder that a dumb relay is very efficient.

Pub/sub, in depth#

Which pub/sub system. The choice turns on persistence, subscription churn and fan-out shape.

SystemDelivery and storageSubscription churnNotes
Redis Pub/Sub, classicAt most once, nothing storedVery cheap; subscribe and unsubscribe freelyIn Redis Cluster, classic PUBLISH is broadcast to every node over the cluster bus, so throughput does not grow with nodes
Redis sharded pub/sub, Redis 7.0 and laterAt most onceCheapSSUBSCRIBE and SPUBLISH hash the channel to one shard, so throughput scales with shards
Redis StreamsStored, with consumer groups and IDsModerateGives replay by ID; useful as a short catch-up buffer per room
NATS core, and JetStreamAt most once in core; JetStream adds storage and replayVery cheapSubject wildcards such as room.*.msgs; a common choice for gateway fan-out
KafkaDurable, ordered per partition, replayableExpensive: consumer-group rebalances, fixed partitionsExcellent as the durable event backbone; poor for a channel per user or per viewer
Managed: Google Pub/Sub, SNS, Azure Web PubSub, Ably, PusherVariesVariesRemove the operations work at a price per message or per connection

A common production shape uses both kinds. Kafka, or the database's change log, is the durable source of truth, partitioned by conversation or room. A fan-out service consumes it and publishes into a lightweight pub/sub layer, such as Redis or NATS, keyed by user or room, and the gateways subscribe there. Kafka provides order and replay, and the light layer provides cheap, dynamic subscriptions. The reference makes the same point: Kafka struggles when viewers constantly switch videos, while Redis handles dynamic subscriptions well.

Partition channels by user or by room? This is a classic follow-up question. The answer depends on two numbers: how many rooms a user belongs to, and how large the rooms are.

  • One-to-one chats, with 250 chats per user. Channels per room would force each gateway to subscribe to 250 channels per connected user, and a message is still published only once. Channels per user mean one subscription per user and one publish per recipient. Per user wins.
  • Large rooms, with 1 room of 100 members per user. Channels per user turn every message into 99 publishes. Channels per room mean one publish, and each gateway subscribes once per room it serves. Per room wins.

WhatsApp-like products are dominated by one-to-one and small group chats, so per-user channels are the default. The large-room tail can be handled adaptively. Rooms above a threshold, say 25 to 100 members, get their own channel. Gateways subscribe to the room channels of their connected users in addition to the per-user channel, and publishers send large-room messages to the room channel only. When a room grows past the threshold, publishers should send to both channels for a short overlap period, so gateways have time to subscribe before the per-user path is turned off.

The cost model. For a design review, it helps to write down the work:

  • Subscriptions held = connected users × channels per user.
  • Publishes per second = messages per second × channels per message.
  • Deliveries per second = messages per second × average recipients online.

Per-user channels minimise the first number and inflate the second for large rooms. Per-room channels do the opposite. Deliveries are fixed by the product, and the gateway does that work either way.

Gateway fan-out, not user fan-out. When 10,000 viewers of one stream are spread across 200 gateways, per-room channels mean the pub/sub layer delivers each comment 200 times, once per gateway, and each gateway fans out to its own 50 sockets from memory. That is a 50-fold reduction in pub/sub traffic compared with per-viewer channels. It is the single most important trick for broadcast-style traffic.

A dispatcher instead of subscriptions. The live-comments reference describes an alternative that inverts pub/sub. A dispatcher service keeps a map of which gateways currently serve viewers of each video, kept fresh by gateway registration and heartbeats and stored in ZooKeeper or etcd. Publishers ask the dispatcher, and the dispatcher forwards each event directly to the right gateways. This centralises routing logic, which makes load-aware routing easy, and removes subscription management from the gateways. The cost is keeping the map accurate during sudden churn, such as a viral stream, and keeping the caches of many dispatcher instances consistent. Pub/sub is usually simpler and has fewer corner cases. It is the better default in an interview, with the dispatcher as a credible alternative.

Option 3: push via consistent hashing to an owning server#

The third option makes location computable. Every user, room or document has exactly one owning server, chosen by hashing its ID onto a consistent hash ring of servers. Two things follow from that.

  • Clients connect to their owner. A lookup service tells the client which server to use, or an L7 load balancer hashes on the ID in the request path or a header. NGINX and Envoy both support hash-based upstream selection.
  • Events go straight to the owner. Any service that has an event for key K computes owner(K) from the same ring and sends the event directly to that server, with no broadcast. The owner then writes it to the local sockets.

The ring itself is small shared metadata: the list of servers, their addresses, and the hash ranges or virtual nodes each owns. It lives in a coordination service such as ZooKeeper or etcd, and every participant watches it for changes. See Consistent Hashing and Leader Election and Coordination.

Why bother, when pub/sub is simpler? Because some realtime systems are stateful by nature, and those benefit from having all the clients of one key on one machine:

  • Collaborative documents. With Google Docs-style operational transformation, one server per document orders every edit and transforms concurrent operations against each other. If all editors of a document connect to the same server, the operation log, the current document state and the cursors all live in that server's memory. Figma has described a similar shape publicly: one multiplayer process per open file holds the document state and relays changes.
  • Game rooms and matches. The authoritative game state ticks in one place.
  • Order books and auctions. One owner per instrument or auction serialises bids, so "highest bid wins" is decided in memory, with no distributed lock.
  • Live video comments with co-location. Hashing on the video ID sends all viewers of one video to the same few servers, so each server subscribes to few channels, instead of every server subscribing to everything.

The reference's ticketing example shows why the hashing must be consistent. With hash(id) % N, growing from 3 to 4 servers remaps about three-quarters of all keys. In a realtime system that means three-quarters of all users are suddenly connected to the wrong server and must reconnect at once. With a ring, adding a server moves only the keys in the ranges it takes over, about 1/N of them. Virtual nodes, many points per server, spread those moved keys across every existing server instead of one neighbour. Virtual nodes fix structural imbalance, an uneven split of keys. They do not fix workload imbalance, where one key is simply hot. A celebrity's room is still on one server, which is why huge rooms need the fan-out techniques described later.

Consistent hashing, in depth#

Rebalancing a stateful ring without dropping messages. Adding or removing a server is the hardest operation in this design, because ownership moves while traffic continues. A safe procedure looks like this:

The key ideas are these:

  • Version the ring. Every message carries the ring version its sender used. A server that receives an event for a key it no longer owns forwards it, or rejects it so the sender refreshes its copy of the ring.
  • Overlap ownership. During the move, publishers send events for the moving ranges to both the old and new owners. Clients are therefore covered whichever server they are on at that moment, and their sequence numbers deduplicate the copies.
  • Drain clients gradually. The old owner tells clients to reconnect over a window of a minute or more, with random jitter. This prevents a thundering herd, where tens of thousands of reconnects arrive in the same second.
  • Hand over state, not just sockets. For stateful rooms, the new owner loads a snapshot plus the log after it before it accepts writes. Two servers must never accept writes for the same document at once. Fencing by ring version, with stale-version writes rejected, prevents this split-brain.

Variants of the hash. Several refinements of the basic ring are worth knowing:

  • Rendezvous hashing, also called highest-random-weight hashing (David Thaler and Chinya Ravishankar, IEEE/ACM Transactions on Networking, 1998), scores every server for a key and picks the highest. It needs no ring and has similar minimal movement.
  • Consistent hashing with bounded loads (Vahab Mirrokni, Mikkel Thorup and Morteza Zadimoghaddam, SODA 2018) caps each server at (1 + ε) times the average load and passes overflow keys to the next server on the ring. Google described using it for load balancing, and HAProxy implements it. For connection servers, a cap keeps a cluster of hot keys from overloading one machine.
  • Explicit placement tables. Instead of hashing, a placement service assigns keys or ranges to servers and stores the map in etcd. This costs a lookup, cached by clients, but it allows moving one hot room on its own.

The full-mesh problem. In a pure hash design, any server may need to send to any other, so each server keeps connections to all the others. For 300 servers that is about 45,000 server-to-server links, so the design favours fewer, bigger servers. Large systems put a thin, stateless gateway tier for client sockets in front of a smaller stateful tier of hash-placed room servers.

Slack and Discord, as publicly described. Slack's engineering blog has described exactly this split. Gateway servers hold the WebSocket connections and subscribe on behalf of each client to the channels it belongs to. Channel servers are stateful servers that own channels, placed by consistent hashing. A message is sent once to its channel server, which forwards it to every gateway subscribed to that channel. The same blog describes separate admin and presence services. Discord has described running each guild, its word for a community server, as an Elixir process placed on a node by a hash ring. A guild process fans each event out to the session processes of connected members, and Discord built a library called Manifold to batch these sends across nodes. Both companies arrived at the same shape: a stateless edge for sockets, plus hash-placed owners for the stateful keys.

Presence: who is online, and where#

Presence means knowing, for each user, whether they are online, and in this pattern also which gateways hold their connections. It drives three different things:

  • Routing: deliver over the socket, or fall back to a push notification.
  • Product features: green dots, "last seen", and typing indicators.
  • Capacity work: the count of connected users per gateway.

The basic mechanism is a heartbeat with a time-to-live:

  1. On connect, the gateway writes presence:user:B = {gateway: 47, device: phone, since: t} to a fast store such as Redis, with a TTL of, say, 60 seconds.
  2. Every heartbeat, a ping and pong every 20 to 30 seconds, the gateway refreshes the TTL. Gateways batch refreshes for all their users into pipelined writes.
  3. On a clean disconnect, the gateway deletes the entry. On a dirty disconnect, such as a lost phone signal or a crashed gateway, the entry simply expires.
  4. Readers ask the store, or subscribe to presence changes for the users they care about.

The grace state matters. Phones drop and reconnect constantly, and showing "offline" then "online" every few seconds both looks broken and floods every friend with presence updates. Only when the grace timer expires does the system publish "offline" and write a last-seen timestamp. LinkedIn's engineering blog described its presence platform this way: periodic heartbeats keep a user online, and the offline event is published only after a delay, so short disconnections never become visible.

Presence, in depth#

Presence fan-out is the real cost. Storing who is online is cheap. Telling everyone who cares is expensive. If each user has 300 contacts, and each user goes online or offline 20 times a day, then 100 million daily users generate 100 M × 20 × 300 = 600 billion potential presence notifications a day. That is about 7 million per second, far more than the actual messages. Large systems cut this in several ways:

  • Lazy presence: fetch presence only for contacts on screen, such as the open chat or the visible part of the contact list, and subscribe only to those.
  • Coarse presence: for big rooms, show "1,240 online" from a counter or a HyperLogLog-style sketch rather than a list of who.
  • Debounce and batch: the grace period, plus batching changes into one update per few seconds per subscriber.
  • No presence for very large groups: many products simply do not show it.

Last seen without write amplification. Writing last_seen = now() to a database on every heartbeat is 200 million connected users ÷ 20 seconds = 10 million writes per second, for data that is stale the moment it is written. The WhatsApp reference describes a much cheaper approach that uses the connection itself:

  • While a user is connected, the truthful answer is "online", and only the user's gateway knows it. A request for B's status is published to B's channel. If B's gateway holds B, it replies "online" to the requester's channel.
  • In parallel, the requester's gateway reads B's last_disconnect from a durable table, such as DynamoDB, and sends that. The client shows "online" if that reply arrives, and otherwise the last-disconnect time.
  • The table is written only on disconnect, with a conditional write such as "only if the new time is later", so two gateways racing cannot overwrite a newer value with an older one. Writing on connect as well covers gateways that crash before recording disconnects.

Multiple devices. A user may be connected from a phone, a laptop and a tablet, on three different gateways. Presence becomes a set of (device, gateway) entries, and "online" means the set is not empty. Delivery must reach every device, so either each gateway subscribes to user:B for its device, or messages go to a per-device inbox. The latter keeps each device's sync position separate, so a laptop that was off for a day catches up independently of the phone. A limit on devices per account, such as a handful, bounds storage and fan-out. WhatsApp has publicly described a limit for companion devices.

Presence without a central store. Phoenix Presence, in the Elixir Phoenix framework, replicates presence across nodes with a CRDT-based tracker, so each node knows the cluster-wide presence of a topic with no central database. A failed node's entries are removed when the others detect its failure. This trades exactness, since nodes converge after a short delay, for having no single point of failure. See Collaborative Editing and CRDTs for how CRDTs merge.

Ordering and catching up after a reconnect#

Realtime delivery is lossy by design. Sockets die, the pub/sub layer is at-most-once, and gateways restart. Correctness therefore comes from the durable store plus sequence numbers, not from the live path. The rules are these:

  1. Every event gets a server-assigned, monotonically increasing sequence number within some scope, such as per conversation, per room, per document or per user.
  2. The client remembers the last sequence number it has applied in each scope, in local storage on the web or app storage on mobile.
  3. On every reconnect, the client sends its cursors, and the server replays everything after them from the store before switching to live events.
  4. Clients deduplicate by sequence number or event ID, so a replayed event that also arrives live is applied only once.
  5. Gaps are detected and filled. A client holding 41 that receives 43 knows 42 is missing and fetches it.

Subscribe first, then read. The order of the two steps in the diagram matters. If the gateway read history first and subscribed afterwards, an event published between the read and the subscribe would be in neither: a silent gap. Subscribing first, buffering, reading history, and then flushing buffered events above the last replayed sequence number closes the window. Some events may appear twice, but the sequence numbers remove the duplicates. This is the same reasoning as starting change data capture before taking a snapshot, covered in Change Data Capture.

SSE's built-in resume. SSE standardises this. Each event carries an id: field. When the browser reconnects automatically, it sends the last ID in the Last-Event-ID header, and the server replays from there. With WebSockets the same thing is done by hand, with a resume message carrying cursors. A client can also catch up with an ordinary HTTP call, such as GET /rooms/9/events?after=41&limit=100, which is easy to cache and paginate, and then open the live stream.

Bounded replay. Replay must have limits:

  • Bound it. Keep a recent-events buffer per room in a shared cache, such as a Redis list or stream, capped at the last few minutes or the last N events. Any gateway can then serve replay, which matters because a reconnecting client usually lands on a different gateway.
  • Fall back to a full sync. If the cursor is older than the buffer, return a "too far behind" response, and the client reloads a snapshot. For a chat, that is the latest page of messages plus unread counts. For a live-comment feed, replaying an hour of comments is pointless, so jump to live and show "you missed 300 comments".
  • Pace the replay. For human-facing feeds, the client can animate missed items at two to three times normal speed rather than dumping them all at once.

Ordering and catch-up, in depth#

What order do users actually need? Global ordering across all events is almost never required, and it would force every event through one sequencer. Products need order within a scope:

  • Per conversation, room or document: messages in a chat appear in the same order for every member. A per-scope counter does this, issued by the room's owning server, by a database sequence on the conversation row, or by Redis INCR room:9:seq. Partitioning a Kafka topic by conversation ID gives the same per-conversation order for the durable log.
  • Per user, across scopes: a single counter per recipient makes gap detection global. If a heartbeat says "your sequence is 1,207" and the client has 1,203, it is missing four events, whichever chats they were in. This is the trick the WhatsApp reference rates highest. It piggybacks the recipient's current sequence on each heartbeat, so a missed push is detected within one heartbeat interval at no extra cost. The price is an atomic counter per user on the write path.
  • Causal order, where replies come after what they reply to, falls out of per-room sequencing, because a reply is written after the message it replies to.

Three ways to detect missed pushes, combined. In production these are layered:

  • Gap detection on arrival catches losses as soon as the next event arrives, but not when the conversation goes quiet after a lost message.
  • A sequence piggybacked on heartbeats catches quiet-period losses within one interval.
  • A periodic sync poll every 30 to 60 seconds is the backstop for anything else. It costs about connected users ÷ interval queries: 200 million users ÷ 30 s is nearly 7 million cheap queries per second, so long intervals and cheap "anything since N?" checks matter.

Accepting imperfect order. The WhatsApp reference makes a candid point: strictly reordering messages that arrive out of order needs buffering and waiting for late arrivals, and users would rather see messages immediately. So chat systems stamp each message with the server receive time, or a server sequence, and every client sorts by that stamp. Occasionally a message "pops in" above one it arrived after, which users accept. Stream processors make the opposite choice, waiting for watermarks before emitting results, because their consumers need completeness more than speed. See Batch and Stream Processing. Never order by client clocks, because phone clocks drift by seconds or more. Use the client timestamp only for display, such as "sent at 10:41".

Idempotent sends. The reverse direction needs care too. A client that sends a message and loses its connection before the acknowledgement will resend it. Each outgoing message therefore carries a client-generated ID, and the server deduplicates on it, so the retry returns the original sequence number instead of creating a duplicate. See Idempotency.

Detecting dead connections#

A socket can look open while being dead: a phone loses signal without sending a TCP close, or a NAT box silently drops its mapping. TCP keepalives detect this only after minutes by default, while the user stares at a "connected" app and receives nothing. The options, from worst to best:

  • Rely on TCP timeouts. Detection takes minutes. This is not acceptable for chat.
  • Acknowledgement timeouts. The server expects a client ack for each pushed message within 0.5 to 2 seconds. It retries a few times, then closes the socket so the client reconnects and syncs. This only detects failures while traffic is flowing.
  • Application heartbeats. The server pings every 10 to 30 seconds and closes the connection if no pong arrives within about 5 seconds. Detection is bounded by interval plus timeout, so a 10-second interval and a 5-second timeout detect any dead connection within 15 seconds. The cost at 200 million connections and a 10-second interval is 20 million tiny ping-pongs per second across the fleet. That is real but affordable, and it often exceeds the actual message rate.

The client runs its own timer too. If it hears nothing, not even a ping, for two intervals, it assumes the connection is dead and reconnects. Without this, half-open connections can persist on the client side.

Scaling to millions of connections#

A connection tier is a fleet of gateways whose job is to hold sockets. They authenticate, heartbeat, subscribe and write bytes. Scaling it is mostly about memory, file descriptors, the operating system and connection churn, rather than CPU.

How many connections per server. Ports are not the limit. The common belief that a server tops out at 65,535 connections is a myth. A TCP connection is identified by the four values source IP, source port, destination IP and destination port. A single listening port therefore accepts connections from millions of distinct client addresses. The real limits are these:

  • Memory per connection. Kernel socket buffers, TLS session state, and the application's per-connection objects add up to roughly 10 to 50 KB with tuned buffers, and much more with defaults. At 30 KB, 500,000 connections use 15 GB.
  • File descriptors. Each socket is one, so raise ulimit -n and fs.file-max far above the default of 1,024.
  • CPU for TLS handshakes and heartbeats. Handshakes are costly at reconnect time, so use session resumption, and the 1.3 versions of TLS with fewer round trips.
  • An event-driven runtime. Use epoll on Linux or kqueue on BSD, with one thread watching thousands of sockets. Node.js, Go, Netty, Erlang and Elixir on the BEAM, and Rust's tokio all work this way.

Public figures show the ceiling. WhatsApp described more than 2 million connections per server on Erlang and FreeBSD in 2012, and the Phoenix team demonstrated 2 million WebSocket connections on one large machine in 2015. Production fleets usually run each gateway at 100,000 to 500,000 connections, leaving headroom for reconnect storms and for losing a zone.

Keep gateways thin. A gateway deploy disconnects every client on it, so the less code it holds, the less often it is deployed. Business logic belongs in stateless services behind the gateways. The gateway authenticates, maintains subscriptions, heartbeats, writes to sockets, and forwards client messages to services.

Load balancing long-lived connections. Connections are balanced when they are opened, not per message. That has consequences:

  • A newly added gateway receives nothing until clients connect, so autoscaling responds slowly, and connection count, not CPU, is the scaling signal.
  • Use least-connections balancing, and idle timeouts on the load balancer comfortably above the heartbeat interval.
  • Some systems recycle connections deliberately every few hours, by having the server close a random fraction with a reconnect hint, so load evens out and old code versions drain.
  • For hash-routed designs, the load balancer hashes on the room or user ID, or a lookup service returns a gateway address.

Reconnect storms. When a gateway holding 200,000 clients dies, all 200,000 try to reconnect. If they all retry after exactly 1 second, the remaining gateways and the authentication service receive 200,000 TLS handshakes and token checks in one second. Exponential backoff with full jitter spreads them: wait a random time between 0 and min(cap, base × 2^attempt). With the first retry spread over 0 to 5 seconds, the peak drops to about 40,000 per second, and with 30 seconds to under 7,000. The same applies after a regional failover, a load balancer restart or a mass app update. Servers can also shed load at connect time, returning "retry after N seconds" when the connect rate exceeds a budget.

Slow consumers and backpressure. A client on a poor network reads slowly, so its server-side send buffer grows. With 100,000 connections, a few thousand slow ones can exhaust gateway memory. Gateways therefore need:

  • A cap on per-connection queued bytes or messages. When the cap is exceeded, either drop or coalesce events, sending only the latest value of a price or a cursor, or disconnect the client so it resyncs from its cursor.
  • No blocking of the fan-out loop on one socket. Each write is non-blocking, and a full socket buffer means the event is queued or dropped, never waited for.
  • Metrics on buffer sizes, drop counts and disconnect reasons.

Fan-out to millions: celebrities and mega-streams#

Huge fan-out is a different regime. Suppose 20 million people watch one stream and post 5,000 comments per second. The reference puts it vividly: that is the length of War and Peace every half-minute, and with 20 comments on screen each one is visible for about 4 milliseconds. No human can read it. At that point the requirement itself changes. Viewers want the feeling of a crowd, not every message.

The techniques, roughly in order of how far they go:

  • Publish to gateways, not users. As described earlier, one publish per gateway, then local fan-out from memory. This is necessary but not sufficient at this scale.
  • Relay trees. The source sends to 20 relays, each of which sends to 25 gateways, so no single node fans out to more than a few dozen peers. Discord's Manifold batches cross-node sends in the same spirit.
  • Sampling. Choose a sampling rate based on comment velocity, so each viewer receives a roughly constant 10 to 20 comments per second however fast comments arrive. That might be 50% at 100 per second and 1% at 5,000 per second. Prefer comments from people the viewer follows, popular comments, and verified accounts over pure random sampling.
  • Coalescing to the latest value. For state rather than events, such as a score, a price, a viewer count or a bid, send only the newest value every 100 to 500 ms. Intermediate values are skipped harmlessly.
  • CDN snapshots. For the largest streams, stop pushing altogether. Keep a ring buffer of the latest 100 to 200 comments, write a snapshot every second to the CDN origin, and let clients poll the CDN each second. CDNs exist precisely to serve the same small object to millions of clients, so the realtime tier is barely touched. The client spaces the new comments over the next second using their timestamps, so the feed looks continuous. Latency rises from under 200 ms to 1 to 2 seconds, which does not matter at this volume. The user's own comments are inserted locally and immediately, to preserve read-your-writes. The switch between push mode and snapshot mode needs hysteresis, for example entering above 100,000 viewers and leaving below 70,000, so a stream hovering at the threshold does not flap.
  • A notify-then-fetch split. For data that is the same for everyone, push a tiny "version 812 is available" signal and let clients fetch the payload from a cache or CDN, with a random delay of up to a second or two so the fetches do not all land in the same millisecond.

The same shape answers "a user with millions of followers posts something" in feed systems. Push a notification to the followers who are online and looking, and let everyone else see the post when they next load their feed. This is the hybrid push-pull model described in Pattern: Scaling Reads and in the news feed case study.

Security, multi-region and the edges of the pattern#

Authorise subscriptions, not just connections. Authenticating the socket at connect time proves who the user is. It does not prove they may watch auction 9 or join room 77. Every subscribe request must be checked against permissions, and membership changes must be enforced on live connections. When a user is removed from a channel, the server must unsubscribe their gateway immediately, or they keep receiving messages over a socket that was opened while they were still a member. Tokens expire while sockets live for hours. Either the server closes the socket at token expiry, so the client reconnects with a fresh token, or the client sends a refreshed token over the socket before expiry.

Protect the inbound direction. A WebSocket is an open pipe into your system. Apply per-connection rate limits on client messages, a maximum frame size, and schema validation, exactly as for an HTTP API. Check the Origin header on WebSocket upgrades to block cross-site WebSocket hijacking, because browsers send cookies on the upgrade request. See Rate Limiting and Security Fundamentals.

Multi-region. Users connect to the nearest region for low latency, but the people they talk to may be anywhere. Two shapes are common:

  • Home region per room or conversation. Writes for a room go to its home region, which assigns sequence numbers. Events are replicated to other regions, whose gateways deliver them locally. Order stays simple, at the price of a cross-region hop for remote writers, typically 50 to 150 ms.
  • Global event bus. Every region publishes to a replicated log, for example Kafka replicated between regions with MirrorMaker 2, and every region's fan-out tier consumes all of it. That is simple to reason about for broadcast data. Sequence numbers must still come from one place per scope, or clients must tolerate per-region orderings.

Presence registries are usually per region, with a global lookup only when routing a message to a user in an unknown region. See Multi-Region Data.

Webhooks are realtime for servers. When the recipient is another company's server rather than a person, push means webhooks: an HTTP POST to a registered URL, signed, retried with backoff, and deduplicated by event ID. The pattern's rules still apply: store first, give events IDs, and offer a way to replay missed events.

Worked example: a live auction site#

The problem. An auction site runs about 50,000 live auctions at peak, with 2 million concurrent viewers. Viewers must see each new highest bid within 500 ms, and bidders need instant confirmation. One celebrity charity auction attracts 600,000 viewers and 3,000 bid attempts per second in its final minute. Viewers also see a live viewer count and a comment stream.

Step 1: the client protocol. Viewers mostly receive, so the stream is SSE: price updates, comments and the viewer count, each event with an ID. Bids are rare, important and need a synchronous answer, so they are an ordinary POST /auctions/:id/bids with an idempotency key. This keeps rate limiting, authentication and retries on the well-understood HTTP path. Mobile apps use the same SSE endpoint in the foreground, and push notifications for "you have been outbid" in the background.

Step 2: the bid path, with ordering by ownership. Correctness lives here. Each auction is owned by one bid server, chosen by consistent hashing of the auction ID over a ring stored in etcd. The owner holds the auction state in memory: current price, high bidder and end time. It validates each bid against that state, writes accepted bids to the database with a per-auction sequence number, and only then publishes a price event. Because one owner serialises all bids for an auction, there is no distributed lock and no race over "who bid highest". The single-writer principle gives order for free. With 50,000 auctions over 40 bid servers, each holds about 1,250 auctions. The celebrity auction's 3,000 bids per second are trivial for one in-memory owner: an in-memory comparison and a batched database write per bid.

Step 3: fan-out. The bid server publishes to channel auction:<id> on a sharded Redis pub/sub cluster (SPUBLISH). The gateways subscribe to the channels of the auctions their viewers watch:

  • 2 million viewers ÷ 200,000 per gateway = 10 gateways, or 16 with headroom for losing a zone and for reconnects.
  • The load balancer uses least-connections, not hashing, so gateways stay interchangeable. With 50,000 auctions on 16 gateways, each gateway subscribes to at most a few thousand channels.
  • Each price change is delivered once per gateway that has a viewer of that auction, at most 16 deliveries, and then fanned out locally.

Step 4: the hot auction. 3,000 bid attempts per second become perhaps 500 accepted price changes per second, and 600,000 viewers each receiving 500 events per second would be 300 million socket writes per second. Price is state, not a stream of events, so the gateway coalesces: it sends each viewer the latest price at most every 200 ms. That is 5 updates per second per viewer, 3 million writes per second across the fleet, comfortably within 16 gateways. The bidder's own bid result comes back synchronously on the POST, so their screen is correct immediately. Comments on the hot auction are sampled to about 15 per second per viewer. The viewer count is an approximate counter updated every 2 seconds.

Step 5: presence and the viewer count. Each gateway keeps a local count per auction and adds it every 2 seconds to viewers:<auction> in Redis, with a short TTL per gateway entry. The count is the sum of the live entries, so a crashed gateway's share expires on its own. Nobody needs exact viewer identities, so there is no per-user presence fan-out at all.

Step 6: catch-up. Every price event carries the auction's sequence number. A viewer whose connection drops reconnects to any gateway with Last-Event-ID. Price is state, so the gateway simply sends the current price and sequence from the owner's latest snapshot, cached in Redis, and resumes live delivery. Comments are replayed from a per-auction Redis stream capped at 2 minutes. In the last 10 seconds of an auction, the client also polls GET /auctions/:id every 2 seconds as a backstop, because missing the final bid is the worst possible failure.

Step 7: failure of an owner. If a bid server dies, etcd's lease on its membership expires within a few seconds, and the ring version increments. Its auctions move to the next owners, which load state from the database, the system of record, before accepting bids. Bids arriving with the old ring version are rejected and retried by the API tier. Each auction end time is extended by the length of the outage, a product rule rather than a technical one, so no bidder loses because of downtime.

Result. The design meets the 500 ms target with a large margin: bid commit about 10 ms, publish about 2 ms, gateway coalescing up to 200 ms, network about 50 ms. It uses about 60 servers in total, and the only strongly ordered component is the per-auction owner. Everything on the delivery path can lose messages without causing an incorrect result, because catch-up reads from the owner's snapshot and the database.

When to Use It#

  • Users act on fresh information within seconds: chat and messaging, bids and auctions, ride and delivery tracking, trading screens, multiplayer games and collaborative editors.
  • Many viewers watch the same changing thing: live comments, scores, election results, viewer counts and dashboards. Push, or a cached poll for huge audiences, beats every client hammering an API.
  • Updates are rare but urgent: a payment confirmation, "your driver has arrived", or "you have been outbid". The connection is idle most of the time, and push removes polling waste.
  • Long-running work must report progress: build logs, LLM token streams and video processing status. See Pattern: Long-Running Tasks.
  • In interviews: whenever a requirement says "in real time", "live", "instantly", "see others' changes" or "notify".

When NOT to Use It#

  • When a delay of 10 seconds or more is fine. Plain polling of a cached endpoint is simpler, cheaper to run and easier to debug. A connection tier is real operational weight.
  • When the data is the same for everyone and a second of staleness is fine. Use CDN-cached polling rather than millions of sockets.
  • When updates are dense and continuous, such as a 60-frames-per-second game or voice and video. Use UDP-based protocols, WebRTC or specialised game networking, because a TCP stream suffers head-of-line blocking: one lost packet delays everything behind it.
  • When the client is a server. Use webhooks or a message queue, not a socket that someone must hold open.
  • Never as the only path for important data. If an event matters, it is stored first and recoverable by cursor. Push is an optimisation for latency, not a delivery guarantee.

How to Implement It#

  1. State the freshness target and the shape of the traffic: how fresh updates must be, how many users are connected, the message rate, the fan-out distribution including the largest room, and the read-to-write ratio.
  2. Pick the client protocol: polling if 5 to 10 seconds is fine, SSE for mostly server-to-client traffic, and WebSockets for chatty two-way traffic. Plan push notifications for mobile apps in the background.
  3. Design the durable event model: the scope of ordering, how sequence numbers are allocated, an event store or inbox, a retention window for replay, and client-generated IDs for idempotent sends.
  4. Pick hop-two routing: pub/sub for stateless fan-out, consistent hashing for stateful owners, or both. Decide between channels per user and per room, with an adaptive threshold for large rooms.
  5. Build the connection tier: an event-driven runtime, raised OS limits, heartbeats with a bounded detection time, per-connection send caps, authorisation for each subscription, and graceful draining.
  6. Implement resume: subscribe, buffer, replay from the cursor, then flush. Deduplicate on the client. Bound the replay, and fall back to a snapshot.
  7. Add presence with TTLs and a grace period, and keep presence fan-out lazy and scoped.
  8. Plan for the tail: coalescing, sampling, relay trees, a CDN snapshot mode with hysteresis, connect-rate shedding, and backoff with jitter on clients.
  9. Measure end to end: connected clients, connect and disconnect rates, delivery latency from commit to client, missed-sequence rates, buffer sizes, drops and pub/sub lag.

The heart of a gateway's resume logic, in TypeScript. It subscribes first, buffers live events, replays from the store, then flushes anything newer than the replay:

type Ev = { room: string; seq: number; body: unknown };
 
async function resume(sock: Socket, room: string, after: number) {
  const buffered: Ev[] = [];
  let live = false;
  let last = after;
  const deliver = (e: Ev) => {
    if (e.seq <= last) return;            // duplicate of something already sent
    last = e.seq;
    if (!sock.trySend(e)) sock.close(4008, "slow consumer, resync");
  };
  await pubsub.subscribe(`room:${room}`, (e: Ev) =>
    live ? deliver(e) : buffered.push(e)); // 1. subscribe before reading history
 
  const oldest = await recent.oldestSeq(room);
  if (after < oldest - 1) {                // 2. too far behind the replay buffer
    const snap = await snapshots.get(room);
    sock.send({ type: "resync", room, snapshot: snap });
    last = snap.seq;
  } else {
    for (const e of await recent.after(room, after, 500)) deliver(e); // 3. replay
  }
  buffered.sort((a, b) => a.seq - b.seq).forEach(deliver);  // 4. flush, deduped
  live = true;                                                // 5. now live
}

Two details in the snippet matter. First, trySend never blocks. A full send buffer closes the socket with a "resync" code instead of letting one slow client stall the fan-out loop. Second, the single last variable is shared by the replay, the buffered events and the live events, which is what makes the duplicates harmless.

TechnologyFits when
Socket.IO, ws (Node.js), Go WebSocket librariesBuilding your own gateway in Node.js or Go
Phoenix Channels and Presence (Elixir)Many connections per node, built-in presence, BEAM fault tolerance
Netty, Spring WebFlux, SignalRJVM or .NET shops building gateways
CentrifugoA self-hosted realtime server with channels, history, presence and recovery
Redis Pub/Sub, sharded pub/sub, Redis StreamsCheap dynamic fan-out; short replay buffers per room
NATS and JetStreamLightweight subject-based fan-out with optional persistence
Kafka, Pulsar, KinesisA durable, ordered, replayable event backbone feeding the fan-out tier
etcd, ZooKeeperHash ring membership, placement tables, owner leases
Pusher, Ably, AWS API Gateway WebSockets, AppSync, Firebase, Azure Web PubSubManaged connections when you do not want to run a gateway fleet
APNs, FCMDelivery to mobile apps in the background
CDNs such as CloudFront, Fastly, Akamai, CloudflareSnapshot polling for mega-audiences

Trade-offs#

OptionProsConsPick when
Short pollingStateless; works everywhere; trivial to cacheLatency equals the interval; wasted requestsFreshness of 5 s or more; MVPs; huge identical audiences via a CDN
SSEOne-way push over plain HTTP; built-in resumeServer-to-client only; proxy buffering; text onlyFeeds, comments, prices, token streams
WebSocketsFull duplex; lowest latency both waysYou build heartbeats, resume and auth refresh; statefulChat, games, collaboration
Gateways poll the sourceNo routing tier; simpleLoad grows with keys, not changes; latency floorLow-rate updates; log-tailing gateways
Pub/sub routingInterchangeable gateways; easy scaling; dynamic subscriptionsExtra hop; at-most-once; a pub/sub cluster to runDefault for chat, notifications and broadcasts
Consistent-hash ownersOne hop; in-memory per-key state; natural orderingDelicate rebalancing; hot keys; server meshDocuments, rooms, auctions, order books
Dispatcher serviceCentral, load-aware routingMap freshness under churn; more moving partsVery dynamic placement with custom routing rules
CDN snapshot modeScales to any audience at edge cost1 to 2 s latency; no per-user contentMega-streams and global broadcast moments

Common Pitfalls#

  • Pushing before storing, so a dropped socket or at-most-once pub/sub loses the event for ever.
  • Reading history before subscribing, which leaves a silent gap between the two.
  • No sequence numbers, so clients can detect neither gaps nor duplicates.
  • A Kafka topic or partition per user or per viewer. Kafka is the durable backbone, not a channel per person.
  • Load balancing without routing: several gateways, and no way for an event to find the right one.
  • Relying on TCP to detect dead connections, so users sit "connected" while receiving nothing for minutes.
  • Reconnecting without jitter, so one gateway crash becomes a synchronised storm that takes down the authentication service.
  • Fanning out per user to huge rooms instead of per gateway, with no sampling or coalescing for mega-streams.
  • Unbounded per-connection buffers, so a few slow clients exhaust a gateway's memory.
  • Authorising the connection but not each subscription, or not revoking subscriptions when membership changes.
  • Writing presence or last-seen to the database on every heartbeat.
  • Putting business logic in the gateways, so every deploy disconnects millions of users.
  • Ordering by client timestamps, which drift by seconds and can be forged.

Real-World Examples#

  • WhatsApp has described serving more than 2 million connections per server on Erlang and FreeBSD, with messages stored until delivered.
  • Slack has described gateway servers that hold WebSockets and subscribe on behalf of clients, stateful channel servers placed by consistent hashing that fan messages out to subscribed gateways, and separate presence servers.
  • Discord has described running each guild as an Elixir process on a hash ring, fanning events out to session processes, and building Manifold to batch sends across nodes, in its posts on scaling Elixir to millions of concurrent users.
  • Figma has described a multiplayer server process per open document that holds the document state and relays changes between editors: a stateful owner per key.
  • Netflix open-sourced Zuul Push in 2018, a push gateway for WebSocket and SSE connections, used for notifications to devices.
  • Uber has described a realtime push platform for its rider and driver apps that moved from SSE towards gRPC bidirectional streaming.
  • LinkedIn has described a presence platform built on heartbeats with delayed offline events, so brief disconnections do not flicker.
  • Facebook Messenger has been described as using MQTT on mobile to save battery and bandwidth.
  • Chat assistants such as ChatGPT stream generated tokens to the browser over SSE, the most visible use of SSE today.

Case studies that use this pattern#

  • Chat System: per-user channels, an inbox per device, heartbeats, sequence numbers and last seen.
  • Live Comments: SSE, partitioned pub/sub with co-location, sampling and CDN snapshots for mega-streams, and Last-Event-ID.
  • Online Auction: an owner per auction, coalesced price pushes and a backstop for the final seconds.
  • Stock Exchange: market-data fan-out, sequence numbers and gap recovery.
  • Collaborative Editor: a document owner by consistent hashing, operations over WebSockets, and cursors as presence.
  • Ride-Hailing: driver locations flowing in, trip updates flowing out, and push notifications in the background.
  • Ticket Booking: live seat maps and virtual-queue position updates.
  • Flash Sale: waiting-room position and stock-left updates to huge audiences.
  • ChatGPT: token streaming over SSE with resume.
  • Food Delivery and Notification System: order tracking, and the choice between live delivery and push notification.

In the Interview#

Deep Dive: Why subscribe-then-replay is gapless, argued carefullyShow

The resume procedure claims that a client which reconnects with cursor c receives every event with sequence number greater than c, in order, with duplicates removed. It is worth seeing why, because each condition in the argument corresponds to a design rule, and dropping any one of them breaks it.

Assumptions.

  • A1, store before publish. Every event with sequence s is committed to the store before it is published.
  • A2, one sequencer per scope. Sequence numbers within a scope are assigned by one sequencer, so they are dense, 1, 2, 3 and so on, with no holes.
  • A3, FIFO per channel. Once the subscription is active, pub/sub delivers each later publish on the channel to the subscriber, in publish order, unless the subscriber's link drops.
  • A4, reads see commits. A read of the store returns every event committed before the read began.

The argument. Let t_sub be the moment the subscription becomes active, and t_read the moment the history read begins, with t_sub before t_read. Take any event e with sequence greater than c. It was published at some time t_pub, which was after its commit at t_commit by A1. There are two cases.

  • It was published after t_sub. Then by A3 it arrives on the subscription, and is either buffered or delivered live.
  • It was published before t_sub. Then it was committed before t_sub, which is before t_read, so by A4 the history read returns it.

Every event is therefore in the replay, in the buffer, or both. Delivery in sequence order with a "skip if not above the last sent" filter removes the overlap. A2 guarantees that after replaying up to m and flushing the buffer, there is no unseen event between m and the first buffered sequence. If a hole does appear, the only explanations are a dropped pub/sub link, which breaks A3, or a sequencer failure, which breaks A2. Both are detectable, and the response to both is the same: resync.

Where real systems break the assumptions.

  • Publishing without storing first breaks A1. An event published but never committed, because the transaction rolled back after the publish, shows up live and then disappears on replay. That is a "ghost message". This is why the publish happens after commit, ideally driven by the outbox or change data capture.
  • Allocating sequence numbers outside the transaction breaks A2. If sequence 42 is taken from a Redis counter but the transaction that would store 42 fails, 42 never exists, and every client sees a permanent gap. Either allocate inside the same transaction, as a column on the conversation row incremented in the same commit, or let clients treat a gap that persists after one refetch as a hole and skip it.
  • Reading from a lagging replica breaks A4. A history read from an asynchronous replica can miss recent commits that were published before t_sub. Read replay from the primary, or from a cache that is updated before publish, or wait until the replica has reached the latest committed sequence number.
  • Failover of the sequencer. If the owner of a room fails and a new owner starts allocating, it must continue from the last committed number. Many systems add an epoch to the cursor, (epoch, seq), so a client holding a cursor from an older epoch knows to resync rather than trust the numbers.

The result is at-least-once delivery to the client with idempotent application by sequence number, which the user experiences as exactly-once. This is the same construction as exactly-once processing in stream systems, described in Delivery Semantics. True exactly-once delivery over an unreliable network is impossible, but exactly-once effect is not.

Deep Dive: Capacity maths for a connection tierShow

Memory per connection. A connection's memory has three parts.

  • Kernel socket buffers. Linux sizes receive and send buffers dynamically, between the minimum and maximum set in tcp_rmem and tcp_wmem. An idle connection with tuned minimums holds a few kilobytes. A connection that is actively streaming can grow to hundreds of kilobytes if allowed. Capping the maxima for gateway workloads is what keeps a million connections affordable.
  • TLS state. Session keys and record buffers cost from a few kilobytes up to tens of kilobytes, depending on the library and its buffer settings.
  • Application state. User ID, subscriptions, a small outbound queue and the runtime's per-connection objects. Goroutines start with small stacks of a few kilobytes, and Erlang processes are similarly small, while a thread per connection would cost far more.

A planning figure of 20 to 50 KB per idle connection is realistic. One million connections then needs 20 to 50 GB, which fits a large server. For safety and smaller failure domains, most fleets run 100,000 to 500,000 per gateway.

Heartbeat and message budget. With N connections, heartbeat interval h, and a message rate of m per connection per second, a gateway handles N/h + N·m frames per second. For N = 300,000, h = 25 s and m = 0.1, that is 12,000 heartbeats plus 30,000 messages per second, which is small. Heartbeats dominate when traffic is light, which is why mobile-oriented systems lengthen the interval to spare batteries. The interval is a trade between detection time and cost.

Reconnect storms and Little's law. If a gateway holding G connections fails, and clients retry with a delay uniformly spread over a window W, the reconnect rate is about G/W. Each reconnect holds the authentication service for its service time S, so by Little's law the concurrent authentications are about (G/W)·S. For G = 300,000, W = 30 s and S = 20 ms, that is 10,000 reconnects per second and about 200 in flight, which is fine. With W = 1 s, it is 300,000 per second and 6,000 in flight, enough to saturate most authentication tiers and cause cascading reconnect failures. Those failed clients then retry again, which is the definition of a storm. This is why the jitter window matters more than the backoff base. Short-lived signed resume tokens, which gateways can verify locally without calling the authentication service, cut S for reconnects to nearly zero.

Pub/sub throughput. With per-room channels, the pub/sub layer's work is E·g, where E is events per second and g is the average number of gateways subscribed per event. With per-user channels it is E·r, where r is the average number of recipients. For broadcast rooms g is much smaller than r, so per-room channels win by orders of magnitude. For one-to-one chat, g and r are both about 1, and per-user channels win on subscription count. Sharded pub/sub spreads E·g across shards. Classic pub/sub in Redis Cluster does not, because each publish is broadcast to all nodes, which caps throughput no matter how many nodes are added.

Autoscaling lag. Long-lived connections do not move when a gateway is added. If load rises by connection count C per minute and a new gateway takes T minutes to boot and register, the existing fleet must absorb C·T extra connections. For a match kick-off adding 2 million viewers in 5 minutes, with T = 3 minutes, that is 1.2 million connections on the existing fleet. So provision ahead for scheduled events, keep 30 to 50% headroom, and use connect-time shedding with "retry after" so the overflow waits rather than crashes gateways.

Deep Dive: Fan-out topologies and what they costShow

There are four basic shapes for getting one event to many connections, and they trade latency, cost and coupling differently.

Direct fan-out from the publisher. The publisher sends one message per recipient. The cost is O(r) work on the publisher, with latency growing with r. It is fine for r below about 100 and hopeless for a celebrity.

Per-gateway fan-out through pub/sub. The publisher sends once, the pub/sub layer delivers g copies, and each gateway delivers about r/g locally. The publisher does O(1) work, and the slowest gateway sets the tail latency. This is the workhorse shape.

Relay trees. With fan-out k per level, an event reaches N gateways in about log base k of N hops. For N = 2,000 and k = 50, that is 2 hops, so roughly 2 milliseconds of added latency inside a data centre, while no node sends more than 50 copies. Trees suit global broadcasts and cross-region distribution, with one relay per region feeding local gateways, so a cross-region link carries one copy rather than one per gateway.

Pull from a cache or CDN. The publisher writes one object. Clients fetch it, and the CDN absorbs the read load from tens or hundreds of edge locations. The cost moves from the realtime tier to CDN requests, which are cheap at scale. Latency is the poll interval plus the cache TTL. This is the only shape whose cost on your own servers is independent of audience size.

Choosing per key, not per system. Real systems mix shapes and choose per key by size:

  • One-to-one chats use per-user channels.
  • Groups above a threshold use per-room channels.
  • Mega-streams switch to snapshots.
  • A celebrity's posts reach online followers by per-gateway fan-out, and offline followers by a pull at read time.

The thresholds must use hysteresis, and transitions must overlap, publishing to both paths for a short time, so no event is lost while subscribers switch.

Ordering in each shape. Direct and per-gateway fan-out keep per-channel order if each hop is FIFO, which it is for a single Redis or NATS connection. Relay trees keep order if each relay forwards in order over one link. Snapshots carry ordering inside the object, as the ring buffer is sorted. In every case the per-scope sequence number is still the final arbiter on the client.

Consistency between viewers. None of these shapes makes all viewers see an event at the same instant. Per-gateway delivery spreads arrival over the gateways' queue times, typically a few to tens of milliseconds, and snapshot polling spreads it over the poll interval. For auctions and games, where fairness matters, the authoritative decision, such as the winning bid, is made at the single owner using server time, and the displayed timing is only informational. The reference's point stands: realtime systems guarantee fast and eventually complete, while the decisions that need a single truth belong to one owner.

Key Takeaways#

  • Every realtime feature has two hops: connection server to client, using polling, SSE, WebSockets or WebRTC, and source to the right connection server, using pull, pub/sub or consistent hashing.
  • Store first, then push. The socket and the pub/sub layer are best-effort fast paths, and the durable store with per-scope sequence numbers is the truth.
  • Pub/sub makes gateways interchangeable and is the default. Consistent hashing places stateful owners, such as documents, rooms and auctions, and needs careful rebalancing with ring versions, dual delivery and drained reconnects.
  • Choose per-user or per-room channels from the room-size distribution, and adapt above a threshold. Never create a Kafka topic per user.
  • Resume is subscribe, buffer, replay after the cursor, flush above the last replayed sequence, and deduplicate. Bound the replay and fall back to a snapshot.
  • Detect dead connections with application heartbeats, where detection time is interval plus timeout, and catch missed pushes with gap detection, a sequence on each heartbeat and a slow backstop poll.
  • Presence uses heartbeats with TTLs and a grace period. Its fan-out, not its storage, is the cost, so make it lazy and scoped, and write last-seen only on disconnect.
  • Millions of connections are a memory and churn problem: thin event-driven gateways, raised OS limits, least-connections balancing, backoff with full jitter, per-connection send caps and headroom.
  • Huge fan-out goes per gateway, then through relay trees, then sampling and coalescing, and finally CDN snapshots with hysteresis, because at that scale the requirement itself changes.