What is the Cluster Module in Node.js?
Learn how the Node.js cluster module forks worker processes to use all CPU cores, handles crashes, and scales apps with practical code examples.
Expected Interview Answer
The cluster module lets a Node.js application spawn multiple worker processes that share the same server port, allowing it to use all available CPU cores since a single Node process is limited to one core by default.
Node runs JavaScript on a single thread per process, so a single instance can't use multiple CPU cores for concurrent request handling. The cluster module's primary process forks worker processes (typically one per core via os.cpus().length), and the OS or a built-in round-robin scheduler distributes incoming connections across them. Each worker has its own event loop and memory, so workers don't share in-memory state — session stores or caches need external stores like Redis. If a worker crashes, the primary can detect the 'exit' event and fork a replacement, improving resilience. In production, process managers like PM2 or container orchestration (Kubernetes replicas) often replace manual clustering.
- Utilizes all CPU cores for a single Node app
- Improves throughput under concurrent load
- Primary process can restart crashed workers
- Transparent port sharing across workers
- No code changes needed to the request-handling logic
AI Mentor Explanation
The cluster module is like fielding four identical bowling attacks in the nets simultaneously instead of one bowler working through every batter alone. A head coach assigns each incoming batter to whichever net is free, and if one bowler gets injured, the coach simply brings in a substitute to keep all four nets running.
Cluster module architecture
Primary process
- Forks N workers
- Distributes connections
- Restarts crashed workers
Worker 1..N
- Own event loop
- Own memory space
- Handles requests independently
Step-by-Step Explanation
Step 1
Import cluster and os
Require 'cluster' and use os.cpus().length to determine core count.
Step 2
Check if primary or worker
cluster.isPrimary (or isMaster in older versions) branches the setup logic.
Step 3
Fork workers in the primary
Call cluster.fork() once per CPU core to spawn worker processes.
Step 4
Run the server in each worker
Each worker independently creates an HTTP server bound to the same port.
Step 5
Handle worker exit
Listen for cluster.on('exit', ...) in the primary to fork a replacement worker.
Step 6
Externalize shared state
Use Redis or a database for sessions/caches since workers don't share memory.
What Interviewer Expects
- Explains that Node is single-threaded per process by default
- Knows cluster forks one worker per CPU core typically
- Understands workers don't share memory state
- Mentions restart-on-crash resilience pattern
- Can compare cluster module to PM2/container-based scaling
Common Mistakes
- Assuming clustered workers share in-memory variables or sessions
- Forgetting to handle the worker 'exit' event to restart crashed workers
- Using cluster for CPU-bound work instead of worker_threads
- Not considering container/orchestrator-level scaling as an alternative
Best Answer (HR Friendly)
“The cluster module lets a Node.js app use all the CPU cores on a machine by running several copies of the app at once, sharing incoming traffic between them. This helps the app handle more users at the same time instead of being limited to a single processor core.”
Code Example
const cluster = require('cluster');
const http = require('http');
const os = require('os');
if (cluster.isPrimary) {
const numCPUs = os.cpus().length;
for (let i = 0; i < numCPUs; i++) cluster.fork();
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died, forking a new one`);
cluster.fork();
});
} else {
http.createServer((req, res) => {
res.end(`Handled by worker ${process.pid}`);
}).listen(3000);
// Output: Handled by worker 23456 (varies per request)
}Follow-up Questions
- How does the cluster module distribute incoming connections?
- What happens to in-memory session data across cluster workers?
- How is the cluster module different from worker_threads?
- How would you handle zero-downtime restarts with clustering?
- Why might you use PM2 instead of the raw cluster module in production?
MCQ Practice
1. Why is the cluster module needed in Node.js?
Node runs on a single thread per process, so clustering forks multiple processes to use all CPU cores.
2. Do cluster workers share in-memory state by default?
Each worker is a separate process with its own memory; shared state needs an external store like Redis.
3. What should the primary process do when a worker crashes?
Listening for the worker 'exit' event and forking a new worker keeps the app resilient to crashes.
Flash Cards
What problem does the cluster module solve? — It lets a Node app use multiple CPU cores by forking multiple worker processes.
How many workers are typically forked? — One per CPU core, often via os.cpus().length.
Do workers share memory? — No — each worker has its own event loop and memory space.
What's a common production alternative to raw cluster? — Process managers like PM2, or container orchestration with multiple replicas.