research/graceful-shutdown-for-a-node-http-server

Graceful Shutdown for a Node.js HTTP Server: Finishing In-Flight Requests on SIGTERM

Engineering Note · November 27, 2026 · 8 minute read · Node.js · HTTP · Reliability · Testing

When a Node.js HTTP server receives SIGTERM (the polite “please stop” signal a deploy or process manager sends), it exits at once unless you handle the signal, and every request in progress gets a dropped connection. The fix is to call server.close() in a SIGTERM handler, which stops new connections and lets in-flight requests finish, plus a deadline that forces the exit if a request hangs. Our test found one more catch: a keep-alive connection can keep the process alive for the full keep-alive timeout after the last response. Sending Connection: close while shutting down fixes that.

Everything below was run on Linux with Node.js 22.23.5, using only node:http and node:child_process. The outputs are real.

Why does this matter for a small app?

Every deploy, restart or scale-down stops the running process. If a customer is halfway through submitting a booking or a payment form at that moment, a dropped connection means an error page, and sometimes a booking that was saved on the server while the customer was told it failed. Restarts happen more often than most people expect, so a server that stops cleanly is worth the 20 lines it takes.

What did we test?

A server with one route that waits a given number of milliseconds before answering, so we could have slow requests in flight on demand. The final version, with all three shutdown modes:

import http from 'node:http';
const mode = process.argv[2]; // naive | close | graceful | graceful-close-header
let inFlight = 0;
let shuttingDown = false;
const server = http.createServer(async (req, res) => {
  inFlight++;
  const ms = Number(new URL(req.url, 'http://localhost').searchParams.get('ms') ?? 0);
  await new Promise((r) => setTimeout(r, ms));
  if (shuttingDown) res.setHeader('Connection', 'close');
  res.end(`done after ${ms} ms\n`);
  inFlight--;
});
if (process.env.KA_MS) server.keepAliveTimeout = Number(process.env.KA_MS);
server.listen(3100, () => console.log(`[${mode}] listening, pid ${process.pid}`));
let sig = 0;
const t0 = () => `+${((performance.now() - sig) / 1000).toFixed(2)}s`;
if (mode === 'close') {
  process.on('SIGTERM', () => {
    sig = performance.now();
    console.log(`${t0()} SIGTERM, in flight: ${inFlight}`);
    server.close(() => { console.log(`${t0()} closed, exiting`); process.exit(0); });
  });
}
if (mode.startsWith('graceful')) {
  process.on('SIGTERM', () => {
    sig = performance.now();
    if (mode === 'graceful-close-header') shuttingDown = true;
    console.log(`${t0()} SIGTERM, in flight: ${inFlight}`);
    server.close(() => { console.log(`${t0()} all requests finished, exiting`); process.exit(0); });
    server.closeIdleConnections();
    setTimeout(() => {
      console.log(`${t0()} deadline hit, in flight: ${inFlight}, forcing`);
      server.closeAllConnections();
      process.exit(1);
    }, Number(process.env.DEADLINE_MS ?? 10000)).unref();
  });
}

Times printed by the server (+2.81s) are measured from the moment it received SIGTERM. A harness starts the server, sends slow requests (1 second and 3 seconds), sends SIGTERM 200 ms later, tries one new request 300 ms after that, then waits for everything to finish. Its own times are from when it sent the first request.

What happens with no SIGTERM handler?

== naive
[naive] listening, pid 1066
sending SIGTERM at 0.21s
request 3000 ms -> error ECONNRESET at 0.22s
request 1000 ms -> error ECONNRESET at 0.22s
new request after SIGTERM: error ECONNREFUSED at 0.51s
server exited: SIGTERM at 0.52s

Both requests in progress were cut off within 10 ms of the signal. The clients got ECONNRESET, meaning the server dropped the connection without an answer. The process was killed by the signal itself, so no finally block, log flush or database close in your code ever ran.

What does server.close() do?

The Node.js 22 documentation for http.Server says server.close() “stops the server from accepting new connections and closes all connections connected to this server which are not sending a request or waiting for a response.” It runs its callback once the server has fully closed.

== close
[close] listening, pid 1084
sending SIGTERM at 0.21s
+0.00s SIGTERM, in flight: 2
new request after SIGTERM: error ECONNREFUSED at 0.51s
request 1000 ms -> 200 done after 1000 ms at 1.02s
+2.81s closed, exiting
request 3000 ms -> 200 done after 3000 ms at 3.02s
server exited: 0 at 3.02s

Both requests finished with a 200. The new request, sent after SIGTERM, was refused (ECONNREFUSED): the server had stopped listening. That is what you want behind a load balancer, which sends new traffic to another instance. On a single server it means a short window where new visitors get nothing, so restart quickly or start the new process first.

The graceful mode adds a deadline and calls server.closeIdleConnections(). On Node.js 19 and later, close() already closes idle connections; the documentation says calling it as well “won’t cause any harm” and helps older versions. With no keep-alive connections, graceful behaved the same as close, exiting at +2.81s.

Why did shutdown take 9 seconds with keep-alive?

Browsers and many HTTP clients reuse one connection for several requests, called keep-alive. We repeated the test with a keep-alive agent, after one warm-up request so an idle connection was already open:

== graceful, keep-alive
[graceful] listening, pid 1122
warm-up: 200 done after 0 ms at 0.02s
sending SIGTERM at 0.22s
+0.00s SIGTERM, in flight: 2
new request after SIGTERM: error ECONNREFUSED at 0.52s
request 1000 ms -> 200 done after 1000 ms at 1.02s
request 3000 ms -> 200 done after 3000 ms at 3.02s
+8.80s all requests finished, exiting
server exited: 0 at 9.02s

The last response went out at +2.8s, but the server waited until +8.8s to exit. Six seconds of nothing. The plain close mode did exactly the same (+8.80s).

Here is why. close() and closeIdleConnections() close connections that are idle at the moment you call them. The two connections serving slow requests were busy then. When their responses finished, they became idle keep-alive connections, and nobody closed them. They waited for the keep-alive timeout like any other idle connection.

The wait matched the documented timeout. server.keepAliveTimeout defaults to 5000 ms, and the documentation says the socket timeout is keepAliveTimeout + keepAliveTimeoutBuffer, where the buffer (added in Node.js 22.19.0) defaults to 1000 ms. That is 6 seconds. Setting keepAliveTimeout to 2000 ms moved the exit to 3 seconds after the last response:

== keep-alive, keepAliveTimeout 2000
...
request 3000 ms -> 200 done after 3000 ms at 3.02s
+5.80s all requests finished, exiting
server exited: 0 at 6.03s

Six seconds may not sound like much. But if your process manager kills the process after a grace period, a slow request plus this wait can cross it, and requests you meant to finish get cut off anyway.

How do you close keep-alive connections during shutdown?

Tell each client, in its last response, that the connection is closing. Once the SIGTERM handler sets shuttingDown, every response carries Connection: close, and Node.js closes the socket after sending it:

if (shuttingDown) res.setHeader('Connection', 'close');
res.end(`done after ${ms} ms\n`);
== keep-alive, Connection: close while shutting down
[graceful-close-header] listening, pid 1181
warm-up: 200 done after 0 ms at 0.02s
sending SIGTERM at 0.22s
+0.00s SIGTERM, in flight: 2
new request after SIGTERM: error ECONNREFUSED at 0.52s
request 1000 ms -> 200 done after 1000 ms at 1.02s
+2.80s all requests finished, exiting
request 3000 ms -> 200 done after 3000 ms at 3.02s
server exited: 0 at 3.03s

Shutdown ended at +2.80s, the moment the last request finished, with no keep-alive wait. In a framework, set the header in a middleware that runs before the route, or in a hook that runs before the response is sent.

What if a request never finishes?

