Backend & Node.js · APIs, data and failure
How do you implement graceful shutdown in a Node.js service?
Short answer
On SIGTERM, stop accepting new requests, mark readiness false, drain in-flight work, close consumers and pools, then exit. Set a hard deadline so a stuck request cannot block a deployment forever.
A deployment sends SIGTERM before killing a process. If the process exits immediately, in-flight requests fail and queue messages are abandoned. Graceful shutdown gives the instance time to finish work while the load balancer stops sending new traffic.
const server = app.listen(3000);
process.on("SIGTERM", () => {
server.close(async () => {
await pool.end();
process.exit(0);
});
setTimeout(() => process.exit(1), 10000).unref();
});The sequence
- Flip the readiness probe to false so the load balancer removes the instance
- Stop accepting new connections with server.close
- Let in-flight requests finish, with a bounded timeout
- Stop consuming from queues and finish or requeue current messages
- Close database pools, Redis clients and telemetry exporters
- Exit with a success code, or force exit after the deadline
The platform's termination grace period must be longer than your drain timeout, otherwise the process is killed before it finishes. In Kubernetes, readiness removal and SIGTERM are not instantaneous, so allow a short pre-stop delay if traffic still arrives. Background jobs need their own drain logic.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why should readiness fail before the server stops accepting connections?
- 2What happens to in-flight requests during server.close?
- 3How does the Kubernetes termination grace period relate to your drain timeout?
- 4Why must shutdown be idempotent?
Say it in the interview
On SIGTERM I mark the instance unready so the load balancer stops routing to it, then stop accepting new connections and let in-flight requests finish. I close queue consumers, database pools and telemetry clients, and I set a hard deadline that force-exits if something hangs. The platform grace period must be longer than my drain timeout, and the handler must tolerate a second signal.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Backend & Node.js mock interview and get scored feedback on depth, clarity and confidence.