Realtime Communication
How servers push updates to clients with polling, long polling, server-sent events and WebSockets, and how to scale and recover long-lived connections.
On this page
Realtime communication is any technique that lets a server deliver data to a client as soon as the data exists, instead of waiting for the client to ask for it. It is used for chat messages, notifications, live scores, driver locations and shared documents. Plain HTTP only lets the client start a conversation, so each technique in this lesson is a different way of getting around that, and each one changes how many servers you need and what state they keep.
Without a push mechanism, the client has to ask repeatedly whether anything is new. If a million phones ask every 5 seconds, the servers handle 200,000 requests a second, nearly all of them answered with "nothing new", and updates are still up to 5 seconds late.
Where realtime connections sit
Ways to push updates to a client
Short polling
The client sends an ordinary HTTP request on a timer, for example every 5 seconds, and the server answers immediately with whatever is new, which is often nothing. It needs no special support, works through every proxy and load balancer, and the servers stay stateless.
The load is users divided by the interval whether or not anything changed, and an update can be as late as one full interval. Choose it when updates are rare and a delay is acceptable.
Long polling
The client sends a request, and the server holds it open without answering until there is something to send or about 30 seconds have passed. When the response arrives, the client processes it and immediately sends the next request.
A message that arrives between two requests has nobody waiting for it, so the client must send a cursor such as "everything after message 9001", and the server must keep messages until they are fetched. Every message also costs a full request and response. Long polling is mostly used as a fallback for networks that block WebSockets and server-sent events.
Server-sent events
With server-sent events (SSE), the client makes one HTTP request and the server never finishes the response. It keeps writing text events into that response whenever it has news. Data flows only from server to client; anything the client sends goes through normal HTTP requests.
Browsers have SSE built in. If the connection drops, the browser reconnects by itself and sends the id of the last event it received in a Last-Event-ID header, so the server can resume from the right place. Its limits are that it is one-way and that, over HTTP/1.1, a browser allows only about six connections to one host, which HTTP/2 removes. Choose it for feeds the user only reads, such as notifications, live scores or streamed text.
WebSockets
A WebSocket starts as an HTTP request that asks to be upgraded. If the server agrees, the same TCP connection stays open as a channel where either side can send small messages at any time. It is the right choice when the client also sends often, as in chat, multiplayer games and collaborative editing.
The protocol gives you only the channel. Reconnecting, noticing a dead connection and replaying missed messages are your responsibility, and the rest of this lesson covers them. Some proxies block WebSockets, so many products keep a long-polling fallback.
WebRTC
WebRTC lets two browsers or apps exchange audio, video or data directly, so a video call does not pass through your servers. A server is still needed to set up the connection, and a relay for clients that cannot reach each other. Use it for calls, not for ordinary messages.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Short polling | It is plain HTTP, works everywhere and keeps servers stateless. | Mostly empty responses; updates can be one interval late. | Rare updates where a delay is acceptable. |
| Long polling | Updates arrive almost immediately over plain HTTP. | A new request per message, and a cursor to cover gaps. | A fallback where WebSockets and SSE are blocked. |
| Server-sent events | Simple one-way push, with automatic reconnect and resume. | One-way only, and HTTP/1.1 limits connections per host. | Feeds the user only reads. |
| WebSockets Usual default | Fast two-way messages over one connection. | You build reconnect, heartbeats and replay; some networks block it. | Frequent messages in both directions, such as chat. |
Scaling long-lived connections
Connection servers hold state
With request and response, any server can answer any request. With a WebSocket or SSE connection, a client stays attached to one server for hours, and the sender and recipient of a message are usually attached to different servers, so something has to carry the message between them.
The number of connections one server can hold is limited by memory and file descriptors rather than CPU, because an idle connection does almost no work. Keeping connection servers thin means you can deploy business logic without dropping their connections.
Load balancing long-lived connections
A load balancer picks a server only once, when the connection is opened, and the connection then stays there. Round robin is a poor fit, because connections last hours and one server can end up with far more than another. Use least connections, and set the idle timeout above the heartbeat interval.
A newly added server starts empty, because existing clients stay where they are. A server being deployed should be drained by telling its clients to reconnect elsewhere a few at a time, not killed with everyone attached.
Finding which server holds a user's connection
There are two common ways to route a message to the right connection server. One is a registry: when a user connects, the connection server writes "user 42 is on server 7" into a fast shared store with a TTL that heartbeats renew, and a sender looks the user up there. The registry can be wrong for a few seconds after a crash, so delivery to a server that no longer has the user must be handled.
The second way is publish/subscribe, described next, which needs no registry.
A publish/subscribe layer between servers
When a user connects, the connection server subscribes to a topic for that user, such as user:ben. Anything with a message for Ben publishes to that topic without knowing where he is, and the subscribed server pushes it down his connection.
Basic publish/subscribe is at-most-once. A message published while nobody is subscribed is dropped, and a subscriber that is briefly disconnected misses messages. So the database is the source of truth: the service stores the message first and then publishes it, and pub/sub is only a fast path to clients that are online. The tracer shows the whole flow, including a server failure.
1Ana is connected to server 1 and Ben to server 2, which subscribed to
user:benwhen he connected.- last seq Ben saw
- 9000
2Ana sends "lunch?" over her open connection, with no new handshake.
- last seq Ben saw
- 9000
3The chat service stores the message as 9001 first, so it survives a failed delivery.
- last seq Ben saw
- 9000
4It publishes 9001 to
user:benwithout knowing which server Ben is on.- last seq Ben saw
- 9001
5Server 2 is the only subscriber and pushes 9001 down Ben's connection.
- last seq Ben saw
- 9001
6Server 2 crashes. Ana's next message, 9002, is stored, but nobody is subscribed to
user:ben, so the publish reaches no one.- last seq Ben saw
- 9001
7Ben's app reconnects to server 1 after a random delay, and server 1 subscribes to
user:benbefore the app asks for history.- last seq Ben saw
- 9002
8The app asks for everything after 9001 and receives 9002. The store, not pub/sub, made delivery reliable.
Reconnection and missed messages
Connections drop all the time, so the client reconnects automatically and asks the server for what it missed. To make that possible, the server gives every message in a conversation a sequence number that increases by one, and the client remembers the highest number it has received.
On reconnect the client sends that number, and the server returns everything after it from the message store. Sequence numbers also expose lost messages while the connection is up: if the client has 9001 and receives 9003, it knows 9002 is missing and fetches it. A lost final message leaves no gap to notice, so the client also syncs when the app opens. A message can arrive twice, live and in the replay, so the client ignores sequence numbers it already has.
If a server holding 50,000 connections dies and all of them retry at once, the surviving servers receive a sudden wave and may fail in turn. Clients therefore wait with exponential backoff and random jitter, so the retries spread out.
Heartbeats and dead connections
A phone that loses signal never sends a close message, so the server's socket still looks open, and the server would keep writing to it and keep the user marked online.
The fix is a heartbeat: one side sends a small ping every 20 to 30 seconds, and the other side answers with a pong. If the server receives nothing from a client for about two or three intervals, it closes the connection and cleans up that client's subscriptions. The same pings stop proxies from closing idle connections.
Presence
Presence is the "online" indicator. The simple approach is to treat the heartbeat as a lease: each heartbeat writes the user's key to a fast store with a TTL of about two heartbeat intervals. While heartbeats keep arriving, the key stays and the user is online. When they stop, the key expires and the user becomes offline, which also works when a server crashes without cleaning up.
The difficulty is telling other people. Broadcasting every change to everyone who follows a user is expensive, and users on a weak network flip between online and offline constantly. Common fixes are to wait a few seconds before announcing "offline" so a quick reconnect causes no flicker, and to send presence only for conversations the viewer has open.
Fan-out to many subscribers
A group chat with 50,000 members or a live event with a million viewers turns one message into a very large number of deliveries, and publishing once per recipient would overload the publisher.
Instead, publish once to a topic for the group. Each connection server subscribes to the topic when at least one of its connections is in the group, and it pushes the message to all of those connections locally. The publisher's work then depends on the number of servers, not the number of users.
Slow clients also matter. A client on a poor network cannot read as fast as the server writes, and its queued messages use server memory. Give each connection a bounded buffer, and when it is full, drop old messages (fine for live scores) or close the connection and let the client resync by sequence number.
In the interview
Start with the direction of data. If clients only receive, use SSE, or polling when updates are rare; if both sides send frequently, use WebSockets. Then say that connection servers are stateful and that the database, not pub/sub, is the source of truth. For example: "Users both send and receive constantly, so I'd use WebSockets, with a sequence number per conversation so clients can catch up after a reconnect."
Questions to expect:
- "Why not just poll?" Polling costs users divided by the interval in requests a second even when nothing changes, and updates arrive late. Use it only when updates are rare.
- "WebSockets or SSE?" If the client only receives, SSE is simpler, because the browser reconnects and resumes by itself. If the client also sends frequently, WebSockets avoid a separate request for each message.
- "How does a message reach a user connected to a different server?" The connection server passes it to a service, which stores it and publishes to the recipient's topic. The server holding the recipient's connection is subscribed to that topic and pushes it down.
- "What if a message is lost?" Every message has a per-conversation sequence number and is stored before it is published. The client detects a gap, or asks for everything after its last number on reconnect, and the server replays it from the store.
- "How do you load balance WebSockets?" Use least connections, because connections are long-lived, and set the idle timeout above the heartbeat interval. Drain servers during a deploy, and have clients reconnect with backoff and jitter.
- "What happens if the pub/sub layer goes down?" Messages are still stored, so nothing is lost, but online users stop receiving them live. Clients catch up from their last sequence number once pub/sub recovers.
- "How do you deliver to a group of a million?" Publish once to a topic, and let each connection server push to its own subscribers. Bound each connection's buffer so slow clients cannot exhaust memory.
Two users are chatting and are connected to different servers. How does a message get from one to the other?
The sender's connection server hands the message to the chat service, which stores it with the next sequence number for that conversation and then publishes it to the recipient's topic. The recipient's connection server is subscribed to that topic, so it pushes the message down the open connection.
What if the recipient's server crashes at that moment?
The message is already stored, so nothing is lost. When the client reconnects, it sends the last sequence number it has, and the server returns everything after it. Pub/sub is only the fast path for users who are online.
A sports site shows live scores in the browser, and readers never send anything back. Which transport fits best?
A chat client has received message 9001 and then receives 9003 over its connection. What should it do?
What to practise next
Open connections invite floods, which Rate Limiting covers. To use all of this in a full design, work through Design a Chat App.