AceDevHub
Advanced Node.js Interview QuestionsAdvancedConcept

Node.js · Question 75

How does the Node.js cluster module work?

Direct answer

cluster.isPrimary forks worker processes (cluster.fork) that share server ports via OS scheduling — primary can respawn dead workers; each worker runs full Node app; alternative to multiple Docker replicas on single host.

cluster uses child_process.fork with IPC — workers are full V8 isolates, not threads. Primary distributes incoming connections (round-robin on most platforms).

  • isPrimary / isWorker — branch entry: fork N workers or start server.
  • Worker count — os.availableParallelism() or CPU cores; match container limit.
  • Respawn — cluster.on('exit', () => cluster.fork()) for crash recovery.
  • Sticky sessions — WebSocket/stateful apps may need session affinity or Redis pub/sub.
cluster.mjs
import cluster from "node:cluster";
import process from "node:process";

if (cluster.isPrimary) {
  console.log(`Primary ${process.pid}`);
  for (let i = 0; i < 4; i++) cluster.fork();

  cluster.on("exit", (worker) => {
    console.log(`Worker ${worker.process.pid} died — restarting`);
    cluster.fork();
  });
} else {
  await startFastify({ port: 4000 });
  console.log(`Worker ${process.pid} listening`);
}