0
0
Node.jsframework~5 mins

How cluster module works in Node.js

Choose your learning style9 modes available
Introduction

The cluster module helps Node.js use multiple CPU cores to run tasks faster by creating copies of the main program.

When you want your Node.js app to handle many users at the same time without slowing down.
When your server has multiple CPU cores and you want to use them all efficiently.
When you want to keep your app running even if one part crashes by restarting workers.
When you want to balance the load of incoming requests across several processes.
Syntax
Node.js
import cluster from 'node:cluster';
import os from 'node:os';

if (cluster.isPrimary) {
  const cpuCount = os.cpus().length;
  for (let i = 0; i < cpuCount; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker) => {
    console.log(`Worker ${worker.process.pid} died. Restarting...`);
    cluster.fork();
  });
} else {
  // Worker process code here
}

cluster.isPrimary checks if the current process is the main one that controls workers.

cluster.fork() creates a new worker process that runs the same code.

Examples
This example creates one worker per CPU core. Each worker runs a simple HTTP server.
Node.js
import cluster from 'node:cluster';
import http from 'node:http';
import os from 'node:os';

if (cluster.isPrimary) {
  const cpuCount = os.cpus().length;
  for (let i = 0; i < cpuCount; i++) {
    cluster.fork();
  }
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello from worker ' + process.pid);
  }).listen(8000);
}
This example creates exactly two worker processes that print their process IDs.
Node.js
import cluster from 'node:cluster';

if (cluster.isPrimary) {
  cluster.fork();
  cluster.fork();
} else {
  console.log('Worker ' + process.pid + ' started');
}
Sample Program

This program uses the cluster module to create one worker per CPU core. The primary process manages workers and restarts any that die. Each worker runs a simple HTTP server that responds with its process ID.

Node.js
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 ${process.pid} is running`);

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

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died. Restarting...`);
    cluster.fork();
  });
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Hello from worker ${process.pid}`);
  }).listen(8000);
  console.log(`Worker ${process.pid} started and listening on port 8000`);
}
OutputSuccess
Important Notes

Workers share the same server port but run in separate processes, improving performance on multi-core machines.

If a worker crashes, the primary process can restart it automatically to keep the app running smoothly.

Use cluster only when your app is CPU-bound or needs to handle many connections simultaneously.

Summary

The cluster module lets Node.js use all CPU cores by creating worker processes.

The primary process controls workers and can restart them if they crash.

Workers run the same code and can share server ports to handle many requests efficiently.