HTTP Graceful Shutdown

3.1.16 · active · verified Sun Apr 19

http-graceful-shutdown is a Node.js utility library designed to ensure HTTP and HTTPS servers (including those built with frameworks like Express, Koa, and Fastify, or native Node.js http/http2) shut down cleanly and without disrupting active client connections. It manages open sockets, stops accepting new connections, and allows for the registration of custom cleanup functions (e.g., closing database connections) to execute before the server fully terminates. The library tracks all connections, gracefully communicates shutdown intent to clients, and can optionally destroy remaining sockets forcefully after a timeout. Version 3.1.16 is the current stable release, with version 3.0 being a significant update that improved internal handling while maintaining backward compatibility with 2.x. It has seen over 35 million downloads, indicating its widespread adoption for robust application termination. The release cadence appears stable, with major versions being well-tested.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `http-graceful-shutdown` with an Express application, showing server initialization, handling a simulated long-running request, and registering custom cleanup functions during a graceful shutdown triggered by signals like `SIGINT` or `SIGTERM`.

const express = require('express');
const http = require('http');
const gracefulShutdown = require('http-graceful-shutdown');

const app = express();
app.get('/', (req, res) => {
  console.log('Request received at /');
  // Simulate a long-running request that might be in progress during shutdown
  setTimeout(() => {
    res.send('Hello from server! Shutting down soon...');
  }, 2000);
});

const PORT = process.env.PORT || 3000;
const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log('Press Ctrl+C to initiate graceful shutdown.');
});

// This enables the graceful shutdown mechanism
gracefulShutdown(server, {
  forceExit: true, // Default is true, causes process.exit after timeout
  timeout: 10000, // how long to wait before force exiting (in ms)
  // Register custom cleanup functions to run before the server fully terminates
  onShutdown: async (signal) => {
    console.log(`Server received ${signal}. Running cleanup...`);
    // Example: Close database connections or other resources
    await new Promise(resolve => setTimeout(resolve, 3000)); // Simulate async cleanup
    console.log('Cleanup complete!');
  },
  finally: () => {
    console.log('Server shutdown sequence finished. Goodbye!');
  }
});

view raw JSON →