typescriptadvanced
Graceful HTTP Server Shutdown
Production-ready server shutdown that drains active connections and closes resources cleanly.
typescriptPress ⌘/Ctrl + Shift + C to copy
import http from 'http';
function gracefulShutdown(server: http.Server, cleanupFn?: () => Promise<void>) {
let isShuttingDown = false;
const shutdown = async (signal: string) => {
if (isShuttingDown) return;
isShuttingDown = true;
console.log(`\n${signal} received. Starting graceful shutdown...`);
server.close(async () => {
console.log('HTTP server closed');
if (cleanupFn) await cleanupFn();
process.exit(0);
});
setTimeout(() => {
console.error('Forced shutdown after timeout');
process.exit(1);
}, 10_000);
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
}
export { gracefulShutdown };Use Cases
- Container deployments
- Zero-downtime deployments
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Graceful Server Shutdown
Handle SIGTERM and SIGINT signals to drain connections, close database pools, and exit cleanly.
Best for: Production server deployment
#server#shutdown
typescriptintermediate
Node.js Graceful Shutdown Handler
Implement graceful shutdown to properly close connections and finish requests before exit.
Best for: Production Node.js server reliability
#nodejs#shutdown
typescriptintermediate
WebSocket Server with ws
Create a WebSocket server with connection tracking, heartbeat ping/pong, and typed message handling.
Best for: Chat applications
#websocket#realtime
typescriptbeginner
Native HTTP Server
Create a lightweight HTTP server using Node.js built-in http module with routing and JSON responses.
Best for: Lightweight API server without frameworks
#nodejs#http