Back to course

Node Clusters

Node.js applications normally run on a single CPU core, which can become a bottleneck for CPU‑intensive tasks.

The cluster module allows you to create multiple worker processes that share the same server port.
This lets your application take advantage of all available CPU cores, improving throughput and performance.


Why use clusters?

Clustering is useful when your application:

  • performs CPU‑heavy operations
  • needs to handle many concurrent requests
  • must remain responsive under load
  • should automatically restart workers if they crash

How clusters work

A cluster consists of:

  • a master process that manages workers
  • multiple worker processes, each running a copy of your server
  • shared communication channels between master and workers

When a worker dies, the master can automatically spawn a new one, improving reliability.


Basic example

import cluster from "node:cluster";
import http from "node:http";
import os from "node:os";

if (cluster.isPrimary) {
  const cpuCount = os.cpus().length;

  console.log(`Primary process running. Spawning ${cpuCount} workers...`);

  for (let i = 0; i < cpuCount; i++) {
    cluster.fork();
  }

  cluster.on("exit", worker => {
    console.log(`Worker ${worker.process.pid} died. Restarting...`);
    cluster.fork();
  });
} else {
  http
    .createServer((req, res) => {
      res.end(`Handled by worker ${process.pid}`);
    })
    .listen(3000);

  console.log(`Worker ${process.pid} started`);
}