View as Json

Graceful Shutdown Handler

A standardized way to handle graceful shutdowns in Express applications, ensuring all requests are finished and resources are released.

Installation Guide

Install the component using the servercn CLI:

npx servercn-cli@latest add shutdown-handler

Why Graceful Shutdown Matters

When an application is restarted or stopped (e.g., during a deployment or scaling event), it's important to finish current work. Without graceful shutdown:

  • Active HTTP requests are abruptly terminated, leading to errors for users.
  • Database connections might be left in a "hanging" state.
  • Background tasks might be interrupted without saving progress.


Basic Implementation

src/utils/shutdown.ts
import { Server } from "http";
 
export const configureGracefulShutdown = (server: Server) => {
  const signals = ["SIGTERM", "SIGINT"];
 
  signals.forEach(signal => {
    process.on(signal, () => {
      console.log(`\n${signal} signal received. Shutting down gracefully...`);
 
      server.close(err => {
        if (err) {
          console.error("Error during server close:", err);
          process.exit(1);
        }
 
        console.log("HTTP server closed.");
        // Add additional cleanup logic here (e.g., closing database connections)
        process.exit(0);
      });
 
      // Force shutdown after 10 seconds
      setTimeout(() => {
        console.error(
          "Could not close connections in time, forcefully shutting down"
        );
        process.exit(1);
      }, 10000);
    });
  });
};

Usage

Import and apply the shutdown handler in your main entry file (usually server.ts).

src/server.ts
import http from "http";
import app from "./app";
import { configureGracefulShutdown } from "./utils/shutdown";
 
const server = http.createServer(app);
 
const PORT = process.env.PORT || 3000;
 
server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
 
// Apply graceful shutdown
configureGracefulShutdown(server);

File & Folder Structure

......

Installation

npx servercn-cli@latest add shutdown-handler

Contributed by