Sometimes worker processes stop working unexpectedly. Handling crashes and restarting workers helps keep your app running smoothly without downtime.
Handling worker crashes and restart in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
import cluster from 'node:cluster'; import os from 'node:os'; if (cluster.isPrimary) { // Fork workers for (let i = 0; i < os.cpus().length; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died. Restarting...`); cluster.fork(); }); } else { // Worker code here }
cluster.isPrimary checks if the current process is the main one that controls workers.
The exit event lets you detect when a worker stops and restart it.
cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} crashed.`); cluster.fork(); });
cluster.on('exit', (worker) => { setTimeout(() => { cluster.fork(); }, 1000); // Restart after 1 second delay });
if (cluster.isPrimary) { cluster.fork(); cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died.`); cluster.fork(); }); } else { // Worker code }
This program starts one worker per CPU core. Each worker crashes after 2 seconds. The primary process detects the crash and restarts the worker automatically.
import cluster from 'node:cluster'; import os from 'node:os'; if (cluster.isPrimary) { console.log(`Primary ${process.pid} is running`); // Fork workers equal to number of CPU cores for (let i = 0; i < os.cpus().length; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died. Restarting...`); cluster.fork(); }); } else { console.log(`Worker ${process.pid} started`); // Simulate a crash after 2 seconds setTimeout(() => { console.log(`Worker ${process.pid} crashing now.`); process.exit(1); }, 2000); }
Always monitor worker crashes to avoid infinite restart loops.
You can add logging or alerts inside the exit event handler for better monitoring.
Use process.exit(code) in workers to simulate crashes during testing.
Use the cluster module to run multiple workers for better performance.
Listen to the exit event to detect worker crashes.
Restart workers automatically to keep your app running smoothly.
Practice
exit event on a worker in Node.js cluster module?Solution
Step 1: Understand the
Theexitevent roleexitevent is triggered when a worker process stops, either normally or due to a crash.Step 2: Identify the purpose of listening to
Listening toexitexithelps detect unexpected worker crashes so the master can respond.Final Answer:
To detect when a worker crashes or stops running -> Option DQuick Check:
exitevent = detect crash [OK]
- Confusing exit event with message passing
- Thinking exit event starts new workers automatically
- Assuming exit event logs CPU usage
Solution
Step 1: Recall event listener syntax on worker
In Node.js cluster, each worker is an EventEmitter and usesonto listen to events.Step 2: Match correct event and method
The correct event isexitand the method ison, soworker.on('exit', ...)is correct.Final Answer:
worker.on('exit', () => { /* handle exit */ }); -> Option BQuick Check:
Useonwithexiton worker [OK]
- Using .listen instead of .on
- Listening on cluster instead of worker
- Using wrong event name like 'workerExit'
const cluster = require('cluster');
if (cluster.isMaster) {
const worker = cluster.fork();
worker.on('exit', (code, signal) => {
console.log(`Worker exited with code ${code} and signal ${signal}`);
});
} else {
process.exit(1); // Simulate crash
}Solution
Step 1: Understand process.exit(1) effect
Callingprocess.exit(1)ends the worker with exit code 1, indicating an error.Step 2: Check exit event parameters
Theexitevent callback receives the exit code and signal; here signal isnullbecause no signal caused the exit.Final Answer:
Worker exited with code 1 and signal null -> Option CQuick Check:
Exit code 1 means crash, signal null if no signal [OK]
- Assuming exit code 0 means crash
- Confusing signal with exit code
- Thinking exit event won't fire on crash
const cluster = require('cluster');
if (cluster.isMaster) {
cluster.fork();
cluster.on('exit', (worker) => {
console.log('Worker crashed, restarting...');
cluster.fork();
});
}Solution
Step 1: Check where to listen for worker exit
The 'exit' event is emitted by the cluster module, and the callback receives (worker, code, signal).Step 2: Identify callback parameter mismatch
The code uses only one parameter (worker), but the event provides three parameters; this can cause confusion or errors.Final Answer:
The 'exit' event should be listened on 'cluster' but the callback parameter should be (worker, code, signal) -> Option AQuick Check:
cluster.on('exit', (worker, code, signal)) is correct [OK]
- Listening on cluster.workers instead of cluster
- Using wrong callback parameters
- Ignoring code and signal parameters
Solution
Step 1: Understand the need to limit restarts
Unlimited restarts can cause infinite loops if the worker crashes repeatedly.Step 2: Implement a counter and timestamp logic
Track how many times workers restart within a time window (e.g., 3 restarts per minute) and only restart if under the limit.Final Answer:
Use a counter and timestamp in the master process to track restarts; restart only if under limit -> Option AQuick Check:
Limit restarts with counter and time check [OK]
- Restarting without limits causing infinite loops
- Delaying restarts but not counting attempts
- Restarting only on exit code 0 (normal exit)
