Bird
Raised Fist0
Node.jsframework~20 mins

Handling worker crashes and restart in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Node.js Cluster Crash Handler
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a worker crashes in this Node.js cluster code?

Consider this Node.js cluster code snippet. What will be the output behavior when a worker process crashes?

Node.js
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
}
AThe primary ignores worker crashes and no logs are shown.
BThe primary automatically restarts each worker after it crashes.
CThe primary logs each worker's death but does not restart any workers.
DThe primary crashes as well when any worker crashes.
Attempts:
2 left
💡 Hint

Look at the cluster event listeners and what happens on 'exit'.

📝 Syntax
intermediate
2:00remaining
Which option correctly restarts a worker after it crashes?

Given this cluster setup, which code snippet correctly restarts a worker when it crashes?

Node.js
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
}
Acluster.on('exit', (worker) => { cluster.fork(); });
Bcluster.on('exit', (worker) => { worker.fork(); });
Ccluster.on('exit', () => { cluster.restart(); });
Dcluster.on('exit', (worker) => { cluster.fork(worker.id); });
Attempts:
2 left
💡 Hint

Remember how to create new workers in Node.js cluster.

🔧 Debug
advanced
2:00remaining
Why does this cluster code fail to restart workers properly?

Examine this code snippet. Why does it fail to restart workers after they crash?

Node.js
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);
}
Acluster.fork() does not accept any arguments, so passing worker.id causes an error and no restart.
BThe 'exit' event is not emitted on worker crashes, so the handler never runs.
CThe worker process exits with code 1, which prevents cluster from restarting it.
DThe code forks too many workers causing resource exhaustion.
Attempts:
2 left
💡 Hint

Check the cluster.fork() method signature.

state_output
advanced
2:00remaining
What is the number of active workers after a crash and restart?

Given this cluster code, how many worker processes will be active after one worker crashes and the restart code runs?

Node.js
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);
}
ANo workers remain active after the crash.
BThe number of active workers decreases by one and never recovers.
CThe number of active workers doubles after the restart.
DThe number of active workers remains equal to the number of CPUs.
Attempts:
2 left
💡 Hint

Think about how cluster.fork() replaces crashed workers.

🧠 Conceptual
expert
2:00remaining
Why is it important to handle worker crashes and restart in Node.js clusters?

Choose the best explanation for why managing worker crashes and restarts is critical in Node.js cluster applications.

ATo reduce CPU usage by stopping workers that crash frequently.
BTo ensure the application remains available and responsive by replacing failed workers automatically.
CTo prevent the primary process from using too much memory by restarting workers manually.
DTo allow workers to share memory directly without restarting.
Attempts:
2 left
💡 Hint

Think about what happens if workers crash and are not restarted.

Practice

(1/5)
1. What is the main purpose of listening to the exit event on a worker in Node.js cluster module?
easy
A. To log the worker's CPU usage
B. To start a new worker automatically
C. To send messages between workers
D. To detect when a worker crashes or stops running

Solution

  1. Step 1: Understand the exit event role

    The exit event is triggered when a worker process stops, either normally or due to a crash.
  2. Step 2: Identify the purpose of listening to exit

    Listening to exit helps detect unexpected worker crashes so the master can respond.
  3. Final Answer:

    To detect when a worker crashes or stops running -> Option D
  4. Quick Check:

    exit event = detect crash [OK]
Hint: Remember: exit event means worker stopped or crashed [OK]
Common Mistakes:
  • Confusing exit event with message passing
  • Thinking exit event starts new workers automatically
  • Assuming exit event logs CPU usage
2. Which of the following is the correct way to listen for a worker's exit event in Node.js cluster?
easy
A. cluster.on('exit', worker => { /* handle exit */ });
B. worker.on('exit', () => { /* handle exit */ });
C. worker.listen('exit', () => { /* handle exit */ });
D. process.on('workerExit', () => { /* handle exit */ });

Solution

  1. Step 1: Recall event listener syntax on worker

    In Node.js cluster, each worker is an EventEmitter and uses on to listen to events.
  2. Step 2: Match correct event and method

    The correct event is exit and the method is on, so worker.on('exit', ...) is correct.
  3. Final Answer:

    worker.on('exit', () => { /* handle exit */ }); -> Option B
  4. Quick Check:

    Use on with exit on worker [OK]
Hint: Use worker.on('exit', callback) to catch exit events [OK]
Common Mistakes:
  • Using .listen instead of .on
  • Listening on cluster instead of worker
  • Using wrong event name like 'workerExit'
3. Given the code below, what will be logged when a worker crashes?
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
}
medium
A. Worker exited with code null and signal SIGTERM
B. Worker exited with code 0 and signal null
C. Worker exited with code 1 and signal null
D. No output because exit event is not triggered

Solution

  1. Step 1: Understand process.exit(1) effect

    Calling process.exit(1) ends the worker with exit code 1, indicating an error.
  2. Step 2: Check exit event parameters

    The exit event callback receives the exit code and signal; here signal is null because no signal caused the exit.
  3. Final Answer:

    Worker exited with code 1 and signal null -> Option C
  4. Quick Check:

    Exit code 1 means crash, signal null if no signal [OK]
Hint: Exit code 1 means crash, signal null if no signal sent [OK]
Common Mistakes:
  • Assuming exit code 0 means crash
  • Confusing signal with exit code
  • Thinking exit event won't fire on crash
4. Identify the error in this code snippet that tries to restart a worker after it crashes:
const cluster = require('cluster');
if (cluster.isMaster) {
  cluster.fork();
  cluster.on('exit', (worker) => {
    console.log('Worker crashed, restarting...');
    cluster.fork();
  });
}
medium
A. The 'exit' event should be listened on 'cluster' but the callback parameter should be (worker, code, signal)
B. The 'exit' event should be listened on 'cluster.workers', not 'cluster'
C. The 'exit' event should be listened on 'cluster' but the callback parameters are wrong
D. The 'exit' event callback parameters are incorrect; it should receive (code, signal)

Solution

  1. 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).
  2. 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.
  3. Final Answer:

    The 'exit' event should be listened on 'cluster' but the callback parameter should be (worker, code, signal) -> Option A
  4. Quick Check:

    cluster.on('exit', (worker, code, signal)) is correct [OK]
Hint: cluster.on('exit') callback needs (worker, code, signal) parameters [OK]
Common Mistakes:
  • Listening on cluster.workers instead of cluster
  • Using wrong callback parameters
  • Ignoring code and signal parameters
5. You want to ensure your Node.js app automatically restarts a worker if it crashes, but only up to 3 restarts per minute to avoid infinite loops. Which approach best implements this behavior?
hard
A. Use a counter and timestamp in the master process to track restarts; restart only if under limit
B. Restart workers immediately on every exit event without limits
C. Use a setTimeout to delay restarts by 1 minute after each crash
D. Restart workers only if exit code is 0, ignore other exit codes

Solution

  1. Step 1: Understand the need to limit restarts

    Unlimited restarts can cause infinite loops if the worker crashes repeatedly.
  2. 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.
  3. Final Answer:

    Use a counter and timestamp in the master process to track restarts; restart only if under limit -> Option A
  4. Quick Check:

    Limit restarts with counter and time check [OK]
Hint: Count restarts with time checks to avoid infinite loops [OK]
Common Mistakes:
  • Restarting without limits causing infinite loops
  • Delaying restarts but not counting attempts
  • Restarting only on exit code 0 (normal exit)