Scaling WebSocket (Horizontal) — Realtime

WebSocket connections are stateful: each connection and its rooms stick to one process. One Node process holds 10,000 connections with about 110 MB (ws) to…

When does a realtime server need to be split across processes, and what breaks once you split it? That is what horizontal scaling is about: adding more server processes or machines instead of buying one bigger machine. For WebSocket it is harder than plain HTTP, because the connections are stateful (the server keeps the state of each connection). Each connection sticks to one process for its whole life, rooms included.

It is like Mrs. Rini's Laundry adding a second clerk to serve customers. A customer being served by clerk 1 has to keep coming back to clerk 1 until they are done, because their papers sit on clerk 1's desk. And when Eko announces something to clerk 1, clerk 2 only hears it if there is an intercom between them. In this picture, each clerk is one server process, a customer is a client, and Eko's announcement is an emit. The papers on the desk are the connection and rooms kept in that process's memory. Always coming back to the same clerk is called a sticky session, and the intercom is the Redis adapter from the Pub/Sub with Redis lesson.

Count first: how many can one process hold?

Every WebSocket connection costs the server two things: memory and one file descriptor (the number the operating system uses for every open file or socket). Measured with Node 22: a server holds N WebSocket connections from clients in another process. Its memory is read after garbage collection (the clean-up of memory no longer in use). RSS is all the memory the process uses:

Connections ws 8.22.0 (RSS) socket.io 4.8.4 (RSS)
0 53.9 MB 59.6 MB
1,000 58.2 MB 84.3 MB
10,000 108.0 MB 164.5 MB

So 10,000 customers' phones still fit in one process, roughly 110 to 170 MB. Mrs. Rini's Laundry, with 4 screens and a dozen or so phones, clearly needs nothing from this lesson. A second process usually comes for other reasons: one process's CPU is full, or so that a deploy (putting a new version live) or a dead machine does not cut everyone off.

Load balancers and sticky sessions

A load balancer (nginx, for example) takes every connection and divides them among several processes. The trouble is Socket.IO's HTTP long polling transport (a way of sending). One polling session (one Socket.IO connection over polling) is many separate HTTP requests (handshake, send, receive), and all of them have to reach the same process.

Guess first: the laundry's realtime server is now two Socket.IO processes, A and B, behind nginx, which sends each request to the next process in turn (round robin). Mr. Darto's phone opens the page with the client's default settings. Does it connect?

Tried with nginx round robin in front of two socket.io 4.8.4 servers. This is what the client and server B logged:

client:   connect_error xhr post error   (HTTP 400)
server B: connection_error 1 Session ID unknown

The handshake GET /socket.io/?EIO=4&transport=polling reached A, so A created the session. nginx took the next request to B, and B does not know that session. So Mr. Darto's phone does not connect.

There are two fixes, both tried and working. The first is in nginx, the second in the client:

upstream realtime {
    ip_hash;                       # the same IP always goes to the same process
    # sticky cookie srv_id;        # another option, in open source nginx since 1.29.6
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
}
// or: skip polling and go straight to WebSocket. One TCP connection, so no sticky needed.
const socket = io('https://laundry.example', { transports: ['websocket'] })

Proxies: the Upgrade header and the 60 second limit

nginx has to pass on the Upgrade and Connection headers so the WebSocket handshake (from the WebSocket Fundamentals lesson) gets through:

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}
server {
    location /socket.io/ {
        proxy_pass http://realtime;
        proxy_http_version 1.1;            # required before nginx 1.29.7; the default since
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 60s;            # the default value
    }
}

proxy_read_timeout defaults to 60 seconds: if the server sends nothing for that long, nginx closes the connection. Tried with nginx 1.27.5: a quiet WebSocket was closed at second 60.01 with code 1006, while a connection getting a ping from the server every 25 seconds stayed alive. Socket.IO already pings every 25 seconds. A plain ws server has to send ws.ping() itself, or raise proxy_read_timeout.

News between processes: the Redis adapter

Rooms live in each process's memory, so an emit on A does not reach sockets on B. The fix comes from the Pub/Sub with Redis lesson: io.adapter(createAdapter(pub, sub)) from @socket.io/redis-adapter. Every emit goes to Redis, and every process passes it on to its own sockets. Sticky sessions take care of connections, the adapter takes care of news. You need both.

