← Back to Node.js, page 2

nodejs-0036 · Hard senior

How does the cluster module work, how does it share one port, and what are its limits?

cluster forks several Node processes (workers) from a primary process. The primary owns the listening socket and, on Linux and macOS, hands incoming connections to workers in round-robin order. It scales a server across CPU cores, but workers do not share memory, so in-process state and caches must move to an external store.

Full answer

A single Node process uses one core for JavaScript. The cluster module starts one worker process per core so a server can use them all.

How it works:

  • The primary process calls cluster.fork() several times. Each worker is a full Node process that runs the same script again, with cluster.isPrimary false.
  • When a worker calls server.listen(port), the request goes to the primary. The primary opens the socket once, accepts connections, and passes each one to a worker. The default policy is round-robin (except on Windows, where the operating system distributes connections).
  • Workers and the primary talk through IPC messages. cluster.on('exit') lets the primary replace a crashed worker.

Limits and trade-offs:

  • No shared memory. Sessions, rate-limit counters and caches kept in a variable differ per worker. Use Redis or a database.
  • Each worker has its own heap, so memory use is multiplied.
  • WebSocket and sticky sessions need extra care, because one client can land on different workers.
  • Round-robin does not balance by work. One worker can get all the slow requests.
  • Today most teams run one process per container and let Kubernetes or a load balancer scale instances. cluster, or a process manager such as pm2 in cluster mode, is still useful on a single machine.
  • worker_threads is the better tool for CPU work. cluster is for scaling request handling.

Always handle worker exit to keep capacity, and add graceful shutdown with worker.disconnect().

javascript
const cluster = require('node:cluster');
const http = require('node:http');

if (cluster.isPrimary) {
  const WORKERS = 2;
  const REQUESTS = 6;
  let listening = 0;
  const served = {};

  for (let i = 0; i < WORKERS; i++) cluster.fork();

  cluster.on('listening', (worker, address) => {
    if (++listening < WORKERS) return;
    // Both workers share one port. Send requests and see who answers.
    let pending = REQUESTS;
    const send = () => {
      http.get({ port: address.port, host: '127.0.0.1', agent: false }, (res) => {
        let body = '';
        res.on('data', (c) => (body += c));
        res.on('end', () => {
          served[body] = (served[body] || 0) + 1;
          if (--pending > 0) return send();
          console.log('workers started:', WORKERS, '| requests sent:', REQUESTS);
          console.log('answers per worker (round-robin):', Object.values(served));
          console.log('different workers answered:', Object.keys(served).length);
          cluster.disconnect();
        });
      });
    };
    send();
  });
} else {
  http.createServer((req, res) => res.end('worker ' + cluster.worker.id)).listen(0, '127.0.0.1');
}

Port 0 asks for any free port, and both workers share the one the primary opened. Requests are sent one at a time, so round-robin alternates between the workers. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): workers started: 2 | requests sent: 6 answers per worker (round-robin): [ 3, 3 ] different workers answered: 2

Key points

  • One primary, many worker processes, one shared listening port.
  • Round-robin distribution (except on Windows).
  • No shared memory between workers.
  • Replace crashed workers from the primary.
  • Containers and orchestrators often replace cluster.

Common mistakes

  • Storing sessions or counters in process memory and running several workers.
  • Believing cluster uses threads.
  • Not restarting workers that crash.
  • Using cluster inside a container that is already scaled horizontally, then over-using memory.

Follow-ups

  • How would you do a zero-downtime restart with cluster?
  • How do you handle sticky sessions for WebSockets?
  • Why is cluster less common today than ten years ago?

Tips

  • Say who owns the socket (the primary) and how connections reach workers.
  • List the trade-offs. Interviewers expect the shared-state problem.
  • Compare with worker_threads in one sentence.