A stuck request (a hung database query, a slow outside API) would keep close() waiting forever. The deadline handles it: after DEADLINE_MS, call server.closeAllConnections() and exit with code 1. We ran the graceful mode with a 5-second deadline and a 15-second request:

== graceful, deadline 5s, 15s request
[graceful] listening, pid 1199
sending SIGTERM at 0.21s
+0.00s SIGTERM, in flight: 2
new request after SIGTERM: error ECONNREFUSED at 0.51s
request 1000 ms -> 200 done after 1000 ms at 1.02s
+5.00s deadline hit, in flight: 1, forcing
request 15000 ms -> error ECONNRESET at 5.22s
server exited: 1 at 5.22s

The 1-second request finished normally. The 15-second request was cut off at the deadline, and the exit code of 1 leaves a trace in the logs that this shutdown was not clean. Note the .unref() on the timer: without it, the timer itself would keep the process alive until it fired, even after a clean close.

Pick a deadline longer than your slowest normal request and shorter than the time your platform waits before killing the process outright.

A checklist

  • Handle SIGTERM (and SIGINT for Ctrl+C in development). Without a handler, in-flight requests are dropped.
  • In the handler, call server.close() first, then server.closeIdleConnections() if you support Node.js before 19.
  • Set a shuttingDown flag and send Connection: close on every response after it.
  • Start a deadline timer with .unref(). When it fires, call server.closeAllConnections() and exit with a non-zero code.
  • Close database connections and flush logs in the close() callback, before process.exit(0).
  • Test it: send a slow request, send SIGTERM, and check that the response arrives.

Limitations

  • We tested plain HTTP/1.1 with node:http on Node.js 22.23.5. We did not test HTTPS, HTTP/2 or WebSocket connections; the documentation notes that closeAllConnections() does not destroy sockets upgraded to another protocol, such as WebSocket.
  • We did not test a framework (Express, Fastify, Hono). They sit on node:http, but some add their own shutdown hooks, which may behave differently.
  • We did not test how a particular process manager, container platform or npm start passes signals on. If a wrapper does not forward SIGTERM to Node.js, none of this code runs. Check with your own setup.
  • The keepAliveTimeoutBuffer default applies to Node.js 22.19.0 and later. Older versions will show a different wait.
  • Timings are from one machine with a local client. Over a real network, add the round trip.

Sources

Frequently asked questions

What happens to in-flight requests when a Node.js server gets SIGTERM?

If you have not added a SIGTERM handler, the process ends immediately and every open connection is dropped. In our test, two requests that were 200 ms into a 1-second and a 3-second response both failed with ECONNRESET. Adding a handler that calls server.close() let both finish with a 200.

Does server.close() wait for active requests in Node.js?

Yes. It stops accepting new connections, closes idle ones, and calls its callback once the remaining connections have ended. In our test the callback ran 2.81 seconds after SIGTERM, right after the 3-second request finished. It does not end connections that are still busy, so you need your own deadline.

Why does my Node.js server take several seconds to exit after server.close()?

Usually a keep-alive connection. A connection that was busy when close() was called becomes idle when its response ends, and then waits for the keep-alive timeout before it closes. On Node.js 22.23.5 that was keepAliveTimeout (5 seconds by default) plus keepAliveTimeoutBuffer (1 second): the process exited about 6 seconds after the last response.

How do I make keep-alive connections close during shutdown?

Set a shuttingDown flag in the SIGTERM handler, and when it is set, add a Connection: close header to each response. The connection then closes right after its last response. In our test this cut shutdown from 8.80 seconds after SIGTERM to 2.80 seconds, the moment the last request finished.

How long should a graceful shutdown wait?

Shorter than whatever stops your process by force, and longer than your slowest normal request. After the deadline, call server.closeAllConnections() and exit with a non-zero code so the logs show the shutdown was not clean. In our test a 5-second deadline cut off a 15-second request at 5.00 seconds.

More from Research

← All research