Skip to main content
Practice Problems

What is the cluster module in Node.js?

Node.js Cluster Module

Node.js runs on a single thread, meaning it can only use one CPU core by default. The Cluster module solves this by allowing you to create multiple worker processes that share the same server port β€” each running on a separate core.


The Problem

Single Node.js process β†’ uses only 1 of 8 CPU cores β†’ wasted 87.5%!

Solution: Cluster Module

js
const cluster = require('cluster'); const os = require('os'); const http = require('http'); const numCPUs = os.cpus().length; if (cluster.isPrimary) { console.log(`Primary PID: ${process.pid}`); console.log(`Forking ${numCPUs} workers...`); // Fork a worker for each CPU core for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died. Restarting...`); cluster.fork(); // restart crashed worker }); } else { // Workers share the same port http.createServer((req, res) => { res.end(`Hello from worker ${process.pid}`); }).listen(3000); console.log(`Worker ${process.pid} started`); }

How It Works

Primary Process (master) ↓ fork() β”œβ”€β”€ Worker 1 (PID 1234) β†’ handles requests β”œβ”€β”€ Worker 2 (PID 1235) β†’ handles requests β”œβ”€β”€ Worker 3 (PID 1236) β†’ handles requests └── Worker 4 (PID 1237) β†’ handles requests All workers share port 3000 via OS round-robin scheduling

Communication Between Primary and Workers

js
if (cluster.isPrimary) { const worker = cluster.fork(); // Send message to worker worker.send({ type: 'config', value: 42 }); worker.on('message', (msg) => { console.log('From worker:', msg); }); } else { process.on('message', (msg) => { console.log('From primary:', msg); process.send({ received: true }); }); }

Zero-Downtime Restart (Graceful Reload)

js
// Restart workers one by one without dropping connections const workers = Object.values(cluster.workers); let i = 0; function restartNext() { if (i >= workers.length) return; const worker = workers[i++]; worker.on('exit', () => { cluster.fork().on('listening', restartNext); }); worker.disconnect(); } restartNext();

Cluster vs Worker Threads vs PM2

FeatureClusterWorker ThreadsPM2
PurposeMulti-process HTTP serversCPU-bound tasksProcess manager
MemorySeparateSharedSeparate
IPCprocess.send()MessageChannelCluster internally
Use caseScale network serversHeavy computationProduction deployment

PM2 Alternative

In production, use PM2 which wraps cluster automatically:

bash
pm2 start app.js -i max # start one worker per CPU pm2 reload app # zero-downtime reload

Summary

The Cluster module lets you utilize all CPU cores by spawning multiple worker processes. It's ideal for scaling HTTP servers. In production, PM2 simplifies clustering and adds process management (restart on crash, logs, monitoring).

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems