How do you implement a graceful shutdown in Express.js?
Answer
A graceful shutdown allows in-flight requests to complete before the process exits, preventing data corruption and incomplete responses during deployments or crashes. Listen for OS signals: process.on('SIGTERM', shutdown); process.on('SIGINT', shutdown);. In the shutdown handler: server.close(() => { db.disconnect(); process.exit(0); });. server.close() stops accepting new connections but lets existing ones finish. Set a timeout to force-exit if connections take too long: setTimeout(() => process.exit(1), 30000);. Also close database connections, flush logs, and deregister from service discovery. Container orchestration systems (Kubernetes) send SIGTERM before killing a container, giving your app the window to shut down cleanly.
Previous
What is the difference between Express 4.x and Express 5.x?
Next
How do you implement request tracing and correlation IDs in Express?
More Express.js Questions
View all →- Advanced How do you implement WebSocket support alongside Express.js?
- Advanced What are security best practices for Express.js APIs?
- Advanced How does clustering work in Node.js/Express for better performance?
- Advanced What is the difference between Express 4.x and Express 5.x?
- Advanced How do you implement request tracing and correlation IDs in Express?