Testing, Performance & Deployment
Node.js Graceful Shutdown
A graceful shutdown stops accepting new connections, lets in-flight requests finish, closes database connections, and only then exits — so a deploy or restart does not drop live requests.
What is Graceful Shutdown in Node.js?
A graceful shutdown stops accepting new connections, lets in-flight requests finish, closes database connections, and only then exits — so a deploy or restart does not drop live requests.
Graceful Shutdown example
JavaScript
const server = app.listen(config.port);
async function shutdown(signal) {
logger.info({ signal }, 'shutting down');
server.close(async () => { // stop accepting new connections
try {
await mongoose.connection.close();
await redis.quit();
logger.info('closed cleanly');
process.exit(0);
} catch (err) {
logger.error({ err }, 'error during shutdown');
process.exit(1);
}
});
// do not hang forever if something refuses to close
setTimeout(() => {
logger.error('forced shutdown after timeout');
process.exit(1);
}, 10_000).unref();
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));Key points to remember
- Docker, Kubernetes and PM2 all send SIGTERM before killing a process.
- Always include a forced-exit timer — a stuck connection should not block the deploy.
- unref() on that timer lets the process exit early if shutdown finishes first.
Common mistakes with Graceful Shutdown
- No SIGTERM handler, so every deploy drops in-flight requests.
- Calling process.exit() immediately, truncating responses and pending writes.
Node.js Graceful Shutdown— Interview Questions & FAQs
Why do requests fail during deployment?+
The process is killed while requests are in flight. Handle SIGTERM, call server.close() to stop accepting new connections, wait for existing ones to finish, then exit.
