0
0
Node.jsframework~30 mins

Handling worker crashes and restart in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling worker crashes and restart
📖 Scenario: You are building a Node.js application that uses the cluster module to create worker processes. Sometimes, a worker might crash unexpectedly. To keep the app running smoothly, you want to detect when a worker crashes and restart it automatically.
🎯 Goal: Build a Node.js cluster setup that creates one worker process, listens for worker crashes, and restarts the worker automatically when it crashes.
📋 What You'll Learn
Use the Node.js cluster module
Create exactly one worker process
Detect when the worker process exits unexpectedly
Restart the worker automatically after a crash
💡 Why This Matters
🌍 Real World
Many Node.js server applications use clustering to improve performance and reliability. Handling worker crashes and restarting them automatically keeps the app available without manual intervention.
💼 Career
Understanding how to manage worker processes and handle crashes is important for backend developers working with Node.js in production environments.
Progress0 / 4 steps
1
Setup cluster and create one worker
Write code to import the cluster and os modules. Then check if the current process is the master process using cluster.isMaster. If it is, create exactly one worker process using cluster.fork(). If it is a worker process, write a simple HTTP server that listens on port 8000 and responds with 'Hello from worker'.
Node.js
Need a hint?

Use cluster.isMaster to check if the current process is the master. Use cluster.fork() to create a worker. In the worker, create a simple HTTP server.

2
Add a crash simulation in the worker
Inside the worker process code, add a timer that crashes the worker after 5 seconds by calling process.exit(1). This simulates a worker crash.
Node.js
Need a hint?

Use setTimeout to schedule process.exit(1) after 5000 milliseconds.

3
Detect worker exit and restart it
In the master process code, listen for the 'exit' event on cluster. When a worker exits, log a message with console.log that the worker died. Then restart the worker by calling cluster.fork() again.
Node.js
Need a hint?

Use cluster.on('exit', callback) in the master to detect worker crashes. Inside the callback, log the worker's PID and call cluster.fork() to restart.

4
Add graceful shutdown for workers
In the master process, listen for the 'SIGINT' signal (Ctrl+C). When received, log 'Master shutting down', disconnect the cluster using cluster.disconnect(), and exit the process with process.exit(0). This ensures workers close gracefully.
Node.js
Need a hint?

Use process.on('SIGINT', callback) in the master to catch Ctrl+C. Inside, log a message, call cluster.disconnect(), and then exit the process.