Q31: How do you implement Graceful Shutdown in Express?
Graceful shutdown prevents dropping active HTTP connections when a deployment or process termination event occurs (e.g., SIGTERM, SIGINT).
Handling SIGTERM Graceful Shutdown
const server = app.listen(3000);
process.on('SIGTERM', () => {
console.log('SIGTERM received. Closing HTTP server...');
server.close(() => {
console.log('HTTP server closed. Cleaning DB connections...');
mongoose.connection.close(false, () => {
console.log('Process terminated cleanly.');
process.exit(0);
});
});
});💡 server.close stops accepting new incoming connections while allowing active requests to complete cleanly before terminating.
Key Takeaways
- Stop accepting new incoming requests using
server.close(). - Allow active requests to finish and close database pools cleanly before exiting.