What is the Cluster Module in Node.js?
Understand the Node.js cluster module: fork worker processes across CPU cores, share one port, balance load and stay resilient when a worker crashes.
Expected Interview Answer
The cluster module lets a single Node.js application fork multiple worker processes that share the same server port, so one app can use all CPU cores instead of being limited to a single core by Node's single-threaded event loop.
A primary (master) process spawns worker processes with cluster.fork(), and the operating system or Node's built-in load balancer distributes incoming connections across them. Each worker is a full Node process with its own event loop and memory, so a crash in one does not take down the others, and the primary can respawn dead workers. Because workers do not share memory, state such as sessions must live in an external store like Redis; sticky sessions or a shared cache handle affinity when needed.
- Uses all CPU cores on a multi-core machine
- Higher throughput for CPU- and connection-heavy apps
- Fault isolation — one worker crashing does not kill the app
- Primary can respawn failed workers for resilience
- Enables zero-downtime restarts by cycling workers
AI Mentor Explanation
One bowler cannot bowl every over of a long innings without tiring. A captain rotates several bowlers from both ends while the scoreboard stays shared. The cluster module is that bowling rotation: the primary process fields many worker bowlers on the same port, spreading the workload so no single core carries the whole match.
Step-by-Step Explanation
Step 1
Detect the CPU count
Read os.availableParallelism() (or os.cpus().length) to decide how many workers to fork.
Step 2
Branch on cluster.isPrimary
In the primary branch, loop and call cluster.fork() once per core to spawn workers.
Step 3
Start the server in workers
In the worker branch, create the HTTP server and listen — all workers share the same port via the primary.
Step 4
Balance connections
Node's round-robin scheduler (default on non-Windows) distributes new connections across workers.
Step 5
Handle worker death
Listen for the 'exit' event on the primary and call cluster.fork() again to respawn crashed workers.
Step 6
Externalize shared state
Move sessions and caches to Redis or a database since workers have separate memory.
What Interviewer Expects
- Explains Node's single-threaded event loop as the motivation
- Knows the primary/worker model and cluster.fork()
- Understands workers share a port via the primary
- Mentions load balancing (round-robin scheduler)
- Knows workers do not share memory and state must be external
- Aware of respawning workers and tools like PM2
Common Mistakes
- Thinking workers share memory or variables
- Storing sessions in worker memory instead of Redis
- Forking more workers than CPU cores, adding overhead
- Not respawning workers after they crash
- Confusing cluster (processes) with worker_threads (threads)
Best Answer (HR Friendly)
“The cluster module lets one Node.js app run several copies of itself, one per CPU core, all sharing the same port. This way the app uses the whole machine and stays available even if one copy crashes, since the others keep serving requests.”
Code Example
const cluster = require('node:cluster');
const http = require('node:http');
const os = require('node:os');
if (cluster.isPrimary) {
const cpus = os.availableParallelism();
console.log(`Primary ${process.pid} forking ${cpus} workers`);
for (let i = 0; i < cpus; i++) {
cluster.fork();
}
// Respawn a worker if it dies
cluster.on('exit', (worker, code) => {
console.log(`Worker ${worker.process.pid} died (${code}); restarting`);
cluster.fork();
});
} else {
// Every worker shares the same port
http.createServer((req, res) => {
res.end(`Handled by worker ${process.pid}`);
}).listen(3000);
console.log(`Worker ${process.pid} started`);
}Follow-up Questions
- How does the cluster module distribute incoming connections across workers?
- Why can't you store session state in worker memory when clustering?
- What is the difference between the cluster module and worker_threads?
- How does PM2 relate to the cluster module?
- How would you achieve zero-downtime restarts with cluster?
MCQ Practice
1. Why does Node.js provide the cluster module?
Node's event loop is single-threaded, so cluster forks multiple processes so the app can use all CPU cores.
2. How do cluster workers share the server port?
The primary process owns the listening socket and hands connections to workers, typically round-robin.
3. Where should session state live in a clustered Node app?
Workers have separate memory, so shared state must live in an external store such as Redis or a database.
Flash Cards
What problem does the cluster module solve? — Node's single-threaded event loop uses one core; cluster forks worker processes so the app uses all cores.
How do you spawn a worker? — In the cluster.isPrimary branch, call cluster.fork() — usually once per CPU core.
How is state shared between cluster workers? — It isn't — workers have separate memory, so use an external store like Redis.
cluster vs worker_threads? — cluster forks separate OS processes (own memory); worker_threads run threads that can share memory.