Graceful reload
- Node.js course
- Advanced
- Lesson 5/83
- 5 min
Learn graceful reload with clusters.
Graceful reload
Graceful reload means restarting workers one by one without stopping the server. The goal is to deploy new code with zero connection drops.
A common method: send the master a SIGUSR2 signal. The master catches the signal, starts a new worker for each existing one, then calls worker.disconnect() on the old worker. The old worker finishes pending requests and exits.
The exit event
The cluster.on("exit") event fires when a worker crashes or is closed. It is the core tool for graceful reload and auto-restart.
The handler takes two parameters: worker and code (the exit code). When a worker dies you call cluster.fork() to start a replacement. This makes your app crash-resilient. A non-zero exit code signals an unexpected crash.
Practice Register an exit handler
Listen for the "exit" event on cluster; inside the handler call cluster.fork(). Then log "reload ready".
Starter code
// Import the cluster module
// listen for exit, call fork
// log "reload ready"Sample solution
const cluster = require("cluster");
cluster.on("exit", () => { cluster.fork(); });
console.log("reload ready");Expected output
reload ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the event name
cluster.on("____", (worker) => { cluster.fork(); })
cluster.on("exit", (worker) => { cluster.fork(); })
Explanation: The exit event fires when a worker dies.
2 Match each piece to its role
| Term | Meaning |
|---|---|
cluster.on("exit") |
Fires on worker exit |
cluster.fork() |
Starts new worker |
SIGUSR2 |
Reload signal |
graceful |
Zero downtime |
3 Which signal triggers a graceful reload?
- SIGUSR2 Correct answer
- SIGKILL
- SIGTERM
- SIGINT
Explanation: SIGUSR2 is the common signal for graceful reload.