Consider this Node.js cluster code snippet. What will be the output behavior when a worker process crashes?
import cluster from 'cluster'; import os from 'os'; if (cluster.isPrimary) { const numCPUs = os.cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died.`); }); } else { process.exit(1); // Worker crashes immediately }
Look at the cluster event listeners and what happens on 'exit'.
The code listens for 'exit' events and logs when a worker dies. However, it does not call cluster.fork() again to restart the worker. So workers are not restarted automatically.
Given this cluster setup, which code snippet correctly restarts a worker when it crashes?
import cluster from 'cluster'; import os from 'os'; if (cluster.isPrimary) { const numCPUs = os.cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { // Restart worker here }); } else { // Worker code }
Remember how to create new workers in Node.js cluster.
To restart a worker, the primary process must call cluster.fork() to create a new worker. The worker object does not have a fork method, and cluster.restart() is not a valid method.
Examine this code snippet. Why does it fail to restart workers after they crash?
import cluster from 'cluster'; import os from 'os'; if (cluster.isPrimary) { const numCPUs = os.cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died.`); cluster.fork(worker.id); }); } else { process.exit(1); }
Check the cluster.fork() method signature.
The cluster.fork() method does not take any arguments. Passing worker.id causes an error or unexpected behavior, so the worker is not restarted properly.
Given this cluster code, how many worker processes will be active after one worker crashes and the restart code runs?
import cluster from 'cluster'; import os from 'os'; if (cluster.isPrimary) { const numCPUs = os.cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died.`); cluster.fork(); }); } else { if (process.env.CRASH) process.exit(1); else setTimeout(() => {}, 10000); }
Think about how cluster.fork() replaces crashed workers.
The code starts one worker per CPU. When a worker crashes, the 'exit' event triggers and cluster.fork() creates a new worker. So the total number of active workers stays the same.
Choose the best explanation for why managing worker crashes and restarts is critical in Node.js cluster applications.
Think about what happens if workers crash and are not restarted.
Automatically restarting crashed workers keeps the app running smoothly and prevents downtime. It helps maintain performance and availability.