What if your server could heal itself instantly after a crash without you lifting a finger?
Why Handling worker crashes and restart in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a Node.js server running multiple worker processes to handle tasks. Suddenly, one worker crashes unexpectedly. Without any automatic recovery, your server loses that worker and stops processing some tasks.
Manually monitoring and restarting crashed workers is slow and error-prone. You might miss crashes, causing downtime or lost requests. Writing complex code to track and restart workers wastes time and adds bugs.
Node.js provides built-in ways to detect when a worker crashes and automatically restart it. This keeps your server healthy without manual checks, ensuring smooth and reliable task processing.
if(worker.exited) { startNewWorker(); } // manual check and restart
cluster.on('exit', (worker, code, signal) => { cluster.fork(); }); // automatic restart on crashThis lets your Node.js app recover from crashes instantly, keeping services available and users happy without extra manual work.
A chat app uses multiple workers to handle messages. If one crashes, automatic restart means users don't notice any interruption in their conversations.
Manual crash handling is unreliable and complex.
Automatic worker restart keeps your app stable.
Node.js cluster module simplifies crash recovery.
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)
