Scaling WebSockets in Node.js Beyond One Server

Scaling WebSockets in Node.js Beyond One Server

Sticky sessions, the Redis adapter and graceful deploys: what changes when real-time traffic outgrows one server.

A single Node.js process handles a surprising number of WebSocket connections. Problems start when you add a second server and messages stop reaching users connected to the other one.

Sticky sessions

Socket.io's HTTP long-polling fallback needs every request from a client to hit the same server. Configure your load balancer for sticky sessions, or use WebSocket transport only.

Share events with the Redis adapter

import { createAdapter } from "@socket.io/redis-adapter";

const pub = createClient({ url: process.env.REDIS_URL });
const sub = pub.duplicate();
await Promise.all([pub.connect(), sub.connect()]);

io.adapter(createAdapter(pub, sub));

Now io.to(room).emit() reaches clients in that room on every server.

Heartbeats and limits

  • Keep ping intervals reasonable so dead connections are cleaned up.
  • Limit message size and rate per socket.
  • Authenticate on connect, not per message.

Graceful deploys

When a server shuts down, stop accepting new connections, let clients reconnect elsewhere, then exit. Clients should reconnect with backoff and resync missed messages.

More on this topic

Photography
3D Models
Development
Illustrations
Fashion
Digital Art
Packaging
Motion
Illustrations
Video Production
Photography
3D Models
Development
Illustrations
Fashion