Graceful shutdown — finish in-flight requests before closing the server.
1const http = require("http");23const server = http.createServer(app);45function gracefulShutdown(signal) {6 console.log(`${signal} received. Starting graceful shutdown...`);78 server.close(() => {9 console.log("HTTP server closed");10 // Close database connections11 db.pool.end();12 // Close Redis13 redis.quit();14 process.exit(0);15 });1617 // Force shutdown after 30 seconds18 setTimeout(() => {19 console.error("Forced shutdown");20 process.exit(1);21 }, 30000);22}2324process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));25process.on("SIGINT", () => gracefulShutdown("SIGINT"));2627server.listen(3000);
Key steps: