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
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
cluster module in Node.js?Solution
Step 1: Understand the cluster module role
The cluster module allows Node.js to create multiple worker processes.Step 2: Recognize the benefit
These workers use all CPU cores to improve performance by handling requests in parallel.Final Answer:
To create multiple worker processes to use all CPU cores -> Option DQuick Check:
cluster module = multiple workers for CPU cores [OK]
- Confusing cluster with database or file system modules
- Thinking cluster manages UI or frontend
- Assuming cluster runs code in a single process
Solution
Step 1: Recall the updated property name
In recent Node.js versions,cluster.isPrimaryreplacescluster.isMaster.Step 2: Identify the correct syntax
Usingcluster.isPrimarycorrectly checks if the process is the primary (master) process.Final Answer:
if (cluster.isPrimary) { ... } -> Option BQuick Check:
Primary process check = cluster.isPrimary [OK]
- Using deprecated cluster.isMaster instead of cluster.isPrimary
- Confusing isWorker with isPrimary
- Using non-existent properties like isMain
const cluster = require('cluster');
const http = require('http');
if (cluster.isPrimary) {
cluster.fork();
cluster.fork();
} else {
http.createServer((req, res) => {
res.end('Worker ' + process.pid);
}).listen(8000);
}What will happen when you visit
http://localhost:8000 multiple times?Solution
Step 1: Understand cluster.fork creates workers
Two workers are created, each running the HTTP server on port 8000.Step 2: Recognize load balancing behavior
Requests are distributed between workers, so responses show different process IDs.Final Answer:
You will see responses from different worker process IDs -> Option AQuick Check:
Multiple workers share port, respond with different PIDs [OK]
- Thinking only one worker handles all requests
- Assuming server crashes due to multiple forks
- Expecting syntax errors from this code
const cluster = require('cluster');
if (cluster.isPrimary) {
cluster.fork();
} else {
console.log('Worker running');
}Solution
Step 1: Check cluster usage
The primary forks one worker, which only logs a message but does not start a server.Step 2: Identify missing functionality
Without server code, the worker does not handle requests, so the cluster setup is incomplete.Final Answer:
Missing server code inside worker -> Option CQuick Check:
Worker must run server code to handle requests [OK]
- Confusing isPrimary with deprecated isMaster
- Expecting cluster.fork in worker process
- Assuming code runs without server in worker
Solution
Step 1: Understand worker crash handling
The primary process can listen to the 'exit' event when a worker dies.Step 2: Restart worker on exit
Inside the 'exit' event handler, calling cluster.fork() creates a new worker to replace the crashed one.Final Answer:
Listen to the 'exit' event on cluster and fork a new worker inside the handler -> Option AQuick Check:
Restart crashed workers by handling 'exit' event [OK]
- Forking workers repeatedly with setInterval causes overload
- Not restarting workers after crash leads to downtime
- Using cluster.disconnect() inside worker does not restart it
