Skip to content

Node.js cluster mode with sticky load balancing

Scale a single-process Node.js service across CPU cores using cluster, and route socket-stateful traffic to the same worker every time.

A Node.js process runs JavaScript on a single thread. On an 8-core box that leaves seven cores idle unless you fork worker processes via the cluster module — and the moment you do, anything that holds per-connection state (Socket.IO, server-sent events, in-process caches) needs sticky routing so a client always lands on the same worker. This walks through both halves: forking workers correctly and pinning a client to a worker by IP hash.

How to verify

Confirm how many workers are running and which port they share:

ps -ef | grep -E 'node.*server' | grep -v grep
ss -tnlp | grep ':3000'
curl -s http://127.0.0.1:3000/_worker | head -5
journalctl -u myapp --since "10 min ago" | grep -i 'worker\|exit\|listening'
nproc  # how many workers should we be running

If ss shows only one PID on the port, the master is handling all connections — cluster isn’t active. If you see N PIDs all listening on the same port, the kernel is round-robining and you have no stickiness.

What’s happening

cluster.fork() spawns child processes that share a single listening socket. By default on Linux, the kernel distributes incoming connections across workers via SO_REUSEPORT — round-robin within a CPU bucket. That works for stateless HTTP, but it breaks Socket.IO and any protocol where a long-lived connection or a follow-up request expects to find the same in-memory session.

Sticky load balancing means hashing the client (usually by IP, sometimes by a cookie or connection.remoteAddress) and always routing them to the same worker. Two patterns are common: the master listens and forwards each TCP connection to a chosen worker via worker.send() with the socket handle, or you put a real load balancer in front (Nginx, HAProxy) doing IP-hash and let each Node process listen on its own port. The second pattern is what we run for clients in production — the first is for environments where you cannot add an LB.

The procedure

  1. Add a master/worker entrypoint. The master forks one worker per core and respawns any that crash:

    // server.js
    import cluster from 'node:cluster';
    import os from 'node:os';
    import { createServer } from './app.js';
    
    if (cluster.isPrimary) {
      const cpus = os.availableParallelism();
      console.log(`primary ${process.pid} forking ${cpus} workers`);
      for (let i = 0; i < cpus; i++) cluster.fork();
      cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} exit (${signal || code}) respawning`);
        cluster.fork();
      });
    } else {
      createServer().listen(3000, () => {
        console.log(`worker ${process.pid} listening`);
      });
    }
  2. For stateless HTTP that is happy with kernel round-robin, you are done — the kernel distributes connections. Verify by hitting / repeatedly and watching different PIDs respond.

  3. For sticky routing without an external LB, use the @socket.io/sticky pattern: the master listens on the port, hashes by remote IP, and hands the connection to the chosen worker:

    import { setupMaster, setupWorker } from '@socket.io/sticky';
    import { createAdapter, setupPrimary } from '@socket.io/cluster-adapter';
    
    if (cluster.isPrimary) {
      const httpServer = createServer();
      setupMaster(httpServer, { loadBalancingMethod: 'least-connection' });
      setupPrimary();
      httpServer.listen(3000);
      for (let i = 0; i < os.availableParallelism(); i++) cluster.fork();
    } else {
      const io = new Server(createServer());
      io.adapter(createAdapter());
      setupWorker(io);
    }
  4. The cleaner production pattern: each worker binds to its own port (3001, 3002, …) and an Nginx upstream uses ip_hash to pin clients:

    upstream node_app {
      ip_hash;
      server 127.0.0.1:3001;
      server 127.0.0.1:3002;
      server 127.0.0.1:3003;
      server 127.0.0.1:3004;
    }
    server {
      listen 80;
      location / { proxy_pass http://node_app; proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
    }
  5. Drain workers on graceful shutdown so in-flight requests finish before the process exits:

    process.on('SIGTERM', () => {
      server.close(() => process.exit(0));
      setTimeout(() => process.exit(1), 30_000).unref(); // hard kill after 30s
    });

Common pitfalls

  • The kernel does not magically distribute load evenly. A worker stuck in a slow handler still gets new connections — combine cluster with a per-worker max in-flight cap or use PM2 cluster mode which adds health-based routing.
  • Sticky-by-IP fails behind a CDN or shared NAT — every client looks like one IP and one worker takes the whole load. Use a stickiness cookie at the LB layer in that case.
  • In-process caches diverge across workers. Two requests for the same user can hit two workers and see two cache states. Move shared state to Redis or accept the inconsistency explicitly.
  • Memory is per-worker. Eight workers each holding a 500 MiB cache means 4 GiB RAM consumed — size the box for workers * peak_rss.
  • The cluster module is in maintenance mode in modern Node. For new services, evaluate worker_threads for CPU-bound work and external load balancing for HTTP scaling instead of cluster.

For Socket.IO and SSE specifically, see WebSocket scaling patterns. In the engagements Stack Harbor runs, the Nginx ip_hash front-door is the default — cluster module is reserved for environments where adding an LB is impossible. We operate the upstream as part of managed operations, with worker counts pinned to CPU and respawn alerting wired into the on-call channel.