Node.js

Tutorial: Graceful Shutdown in Node.js 22: The Signal Handler Most Tutorials Get Wrong

Tutorial: Graceful Shutdown in Node.js 22: The Signal Handler Most Tutorials Get Wrong

Most "graceful shutdown" snippets for Node.js register a SIGTERM listener that calls server.close() and then process.exit(0) immediately inside the callback. That works in a demo with one idle request. In production it drops in-flight requests, abandons keep-alive sockets, and skips cleanup for anything asynchronous you started in that callback. The detail most guides get wrong is that server.close() only stops accepting new connections — it does not terminate idle keep-alive connections, so the callback may never fire, and it says nothing about your database pool, your timers, or your background work.

This tutorial builds a shutdown path that actually finishes. You will end up with a small module you can drop into an HTTP server, wired to Node.js 22's built-in server.closeIdleConnections() and AbortSignal.timeout, with a hard deadline so a stuck handler cannot keep the process alive forever. The code targets Node.js 22 (current LTS line at the time of writing); the APIs used are stable there and require no dependencies.

Prerequisites

  • Node.js 22.x installed (node --version should print v22. something).
  • No framework required. We use the built-in http module so the mechanics are visible, but the same hooks apply to Express or Fastify.

Step 1: Build a server that simulates slow work

Create server.js:

JavaScript
import http from 'node:http';
import { setTimeout as delay } from 'node:timers/promises';

const activeRequests = new Set();

export function createServer() {
  const server = http.createServer(async (req, res) => {
    const token = Symbol('request');
    activeRequests.add(token);

    try {
      if (req.url === '/slow') {
        await delay(5000);
        res.writeHead(200, { 'content-type': 'text/plain' });
        res.end('slow response finished\n');
      } else {
        res.writeHead(200, { 'content-type': 'text/plain' });
        res.end('ok\n');
      }
    } finally {
      activeRequests.delete(token);
    }
  });

  server.keepAliveTimeout = 65_000;
  server.headersTimeout = 66_000;

  return { server, activeRequests };
}

The activeRequests set is only for observability here; the shutdown logic does not strictly need it, because the server tracks its own connections. Keep it anyway if you have work that outlives the response.

Step 2: Write a shutdown function with a real deadline

The naive version:

JavaScript
process.on('SIGTERM', () => {
  server.close(() => process.exit(0));
});

Two problems. First, an idle keep-alive connection holds the server open, so the callback never runs and the orchestrator eventually sends SIGKILL. Second, if a handler hangs, nothing bounds the wait.

Here is the version that behaves:

JavaScript
import { closePool } from './db.js';

let shuttingDown = false;

export async function shutdown({ server, timeoutMs = 10_000 }) {
  if (shuttingDown) return;
  shuttingDown = true;

  console.log('shutdown: stop accepting connections');
  server.close();

  // Drop connections that are idle right now (keep-alive with no request in flight).
  server.closeIdleConnections();

  // New connections become impossible; force out anything still in flight after the deadline.
  const deadline = setTimeout(() => {
    console.warn('shutdown: deadline reached, forcing close');
    server.closeAllConnections();
  }, timeoutMs);
  deadline.unref();

  await new Promise((resolve) => server.once('close', resolve));
  clearTimeout(deadline);

  console.log('shutdown: draining database pool');
  await closePool();

  console.log('shutdown: done');
}

Key points:

  • server.close() returns immediately and stops accepting. The 'close' event fires only once every connection is gone.
  • server.closeIdleConnections() is what makes the 'close' event reachable. Without it, a client holding a keep-alive socket blocks shutdown until keepAliveTimeout elapses.
  • server.closeAllConnections() is the sledgehammer for the deadline branch. Calling it on a normal path would drop legitimate in-flight requests, which is why it lives inside the timeout callback.
  • deadline.unref() prevents the timer from being the thing that keeps the event loop alive if the server closes early. clearTimeout afterwards is belt-and-braces.

Both closeIdleConnections and closeAllConnections were added in Node.js 18.2 and are stable through 22, so you are not relying on experimental flags.

Step 3: Wire the signals

JavaScript
import process from 'node:process';
import { createServer } from './server.js';
import { shutdown } from './shutdown.js';

const { server } = createServer();

const PORT = Number(process.env.PORT ?? 3000);
server.listen(PORT, () => {
  console.log(`listening on ${PORT}`);
});

for (const signal of ['SIGTERM', 'SIGINT']) {
  process.on(signal, () => {
    console.log(`received ${signal}`);
    shutdown({ server }).finally(() => process.exit(0));
  });
}