Other options: Socket.IO has 8 official adapters. The four picked most often:

Adapter When to pick it
@socket.io/redis-adapter (used here) the processes run on several machines and Redis is already there. The most used one
@socket.io/redis-streams-adapter you want news missed during a short drop to still arrive (connection state recovery)
@socket.io/cluster-adapter all processes run on one machine, started through node:cluster (Node's module for several processes). News goes over IPC, with no Redis
@socket.io/postgres-adapter your team already runs Postgres and does not want to add Redis (through LISTEN/NOTIFY)

The other four are for MongoDB, Google Cloud Pub/Sub, AWS SQS and Azure Service Bus.

Deploying without a reconnect storm

When process B is stopped, all its connections drop at the same time, and every client reconnects. If the delay is not random, 5,000 phones try to connect to A in the same millisecond. That is a reconnect storm. The Socket.IO client already randomises its first delay: 1 second ± 50%, so it spreads between 500 and 1,500 ms. A hand-written reconnect must use the backoff and jitter from the WebSocket Fundamentals lesson.

A tidier way is a drain: empty B gradually before stopping it. This code runs when B receives SIGTERM, the signal the system sends to ask a process to stop:

process.on('SIGTERM', async () => {
  httpServer.close() // stop taking new connections; nginx sends new ones to A
  const all = [...io.sockets.sockets.values()]
  for (let i = 0; i < all.length; i += 500) {
    all.slice(i, i + 500).forEach((s) => s.conn.close()) // reason 'transport close': the client reconnects by itself
    await new Promise((r) => setTimeout(r, 1000))          // 500 per second, not all at once
  }
  process.exit(0)
})

Numbers for the laundry

Mrs. Rini's Laundry 10,000 customers' phones
Connections 4 screens + a dozen phones 10,000
Memory unnoticeable 110 to 170 MB, fits in one process
Needs a second process? no for deploys without dropping people, and a spare if a machine dies
What comes with it nothing sticky (or websocket only), Redis adapter, jitter, drain

⚠️ Missteps when adding processes

TL;DR: WebSocket connections are stateful: each connection and its rooms stick to one process. One Node process holds 10,000 connections with about 110 MB (ws) to 170 MB (Socket.IO). The limit is often file descriptors, the numbers the operating system gives each open connection (EMFILE, ECONNRESET). Behind a load balancer (a server that divides connections among processes), Socket.IO polling needs sticky sessions: the same client always goes to the same process (ip_hash or sticky cookie). Otherwise you get Session ID unknown. transports: ['websocket'] (WebSocket right away, no polling) needs no sticky. nginx needs the Upgrade and Connection headers, and closes connections that stay quiet for 60 seconds (proxy_read_timeout). News between processes goes through the Redis adapter. Deploy with a drain (emptying a process gradually) and restarts in turn, and give clients reconnects with jitter (a random delay). A small laundry needs none of this.

⚡ WebSocket connections are stateful

Meaning: Stateful means the server keeps the state of each connection. Each connection sticks to one process for its whole life, rooms included. One Node process still holds 10,000 connections (about 110 to 170 MB), so count first before adding processes.

⚡ Polling needs sticky sessions

Guess first: the laundry's realtime server is now two Socket.IO processes, A and B, behind nginx, which sends each request to the next process in turn. Mr. Darto's phone opens the page with the client's default settings, which start with HTTP long polling (many separate HTTP requests). Does it connect?

It does not connect. The polling handshake reached A, so A created the session. The next request went to B, and B does not know that session: Session ID unknown.

Meaning: A sticky session (ip_hash or sticky cookie in nginx) always sends the same client to the same process. transports: ['websocket'] (WebSocket right away, no polling) needs no sticky.

⚡ News between processes: the Redis adapter

Meaning: Rooms live in each process's memory, so an emit on process A does not reach sockets on process B. The Redis adapter passes that emit on through Redis. Sticky sessions take care of connections, the Redis adapter takes care of news between processes. You need both.

⚡ Deploying without a reconnect storm

Meaning: When a process is stopped, all its clients drop and then reconnect. Stop processes one at a time and empty them gradually (drain), so thousands of clients do not rush another process in the same millisecond.

What you will learn