You want to implement a Node.js cluster that balances load across all CPU cores and automatically restarts workers if they crash. Which code snippet correctly achieves this?
hard📝 Application Q15 of 15
Node.js - Cluster Module
You want to implement a Node.js cluster that balances load across all CPU cores and automatically restarts workers if they crash. Which code snippet correctly achieves this?
if (cluster.isMaster) {
const cpuCount = require('os').cpus().length;
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died, restarting...`);
cluster.fork();
});
} else {
require('http').createServer((req, res) => {
res.end(`Handled by worker ${process.pid}`);
}).listen(3000);
} correctly uses os.cpus().length to fork that many workers in the master process.
Step 2: Restart workers on exit event in master
if (cluster.isMaster) {
const cpuCount = require('os').cpus().length;
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died, restarting...`);
cluster.fork();
});
} else {
require('http').createServer((req, res) => {
res.end(`Handled by worker ${process.pid}`);
}).listen(3000);
} listens to the 'exit' event on cluster and forks a new worker to replace the dead one.
Step 3: Worker creates HTTP server listening on port 3000
if (cluster.isMaster) {
const cpuCount = require('os').cpus().length;
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died, restarting...`);
cluster.fork();
});
} else {
require('http').createServer((req, res) => {
res.end(`Handled by worker ${process.pid}`);
}).listen(3000);
}'s else block creates the server in workers, which is correct for load balancing.
Final Answer:
Forks workers across all CPU cores and automatically restarts workers if they crash -> Option B
Quick Check:
Fork all CPUs + restart on exit = if (cluster.isMaster) {
const cpuCount = require('os').cpus().length;
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died, restarting...`);
cluster.fork();
});
} else {
require('http').createServer((req, res) => {
res.end(`Handled by worker ${process.pid}`);
}).listen(3000);
} [OK]
Quick Trick:Fork all CPUs in master and restart on exit event [OK]
Common Mistakes:
Not forking all CPU cores
Not restarting workers after crash
Forking workers inside worker process
Attaching exit listener inside worker instead of master
Master "Cluster Module" in Node.js
9 interactive learning modes - each teaches the same concept differently