Register the handler after listen, and register it once. Adding a listener on every request is a leak that will eventually hit Node's max-listener warning.

⚠️ Common mistake: calling process.exit() inside the SIGTERM handler. process.exit terminates the event loop immediately — pending promises, open file handles, and in-flight responses are abandoned. Only call it once the shutdown promise resolves (or in the deadline branch).

Step 4: Account for the pieces that are not the HTTP server

Node's built-in server tracks TCP connections. It does not know about:

  • Your database connection pool. If you are using a pool library that exposes pool.end() (or equivalent), call it after the server closes so queries finish before the process exits.
  • setInterval timers in cached modules. Clear them or unref() them; otherwise the event loop stays alive even after process.exit is skipped for some reason.
  • Third-party clients (message brokers, caches) with their own connection objects. Each needs its own close call inside shutdown, sequenced after the HTTP drain.

If you maintain an activeRequests-style set of in-flight jobs, wait for it to empty, or combine it with the abort signal pattern below.

Step 5: Bound the work, not just the connections

AbortSignal.timeout in Node.js 22 is the clean way to give your own async work a hard ceiling:

JavaScript
const controller = new AbortController();

function signalFor(ms) {
  return AbortSignal.timeout(ms);
}

await closePool({ signal: signalFor(8000) });

If closePool accepts an AbortSignal, use it so a hung drain is cut short rather than outliving the orchestrator's kill window. If the library does not accept a signal, race it manually:

JavaScript
await Promise.race([
  closePool(),
  new Promise((_, reject) =>
    setTimeout(() => reject(new Error('pool close timeout')), 8000).unref()
  ),
]).catch((err) => {
  console.warn('pool close did not finish:', err.message);
});

Reset shuttingDown to false only if you have a reload path; a one-way latch is usually correct because a second signal during shutdown should be ignored, not attempt a second close.

Step 6: Make the deadline smaller than your orchestrator's grace period

Kubernetes sends SIGTERM and waits terminationGracePeriodSeconds (30 by default) before sending SIGKILL. Docker Compose sends SIGTERM and waits 10 seconds by default. You have two constraints:

The orchestrator's grace period is the outer bound. Your internal deadline must be smaller — 10 seconds against a 30-second grace period gives you room to drain connections and finish cleanup. If your internal timeout exceeds the grace period, the cleanup is wasted work.

Set them explicitly:

YAML
# docker-compose.yml excerpt
services:
  api:
    stop_grace_period: 20s

In Kubernetes, terminationGracePeriodSeconds: 30 on the pod spec, plus a preStop hook with a short sleep, is the common pairing for load-balancer propagation. Both knobs are configuration, not code, so check them whenever you wonder why a deploy rolls slower than expected.

Step 7: Verify the behavior

Run the server and simulate a slow request in one terminal:

Bash
curl http://localhost:3000/slow

In another, send SIGTERM:

Bash
kill -TERM $(pgrep -f "node server.js")

Expected: the slow request finishes with slow response finished; the log shows the drain sequence; the process exits 0. Open an idle connection with curl --no-buffer pointed at a slow endpoint, hold it, send SIGTERM, and confirm the idle keep-alive connection is closed rather than blocking exit. That behavior is the whole point of closeIdleConnections.

Then simulate a hung handler (comment out the res.end and make the delay 60 seconds). With the 10-second internal deadline, you should see deadline reached, forcing close followed by exit — much faster than the orchestrator's kill.

When not to use this pattern

If your process is a one-shot CLI or a short-lived Lambda, there is no orchestrator sending SIGTERM and no keep-alive pool to drain; a plain process.exit(0) inside the success path is fine. Cluster workers (cluster.fork) need extra handling: the worker must exit and the primary must re-fork or refuse new work, so this shutdown runs inside each worker while the primary handles its own signals. Finally, if your HTTP layer sits behind a reverse proxy, respect the proxy's keepalive and idle timeouts too, or clients can reuse a connection the backend has already closed.

Summary

  • server.close() stops accepting connections but leaves idle keep-alive sockets open; call server.closeIdleConnections() so the 'close' event can fire.
  • Never call process.exit() inside a signal handler; resolve your shutdown promise first, then exit.
  • Use a hard deadline with setTimeout(...).unref() and server.closeAllConnections() in the timeout branch to bound stuck requests.
  • Clean up what the HTTP server does not own: database pools, timers, and client connections, each with its own close call and time limit.
  • Keep your internal timeout below the orchestrator's grace period (Docker's stop_grace_period, Kubernetes' terminationGracePeriodSeconds), and test with a real slow request and a real hanging handler.
Advertisement