Graceful HTTP Server Shutdown

1.0.0 · maintenance · verified Wed Apr 22

This `http-close` package for Node.js provides a mechanism to gracefully shut down an HTTP server by managing open TCP sockets. Currently at version 1.0.0, it appears to be a stable utility, likely in maintenance mode given its focused scope and the absence of rapid version increments. It differentiates itself by intelligently handling various socket states during `server.close()`: it destroys keep-alive sockets without active responses, sends `Connection: close` headers for requests where headers haven't been sent, and applies a configurable timeout (default 5 seconds) to pending connections. If a socket times out after `server.close()` has been called, the module intervenes to respond with a 500 status code before ending the connection for requests with unsent headers, and forcefully destroys all other remaining sockets. This ensures a clean exit for the server process, mitigating the common issue of hanging connections during shutdown.

Common errors

Warnings

Install

Imports

Quickstart

This example sets up an HTTP server with `http-close` to manage graceful shutdown. It simulates asynchronous request handling and demonstrates how to hook `http-close` to the server and trigger shutdown via `server.close()` in response to OS signals (SIGTERM/SIGINT), ensuring open connections are handled gracefully with a specified timeout.

import http from 'http';
import httpClose from 'http-close';

const server = http.createServer((req, res) => {
  // Simulate some async work that might keep the connection open
  setTimeout(() => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!\n');
  }, Math.random() * 500); // Random delay up to 500ms
});

// Add http-close hook with a custom timeout of 3 seconds
httpClose({ timeout: 3000 }, server);

server.listen(3000, () => {
  console.log('Server listening on port 3000. Try hitting it with requests.');
  console.log('Then, press Ctrl+C to initiate graceful shutdown.');
});

// Handle graceful shutdown on process termination signals
process.on('SIGTERM', () => {
  console.log('SIGTERM received. Initiating graceful shutdown...');
  server.close(() => {
    console.log('Server closed. Exiting process.');
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  console.log('SIGINT received. Initiating graceful shutdown...');
  server.close(() => {
    console.log('Server closed. Exiting process.');
    process.exit(0);
  });
});

view raw JSON →