The cluster module helps Node.js use multiple CPU cores to run tasks faster by creating copies of the main program.
How cluster module works in 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.
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); }
import cluster from 'node:cluster'; if (cluster.isPrimary) { cluster.fork(); cluster.fork(); } else { console.log('Worker ' + process.pid + ' started'); }
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.
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`); }
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.
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.