Performance: Load balancing between workers
This affects how efficiently the server handles incoming requests and distributes CPU work, impacting response time and throughput.
Jump into concepts and practice - no test required
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { cluster.schedulingPolicy = cluster.SCHED_RR; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker) => { cluster.fork(); // replace dead worker }); } else { http.createServer((req, res) => { // handle request res.end(`Handled by worker ${process.pid}`); }).listen(8000); }
const cluster = require('cluster'); if (cluster.isMaster) { cluster.schedulingPolicy = cluster.SCHED_NONE; cluster.fork(); cluster.fork(); } else { require('http').createServer((req, res) => { // handle request res.end('Handled by worker'); }).listen(8000); }
| Pattern | CPU Utilization | Request Queuing | Response Time | Verdict |
|---|---|---|---|---|
| Single worker or unbalanced cluster | Low to uneven | High under load | High latency | [X] Bad |
| Balanced cluster with multiple workers | High and even | Low | Low latency | [OK] Good |
cluster module in Node.js for load balancing?isMaster and isWorker boolean properties to identify process roles.cluster.isMaster is true if the process is the master, so the condition should use this.const cluster = require('cluster');
const http = require('http');
if (cluster.isMaster) {
cluster.fork();
cluster.fork();
} else {
http.createServer((req, res) => {
res.end(`Worker ${process.pid} handled request`);
}).listen(8000);
}
What will happen when you send multiple requests to port 8000?const cluster = require('cluster');
if (cluster.isMaster) {
cluster.fork();
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
throw new Error('Crash');
}cluster.fork() inside the exit event handler.os.cpus().length to fork that many workers in the master process.