Building Real-time Features with WebSockets
Build reliable real-time features with WebSockets: connection lifecycle, heartbeat-driven reconnection, backpressure, and horizontal scaling with a pub/sub f...
On this page
Introduction
Real-time features — live notifications, collaborative editing, presence, chat — need a channel that pushes data from the server to the client without the client asking. HTTP is request-response, so the naive options are polling (wasteful and laggy) and long polling (better but still one-directional and header-heavy). WebSockets give a single, persistent, bidirectional connection: the server pushes frames at any time, the client sends frames at any time, and the overhead after the handshake is a few bytes per frame. The protocol is simple; the engineering is in the lifecycle — keeping the connection alive, reconnecting when it drops, applying backpressure, and fanning out across a fleet of servers. This article builds that engineering.
The Connection Lifecycle
A WebSocket begins as an HTTP request with an Upgrade: websocket header; the server responds 101 Switching Protocols and the connection becomes a bidirectional socket. On the server, you accept the upgrade, authenticate the client (the upgrade request carries cookies or a token in a subprotocol), and register the connection. On the client, you open the socket, wire up message and close handlers, and treat the connection as a long-lived resource that will eventually fail.
// Server (ws): authenticate on upgrade, track connections per user.
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ noServer: true });
const connections = new Map<string, Set<WebSocket>>(); // userId -> sockets
server.on("upgrade", (req, socket, head) => {
const user = authenticate(req); // verify token/cookie from the upgrade request
if (!user) { socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n"); socket.destroy(); return; }
wss.handleUpgrade(req, socket, head, (ws) => {
const set = connections.get(user.id) ?? new Set();
set.add(ws); connections.set(user.id, set);
ws.on("close", () => { set.delete(ws); if (set.size === 0) connections.delete(user.id); });
ws.on("message", (data) => handleClientMessage(user.id, data));
});
});
function sendToUser(userId: string, message: object) {
for (const ws of connections.get(userId) ?? []) ws.send(JSON.stringify(message));
}
Two details matter. Authentication happens at the upgrade, using the cookies the browser sends with the upgrade request — do not send a token in the URL query string, which leaks into logs. A user may have multiple connections (two tabs, a phone and a laptop), so the connection map is a set per user, and a broadcast to the user fans out to all of them.
Heartbeats and Detecting Dead Connections
A WebSocket can appear open when it is not. The user’s laptop closed, the NAT gateway dropped the mapping, the mobile network switched towers — the TCP connection is half-open and the server will not learn until it tries to write and fails, which may be never. Dead connections accumulate in the connection map, consuming memory and file descriptors. The fix is a heartbeat: the server sends a ping every thirty seconds, and if a pong is not received within a timeout, the server closes the connection.
function startHeartbeat(ws: WebSocket, intervalMs = 30_000, timeoutMs = 10_000) {
let alive = true;
ws.on("pong", () => { alive = true; });
const timer = setInterval(() => {
if (!alive) return ws.terminate(); // missed two pings -> force close
alive = false;
ws.ping();
}, intervalMs);
ws.on("close", () => clearInterval(timer));
}
The heartbeat is the server’s authoritative liveness check. Do not rely on the client to send periodic messages as a heartbeat, because a quiet but alive client will be incorrectly closed. The ping/pong frames are built into the WebSocket protocol and carry no application payload, so they are cheap and unambiguous.
Reconnection on the Client
Connections drop; the client must reconnect, and it must do so without hammering the server. The pattern mirrors the retry strategy from the resilience article: reconnect with a delay that grows and jitters, cap the backoff, and once connected, re-subscribe to the channels and re-fetch any state missed during the disconnect. The reconnection is the difference between a real-time feature that recovers from a wifi blip and one that stays broken until the user refreshes.
class RealtimeClient {
private ws?: WebSocket;
private reconnectDelay = 1000;
connect(url: string) {
this.ws = new WebSocket(url);
this.ws.onopen = () => { this.reconnectDelay = 1000; this.resubscribe(); };
this.ws.onmessage = (e) => this.handle(JSON.parse(e.data));
this.ws.onclose = () => this.scheduleReconnect(url);
this.ws.onerror = () => this.ws?.close();
}
private scheduleReconnect(url: string) {
const delay = Math.min(30_000, this.reconnectDelay) * (0.5 + Math.random());
this.reconnectDelay *= 2;
setTimeout(() => this.connect(url), delay);
}
private resubscribe() { for (const ch of this.subscriptions) this.send({ type: "subscribe", channel: ch }); }
}
The re-subscribe on reconnect is essential: the server’s subscription state died with the old connection, so the new connection must re-establish it. For state that changed during the disconnect (messages that arrived while the client was offline), the client must reconcile — typically by fetching a snapshot or a delta since a last-seen sequence number. A real-time channel that does not handle the gap delivers a feature that drops messages when the network blips.
Backpressure and Message Framing
A client on a slow connection cannot keep up with a fast producer; if the server sends frames as fast as it can, the send buffer grows unbounded and the server runs out of memory. WebSockets expose backpressure through the buffered amount: ws.bufferedAmount is the number of bytes queued but not yet sent. A producer that checks this and slows down when it is large respects the consumer’s speed.
function sendWithBackpressure(ws: WebSocket, data: string, maxBuffered = 1_000_000) {
if (ws.bufferedAmount > maxBuffered) {
// Consumer is slow; drop, sample, or wait. Never queue unboundedly.
return false;
}
ws.send(data);
return true;
}
Frame your messages with a typed envelope so the client can route them without parsing the whole payload, and so you can evolve the protocol without breaking old clients. A { type, data } envelope with a discriminated union of message types lets the client switch on type and ignore types it does not know, which is how you add a new real-time event without forcing every client to upgrade simultaneously.
Scaling: Pub/Sub Fan-Out Across Servers
A single server holds the connections it accepted; when a message must reach a user connected to a different server, the servers must coordinate. The architecture is a pub/sub fan-out: each server subscribes to a shared channel (Redis, NATS) on a topic per user or per room; when a server wants to send to a user, it publishes to that topic; every server receives the publication, and the one holding the user’s connection delivers it locally.
// Each server subscribes to user topics and delivers to local connections.
await redis.subscribe("user:42");
redis.on("message", (channel, message) => {
const userId = channel.split(":")[1];
for (const ws of connections.get(userId) ?? []) ws.send(message);
});
// To send to a user from any server, publish to their topic.
async function notifyUser(userId: string, payload: object) {
await redis.publish(`user:${userId}`, JSON.stringify(payload));
}
The pub/sub layer decouples the producer from the server holding the connection, so a notification generated on server A reaches a user connected to server B. For high fan-out (a message to a room of ten thousand users), publish once to the room topic and let each server expand the room membership locally, rather than publishing ten thousand times. Use a Redis cluster or a dedicated message bus for the fan-out at scale; the single Redis instance becomes the bottleneck past a few thousand publishes per second.
Authorization, Multi-Tenancy, and Message Ordering
Authentication at the upgrade establishes who the user is; authorization on every message establishes what they may do. A common mistake is to authenticate the connection and then trust every message on it, but a connection is long-lived and the user’s permissions may change during its life — they are removed from a room, their role is downgraded, their session is revoked. Re-authorize on each message against the current permissions, not the permissions at connection time, or a revoked user continues to receive and send on the open socket.
ws.on("message", async (data) => {
const msg = JSON.parse(data.toString());
// Re-check authorization on every message with current permissions.
const allowed = await can(user.id, msg.action, msg.resource);
if (!allowed) { ws.send(JSON.stringify({ type: "error", code: "forbidden" })); return; }
handle(user.id, msg);
});
For a multi-tenant application, the connection is scoped to a tenant at the upgrade — the tenant id is in the URL (/ws/tenant-42) or a subprotocol parameter — and every message is authorized within that tenant. Never accept a tenant id in the message body that differs from the connection’s tenant; a user connected to tenant A sending a message claiming tenant B is a cross-tenant access attempt, and the connection’s tenant is the authority. Keep the connection’s tenant in the server-side state and ignore any client-supplied tenant in the message.
Message ordering is a subtle guarantee. Within a single WebSocket connection, the protocol preserves order — messages sent on a connection arrive in the order they were sent. Across connections, and across servers, there is no such guarantee: a user with two tabs may send a message from tab A that arrives after a message from tab B, and two users’ messages interleave unpredictably. If your feature depends on a total order (a collaborative document’s operations, a chat’s message sequence), you need an explicit sequence number or a server-side ordering point, not the connection’s implicit order.
// Assign a server-side sequence number to each message in a room.
async function broadcast(roomId: string, message: object) {
const seq = await redis.incr(`room:${roomId}:seq`); // atomic counter
const envelope = { ...message, seq, at: Date.now() };
await redis.publish(`room:${roomId}`, JSON.stringify(envelope));
}
// Client orders by seq; displays gaps as "loading earlier messages".
The sequence number lets the client detect a gap (it received seq 5 and 7 but not 6) and request the missing message, so a dropped message is noticed and recovered rather than silently lost. For idempotent operations (presence updates), the order does not matter and the sequence is unnecessary; for ordered operations (document edits), it is essential. Choose the guarantee the feature needs and implement exactly that — a total order is expensive to maintain, and most features do not need it.
Delivery guarantees deserve the same explicit choice. At-most-once delivery (send and forget) is fast but loses messages on disconnect; at-least-once (acknowledge and retry) requires the client to deduplicate by message id; exactly-once is expensive and usually approximated with at-least-once plus idempotent handlers. For a notification, at-most-once is fine; for a payment event, at-least-once with idempotency is the minimum. State the guarantee in the protocol documentation so the client implements the right deduplication and ordering logic, rather than discovering the gap in production.
Presence and the Heartbeat
Presence — knowing who is online — is a feature that sits naturally on a WebSocket but has its own subtleties. A user is “online” when they have an open connection, but a connection that is open but idle (the user walked away) is not really online. Distinguish “connected” (the socket is open) from “active” (the user has sent a message or a heartbeat recently), and expose the distinction to the UI so the presence indicator reflects engagement rather than mere connectivity. A heartbeat — a ping sent by the client every 30 seconds — is the signal that distinguishes the two: a connected user who stops heartbeating is marked idle, and a connection that misses two heartbeats is presumed dead and closed. The heartbeat also keeps the connection alive through proxies that close idle sockets after a timeout, so it serves double duty as a liveness check and a keepalive.
Conclusion
Real-time features with WebSockets are an exercise in lifecycle management: authenticate at the upgrade, track connections per user, heartbeat to detect the dead ones, reconnect with backoff and re-subscribe on the client, respect backpressure so a slow consumer does not exhaust the server, frame messages with a versioned envelope, and fan out across servers with a pub/sub layer. The protocol gives you the pipe; the engineering gives you a pipe that stays full and recovers when it breaks. Build the lifecycle and the real-time feature stays live under the conditions that break the naive implementation.
Report a problem with this articleOpens a pre-filled issue on GitHub.