Node.js Developer interview question · Most asked
How do you implement graceful shutdown in a Node.js server?
Summary
On SIGTERM/SIGINT, stop accepting new connections (server.close()), let in-flight requests finish (with a timeout), close keep-alive connections, stop consumers, close DB pools and other resources, flush logs, then exit.
Longer Answer
In Kubernetes, fail the readiness probe first so traffic stops arriving, then drain. server.closeIdleConnections() and closeAllConnections() (Node 18.2+) help with keep-alive sockets. Always set a hard timeout so a stuck request doesn't block shutdown forever.
Code Example
function shutdown(signal) {
logger.info({ signal }, "shutting down");
server.close(async () => {
await db.end();
await queue.close();
process.exit(0);
});
server.closeIdleConnections();
setTimeout(() => process.exit(1), 10_000).unref();
}
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
Key Points
- Handle SIGTERM/SIGINT
server.close()+ drain- Close DB pools and consumers
- Hard timeout fallback
More most-asked Node.js Developer questions
- Why is CPU-bound work a problem in Node.js and how do you handle it?
- What are streams in Node.js and what is backpressure?
- What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?
- Explain the phases of the Node.js event loop.
- What is Node.js and why is it well suited to I/O-heavy servers?
- How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?
- Walk through how an Express app handles a request, including errors from async handlers.
- What are the differences between CommonJS and ES modules in Node.js?