Node.js theorytheory 0/50 · 0%
Performance · hard

38. Cluster mode and scaling

Using multiple CPU cores from one Node application.

A single Node process uses one CPU core for its JS. `node:cluster` forks multiple worker processes that share the same listening port, letting you use every core on a machine — the OS load-balances incoming connections across workers.

js
import cluster from "node:cluster";
import { cpus } from "node:os";

if (cluster.isPrimary) {
  for (let i = 0; i < cpus().length; i++) cluster.fork();
  cluster.on("exit", (worker) => {
    console.log(`worker ${worker.process.pid} died, restarting`);
    cluster.fork();
  });
} else {
  startServer(); // each worker runs the actual app
}

Workers are separate processes with separate memory — in-process caches and in-memory state are per-worker, not shared, which is a common surprise when moving from a single process to a clustered deployment. Process managers like PM2 wrap this pattern for you.

Check your understanding

  1. 1. Why does a single Node process only use one CPU core by default?

  2. 2. What happens to in-memory state (like a simple cache) when using cluster mode?

  3. 3. What role does the primary process play in cluster mode?