typescriptadvanced

Graceful HTTP Server Shutdown

Production-ready server shutdown that drains active connections and closes resources cleanly.

typescript
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.