5 min read
•Question 47 of 62hardWhat is the Cluster module in Node.js?
Understanding Node.js clustering for multi-core utilization.
What You'll Learn
- Why clustering is needed
- How to implement clustering
- Load balancing strategies
Why Clustering?
Node.js runs on a single thread. Cluster module allows you to create child processes (workers) that share the same server port, utilizing all CPU cores.
Basic Cluster Setup
code.jsJavaScript
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers for each CPU
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
cluster.fork(); // Restart worker
});
} else {
// Workers share TCP connection
http.createServer((req, res) => {
res.writeHead(200);
res.end(`Worker ${process.pid}`);
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}Using PM2 (Recommended)
$ terminalBash
# Start with cluster mode
pm2 start app.js -i max
# Or specify number of instances
pm2 start app.js -i 4Load Balancing
Node.js uses round-robin approach by default (except Windows).
code.jsJavaScript
// Customize scheduling
cluster.schedulingPolicy = cluster.SCHED_RR; // Round-robin