WebSocket · Node.js · Realtime · Backend

Realtime Systems with Node.js and WebSocket: Patterns That Survive Production

Patterns for live dashboards, notifications and device monitoring with Node.js and WebSocket: connection lifecycle, backpressure, reconnects and scaling.

Sander Yazıcıoğlu Published: 3 min read Türkçe oku

On a real-device testing platform we had to show the status of hundreds of devices, test steps and logs to users instantly. An HTTP request every second can't carry that. This article covers the patterns that matter when you take a Node.js WebSocket system from works on day one to stays up in production.

WebSocket or something else?

Not every live-data need calls for WebSocket:

MethodDirectionWhen it fits
Short pollingClient → serverData changes a few times a minute; simplest option
Server-Sent Events (SSE)Server → clientOne-way streams: notifications, logs, progress
WebSocketBidirectionalCommands plus instant state, low latency
WebRTCPeer-to-peerAudio, video, screen streaming

If users only watch, SSE is often enough and plays better with HTTP infrastructure. If users also send commands over the same channel (tapping a device, stopping a test), WebSocket is the right choice.

Message contract: typed from day one

The most common mistake is throwing free-form JSON at the socket. A few months later nobody knows which message carries which fields. A simple envelope and a TypeScript discriminated union fix that:

type ServerMessage =
  | { type: 'device.status'; deviceId: string; status: 'online' | 'busy' | 'offline' }
  | { type: 'test.step'; runId: string; step: number; result: 'passed' | 'failed' }
  | { type: 'error'; code: string; message: string };

const send = (socket: WebSocket, message: ServerMessage) => socket.send(JSON.stringify(message));

Adding a v (version) field to messages makes backwards compatibility easier later.

Connection lifecycle

Authentication

The browser WebSocket API doesn't let you set custom headers. Practical options: fetch a short-lived token before connecting and pass it in the URL, or authenticate with the first message after the connection opens. A token that lives a few seconds limits the damage if the URL lands in logs.

Heartbeats and dead connections

On mobile networks, behind proxies and when a laptop sleeps, connections die silently. The server should detect dead clients with ping/pong and clean them up:

import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (socket) => {
  socket.isAlive = true;
  socket.on('pong', () => { socket.isAlive = true; });
});

setInterval(() => {
  for (const socket of wss.clients) {
    if (!socket.isAlive) { socket.terminate(); continue; }
    socket.isAlive = false;
    socket.ping();
  }
}, 30000);

Reconnecting on the client

A client should not retry immediately and endlessly when the connection drops: when the server restarts, thousands of clients reconnecting at once cause a thundering herd. Use exponential backoff with jitter:

const delay = (attempt) => Math.min(30000, 1000 * 2 ** attempt) * (0.5 + Math.random() / 2);

The most robust way to recover missed data is for the client to send the last event id it saw after reconnecting, and for the server to resume from there.

Backpressure

Send fast data to a slow client and messages pile up in server memory. In the ws library, socket.bufferedAmount shows that backlog. A few rules prevent big problems:

  • For state updates (such as device status) send only the latest value and skip intermediate ones.
  • When bufferedAmount crosses a threshold, drop low-priority messages (such as verbose logs), or tell the client and close the connection.
  • Batch high-frequency data on the server and flush every 100–250 ms; the human eye won't notice anything faster.

Horizontal scaling

One Node.js process handles thousands of concurrent connections comfortably, but high availability needs more than one server. Two problems appear:

  1. Fan-out: how does an event created on server B reach a user connected to server A? With Redis Pub/Sub, NATS or a similar broker, each server subscribes to the channels it needs.
  2. Load balancer: WebSocket connections are long-lived. The load balancer must support the Upgrade header, and its idle timeout must be longer than your heartbeat interval.

Grouping users into rooms (for example, one room per test run) simplifies both fan-out and authorisation.

Observability

Realtime bugs are hard to reproduce, so measurement is essential:

  • Active connections and messages per second.
  • Average and p95 message size.
  • Reconnect rate (a sudden spike usually means a network or deploy problem).
  • Number of connections above the bufferedAmount threshold.

Conclusion

A working WebSocket demo takes an afternoon. A system that survives production needs typed messages, heartbeats, smart reconnects, backpressure and a message broker. For heavier streams such as video and screens, read the WebRTC article; for the API side, see error handling in TypeScript Node.js APIs.

All articles →