Graceful Shutdown Handler

The Graceful Shutdown Handler ensures that your Express application terminates safely and predictably when the process receives termination signals (like SIGTERM or SIGINT).

It allows the server to:

  1. Stop accepting new connections.
  2. Complete all in-flight requests.
  3. Release resources (like database connections) before exiting.

Installation Guide

Install the component using the ServerCN CLI:

npx servercn 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.

Implementation

The component provides a configureGracefulShutdown function that takes your HTTP server instance.

MVC Structure

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);
    });
  });
};

Import and apply the shutdown handler in your main entry file (usually 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);

Best Practices

You should extend the server.close callback to include logic for closing your database connections.

server.close(async err => {
  // Example: Mongoose cleanup
  await mongoose.connection.close();
  console.log("Database connection closed.");
  process.exit(err ? 1 : 0);
});

In modern cloud environments:

  • SIGTERM: Sent by Kubernetes or Docker when a pod/container is being deleted.
  • SIGINT: Sent when you press Ctrl+C in your terminal.

Both are handled by this component.

Summary

The Graceful Shutdown Handler is a critical component for production-ready applications, ensuring high availability and data integrity during process termination.

File & Folder Structure

Select a file to view its contents

Installation

npx servercn add shutdown-handler