What is graceful shutdown in Node.js and how do you implement it?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized Node.js deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
Graceful shutdown is the process of cleanly stopping a Node.js server by: (1) stopping acceptance of new connections, (2) waiting for in-flight requests to complete, (3) closing database connections, message queue connections, and other resources. Without it, mid-flight requests are killed, causing errors for users and potential data corruption. Implementation: listen to shutdown signals — process.on("SIGTERM", shutdown) and process.on("SIGINT", shutdown) (Ctrl+C). In the shutdown handler: (1) call server.close(callback) — stops accepting new connections, waits for active connections; (2) close database pools: await pool.end();; (3) close Redis clients; (4) flush log buffers; (5) call process.exit(0) after cleanup. Add a timeout (e.g., 30s) to force exit if cleanup hangs: setTimeout(() => process.exit(1), 30000);. In Kubernetes, containers receive SIGTERM before SIGKILL (default 30s grace period) — configure this to allow enough time for your app's shutdown. Libraries like terminus simplify health checks and graceful shutdown for Express/Fastify.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What is circuit breaking pattern in Node.js microservices?
Next
What is connection pooling for HTTP requests in Node.js?
More Node.js Questions
View all →- Advanced How does Node.js handle concurrency without multiple threads?
- Advanced What is the Node.js memory model and how does garbage collection work?
- Advanced What are memory leaks in Node.js and how do you detect them?
- Advanced What is the difference between process.exit() and throwing an uncaught exception?
- Advanced What is the N+1 query problem and how do you solve it in Node.js?