← Back to Node.js, page 7

nodejs-0139 · Hard senior

How do you scale WebSockets across several Node.js instances: authentication on upgrade, backpressure, and fan-out through Redis pub/sub?

Each WebSocket lives on one instance, so a message received by instance 1 must reach clients on instance 2. Publish messages to a broker such as Redis pub/sub (or streams) and let every instance forward them to its own clients. Authenticate during the HTTP upgrade and reject with 401 before accepting the socket, and check bufferedAmount to drop or disconnect slow clients instead of filling memory.

Full answer

Why scaling is harder than HTTP

  • A connection is stateful and long-lived. A load balancer pins it to one instance for its whole life.
  • Local broadcast (loop over wss.clients) reaches only the clients of that instance.

Fan-out with a broker

  • On receipt, publish the message to a Redis channel (for example room:42). Every instance subscribes and sends to its own matching clients. Instances need no knowledge of each other.
  • Redis pub/sub is fire-and-forget: if an instance is down at that moment, it misses the message. For history or replay use Redis Streams, Kafka or a database, and let clients ask for missed messages after they reconnect (with a last seen id).
  • A subscriber connection cannot run normal commands, so use a separate connection for publishing.
  • Presence (who is online) needs shared state with expiry, for example Redis keys refreshed by the heartbeat.
  • Socket.IO has an adapter for this. With plain ws you write it yourself.

Authentication

  • Browsers cannot set custom headers in the WebSocket constructor. Use a short-lived token in the query string or a cookie, or send a first message with the token and close the socket if it is not valid within a few seconds.
  • Do the check in the server 'upgrade' event (with noServer: true), and reject with an HTTP 401 response before calling handleUpgrade. Tokens in URLs can leak into logs, so keep them short-lived or use a ticket pattern.

Backpressure and limits

  • socket.bufferedAmount is the number of bytes queued and not yet sent. If a client is slow and you keep calling send, memory grows. Skip or close clients above a threshold (for example 1 MB).
  • Set maxPayload, rate limit messages per connection, and cap the number of connections per user.

Operations

  • Load balancer needs WebSocket support, long idle timeouts, and a graceful drain on deploy (send close 1001 and let clients reconnect with backoff and jitter to avoid a thundering herd).
  • Monitor connection counts, send queue sizes and reconnect rates.
javascript
const http = require('node:http');
const { once } = require('node:events');
const { setTimeout: sleep } = require('node:timers/promises');
const { WebSocketServer, WebSocket } = require('ws');
const Redis = require('ioredis');

const REDIS_URL = process.env.REDIS_URL || 'redis://127.0.0.1:6379';
const CHANNEL = 'demo-chat-' + process.pid;

async function startInstance(name) {
  const server = http.createServer();
  const wss = new WebSocketServer({ noServer: true });
  const publisher = new Redis(REDIS_URL);
  const subscriber = new Redis(REDIS_URL);

  server.on('upgrade', (req, socket, head) => {
    const token = new URL(req.url, 'http://localhost').searchParams.get('token');
    if (token !== 'valid-ticket') {                       // reject before the upgrade is accepted
      socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
      return socket.destroy();
    }
    wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));
  });
  wss.on('connection', (ws) => {
    ws.on('message', (data) => publisher.publish(CHANNEL, JSON.stringify({ via: name, text: data.toString() })));
  });
  await subscriber.subscribe(CHANNEL);
  subscriber.on('message', (channel, message) => {
    for (const client of wss.clients) {
      if (client.readyState === WebSocket.OPEN && client.bufferedAmount < 1_000_000) client.send(message); // skip slow clients
    }
  });

  server.listen(0, '127.0.0.1');
  await once(server, 'listening');
  const close = async () => { for (const c of wss.clients) c.terminate(); wss.close(); server.close(); publisher.disconnect(); subscriber.disconnect(); };
  return { port: server.address().port, close };
}

async function connect(port, token) {
  const ws = new WebSocket(`ws://127.0.0.1:${port}/?token=${token}`);
  ws.inbox = [];
  ws.on('message', (data) => ws.inbox.push(data.toString()));
  await Promise.race([once(ws, 'open'), once(ws, 'error')]);
  return ws;
}

async function main() {
  const one = await startInstance('instance-1');
  const two = await startInstance('instance-2');

  const alice = await connect(one.port, 'valid-ticket');   // connected to instance 1
  const bob = await connect(two.port, 'valid-ticket');     // connected to instance 2
  await sleep(50);

  alice.send('hello from Alice');
  await sleep(100);
  console.log('Bob (instance 2) received:', bob.inbox.join(' | '));
  console.log('Alice (instance 1) received:', alice.inbox.join(' | '));

  const rejected = new WebSocket(`ws://127.0.0.1:${one.port}/?token=wrong`);
  rejected.on('error', (err) => console.log('wrong token ->', err.message));
  await new Promise((resolve) => rejected.on('close', resolve));

  alice.terminate(); bob.terminate();
  await one.close(); await two.close();
}
main();

Two server instances run in one process, each with its own Redis connections. A message sent to instance 1 reaches the client on instance 2, and a wrong token is refused during the upgrade. Install first with npm install ws ioredis (run here with ws 8.23.1, ioredis 6.1.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): Bob (instance 2) received: {"via":"instance-1","text":"hello from Alice"} Alice (instance 1) received: {"via":"instance-1","text":"hello from Alice"} wrong token -> Unexpected server response: 401

Key points

  • A socket lives on one instance, so use a broker for fan-out.
  • Redis pub/sub is fire-and-forget; use streams for replay.
  • Authenticate in the upgrade handler and reject with 401.
  • Check bufferedAmount and drop slow clients.
  • Drain gracefully on deploy and reconnect with jitter.

Common mistakes

  • Broadcasting only to local clients and wondering why other users miss messages.
  • Using the subscriber connection to publish.
  • Accepting the socket first and checking the token later.
  • Calling send in a loop for a slow client with no bufferedAmount check.
  • Restarting all instances at once, so every client reconnects together.

Follow-ups

  • When would you use Redis Streams instead of pub/sub?
  • How does sticky routing help or hurt WebSocket scaling?
  • How do you handle presence and typing indicators across instances?

Tips

  • Say 'a socket lives on one instance' first.
  • Name the broker and its weakness.
  • Mention bufferedAmount and graceful drain.