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.