Blog

· 6 min read

Socket.io in cluster mode: the bug that took down my live scoreboard

In production, Socket.io answered 'Session ID unknown' with 2 workers. The real cause, and the roles of Nginx, the Redis adapter and JWT in the sockets.

  • socketio
  • nginx
  • redis
  • nodejs

I moved the Kravva API to cluster mode, with 2 workers, to use both of the server's CPUs. In production, the front end started getting this on the live scoreboard:

HTTP 400  {"message":"Session ID unknown"}

It worked in development, with a single process. In production, with two, real time failed. It's worth understanding why, because the fix I credited at the time wasn't quite what solved it.

Why it happens

Three pieces combine to produce this error.

1. node:cluster distributes connections, not clients. A Node process uses one CPU core. The cluster module creates a primary process that forks several workers, all on the same port, and hands out TCP connections among them round-robin. Once a connection is handed to a worker, it stays with that worker.

2. Socket.io can talk in two ways. The protocol underneath it, Engine.IO, often starts with long-polling: a series of ordinary HTTP requests. The first one (the handshake) returns an identifier, the sid, and every following request has to repeat it. After that it can upgrade to WebSocket, a single persistent TCP connection.

3. The session lives in the memory of the process that did the handshake. Any process that didn't do the handshake doesn't know that sid.

Now put an Nginx in front. It keeps a pool of keepalive connections to Node and reuses them for any client:

req 1: GET /socket.io/?transport=polling
       → connection A → worker 1 creates the session  sid=abc

req 2: GET /socket.io/?transport=polling&sid=abc
       → connection B → worker 2: "never seen abc"
       → HTTP 400 "Session ID unknown"

The classic remedy for this is sticky sessions: making sure every request from the same client lands on the same process (via ip_hash in Nginx, via a cookie or via @socket.io/sticky). The Socket.io docs require it for polling with multiple processes.

What actually got rid of the 400

The commit that fixed the problem had three changes, and its message credited the Redis adapter. When I went back to rebuild the mechanism, I saw the 400 went away for a different reason.

Before the commit, Nginx only had a generic location /, with Connection "", which is ideal for plain HTTP and has no Upgrade header. Result: the WebSocket never got through the proxy, and the client stayed stuck on polling, which is exactly the mode that breaks with two workers.

What fixed it was a dedicated location for Socket.io:

location /socket.io/ {
    proxy_pass http://api_upstream;

    # upgrade only exists in HTTP/1.1
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;

    # don't drop the idle connection
    proxy_read_timeout 86400s;
    proxy_send_timeout 86400s;
}

With WebSocket, the whole session lives on a single TCP connection pinned to one worker. Without polling, there's no standalone request to land on the wrong worker, and the 400 disappears. The lesson: I had an explanation that looked right, written in the commit message. The correct one came from reasoning about the mechanism.

The second bug, a silent one: events that get lost

The Redis adapter is there, and it was a necessary fix, but for a different problem, a much sneakier one because it produces no error at all.

The PIX (Brazil's instant payment system) payment scenario: the user opens the app and their socket connects to worker 2, in the user:42 room. The payment provider calls the webhook, and Nginx delivers it to worker 1. Worker 1 does:

this.server.to('user:42').emit('acesso-liberado', payload);

But worker 1's Socket.io server only knows the sockets it holds itself. Nobody is in the user:42 room there. The event vanishes and the user is left staring at the paywall after paying. The same goes for scoreboard deltas emitted by queue jobs on any worker.

The Redis adapter (@socket.io/redis-adapter) solves this with pub/sub. Analogy: a loudspeaker. Whoever speaks doesn't know who's listening. When a worker emits to a room, the adapter publishes the message to Redis, every worker receives it and each one delivers it to the room's local sockets.

// Simplified from the real code
const pubClient = new Redis({ host, port, lazyConnect: true });
const subClient = pubClient.duplicate(); // 2nd connection just for subscribing

await Promise.all([pubClient.connect(), subClient.connect()]);
server.adapter(createAdapter(pubClient, subClient));

There are two connections because a Redis connection in subscriber mode can't run other commands.

Important: the adapter does not share Engine.IO sessions. It replicates broadcasts. Anyone who thinks "the adapter fixes Session ID unknown" ends up scaling workers without sticky sessions, believing they're safe.

Authentication on the sockets

Real time needs identity too. In the notifications gateway, the JWT is required in the handshake. If the token is valid, the socket joins the user's own room; if not, it's disconnected:

async handleConnection(client: Socket) {
  try {
    const token = extrairTokenHandshake(client);
    const usuarioId = await verificarJwtObrigatorio(
      this.jwtService, this.config, token,
    );
    await client.join(`user:${usuarioId}`);
  } catch {
    client.disconnect(true); // no valid token, no socket
  }
}

The user never picks the room: it's derived from the token. That's what stops someone from listening to another person's notifications. The live games gateway accepts an optional JWT, because the scoreboard is public, and limits each socket to 3 game rooms.

What to test

A proxy change calls for an end-to-end test before deploying:

  • Connect forcing transports: ['websocket'] and then ['polling'], with 2 workers up. The first should work; the second shows whether sticky sessions are really configured.
  • Emit from one worker to a socket on another, as in the webhook case, and check that the event arrives.
  • Take Redis down at boot and see whether anyone notices.

What I would do differently

  • Polling is still broken with 2 workers. On networks that block WebSocket, the client falls back to polling and the 400 comes back. Either the client uses WebSocket only (transports: ['websocket'], at the cost of not working on those networks), or I set up real sticky sessions.
  • The adapter silently falls back to memory. If Redis is down at boot, the process carries on without the adapter until it restarts, losing broadcasts between workers with no alert. I would expose this in the health check.
  • The JWT is only checked in the handshake. The socket outlives token expiration and a ban. On a ban, I would disconnect the sockets in the user's room.
  • The CORS origin is open (origin: true). I would restrict it to the product's domains.
  • Behind a CDN, check its maximum idle connection time, which is independent of the Nginx timeout.

Key takeaways

  • node:cluster hands out connections, not clients; the Socket.io session lives in one worker's memory.
  • "Session ID unknown" is polling landing on another worker: the cure is sticky sessions or WebSocket-only.
  • For WebSocket to get through Nginx, you need proxy_http_version 1.1, Upgrade, Connection: upgrade and long timeouts, in a dedicated location.
  • The Redis adapter makes emit reach the right worker, but it doesn't share sessions. They're different problems.
  • Validate the JWT in the handshake, derive the room from the token and remember it isn't revalidated afterwards.

Written by Maycon Liborio, full stack developer. If this helped you or you disagree with something, reach out on LinkedIn.

More posts

Maycon Liborio

São José dos Campos, SP, Brazil

© 2026 · Handmade with Nuxt, modern CSS and zero UI libraries. Data generated from my master profile on every build.

esc

Go to

Projects

Posts

Actions

↑↓ navigate↵ open/ or ⌘K toggles