Skip to content

Graceful shutdown in Node.js: SIGTERM, keep-alive connections and the readiness gap

Why server.close() alone fails requests on every deploy: getting the signal, the readiness gap, draining keep-alive connections and a deadline.

· 7 min read

  • Node.js
  • Reliability
  • Deployment

Every deploy replaces running processes. If the old process stops badly, a handful of requests fail each time: connection refused, connection reset, a 502 from the load balancer. The failures are rare enough to ignore for months, until one is a payment that was taken but never confirmed.

A graceful shutdown has four parts: receive the signal, keep serving until new traffic stops arriving, drain the connections you already have, and give up on a deadline. Most guides stop at server.close(). This article shows, with measurements, why that is not enough. It covers Node’s http module, so HTTP/1.1, and everything was run on Linux with Node 22.23 and 26.13, which behaved identically.

First, make sure the signal arrives

docker stop sends SIGTERM to the container’s main process and, ten seconds later by default, SIGKILL. Kubernetes does the same with a default grace period of 30 seconds. There are two common ways to lose the signal.

PID 1. Linux discards a signal sent to PID 1 if its action is the default, so the first process cannot be killed by accident. Node’s built-in SIGTERM handler only restores the terminal and re-raises the signal with the default action, which PID 1 discards. We ran Node as PID 1 in a fresh PID namespace: without a listener it survived SIGTERM; with a process.on("SIGTERM") listener it exited. Note that a listener also removes Node’s default exit (code 143, which is 128 plus the signal number), so ending the process becomes your handler’s job. docker run --init, or tini in the Dockerfile, is still worth having, because it also reaps zombie processes.

The shell form. CMD npm start or CMD node server.js runs under /bin/sh -c, so the shell is PID 1 and Node is its child. The shell has no handler, so it ignores the signal and Node never hears about it; outside a container the shell dies instead and leaves Node orphaned. With npm start Node never saw the signal either, with npm 10 and 11 and dash as /bin/sh. With bash as npm’s script shell the signal did arrive, because bash replaces itself with a lone command rather than forking it, but that is the shell’s doing, not npm’s. Use the exec form and skip npm: CMD ["node", "server.js"].

What server.close() actually does

The net documentation is precise: server.close() stops the server accepting new connections and keeps existing ones, and the callback runs only once every connection has ended. The http module adds one step, part of close() since Node 19: it destroys connections that are idle at that moment, meaning keep-alive connections with no request in flight.

A connection that is busy when you call close() is kept, and when its response finishes the server just resets the keep-alive timeout. We tested this with two keep-alive connections, one idle and one mid-way through a slow request. On close() the idle one was destroyed at once and a new connection attempt was refused. The busy one finished with Connection: keep-alive, then accepted and served a further request after close() had been called. The close callback did not fire until the client hung up.

Under real load this means server.close() can wait for ever. We ran a client with four keep-alive connections sending requests back to back and called close(). Three seconds later all four were still open and a few hundred requests had been served after the call. A load balancer with warm connections to your pod does exactly this, and your process sits there until the grace period ends in SIGKILL.

So close() has two problems: it refuses new connections too early, and it never finishes with busy ones.

The readiness gap

In every run above, connection attempts made after close() failed with ECONNREFUSED. That matters because the signal and the removal from the load balancer happen concurrently. The Kubernetes documentation says that at the same time as the kubelet starts the graceful shutdown of a pod, the control plane evaluates whether to remove it from EndpointSlice objects. Removal then has to reach kube-proxy and ingress controllers, and until it has, new connections keep arriving.

The fix is to do nothing for a while. On SIGTERM, flip a flag, keep serving as normal, and only then stop. In Kubernetes the deletion itself marks the pod’s endpoint not ready, whatever your probe says, so the number to measure is how long that takes to propagate in your cluster. We start at five seconds. For a balancer that health-checks instances directly, make your readiness route return 503 while the flag is set, and measure how long the balancer takes to notice.

Kubernetes can also do the waiting for you with a preStop hook, which completes before SIGTERM is sent. The sleep action was added for this, alpha in 1.29 and stable since 1.34:

lifecycle:
  preStop:
    sleep:
      seconds: 5

The grace period countdown includes the hook, so size terminationGracePeriodSeconds to cover the sleep plus the drain.

Draining busy connections

The obvious patch is to call server.closeIdleConnections() on an interval until the callback fires. It is racy and ineffective: a connection whose next request is already on the wire is destroyed and the client sees ECONNRESET, while one that is busy at every sweep is never closed. With a 50 ms sweep, three connections were still open after three seconds and one request was reset.

The clean mechanism is HTTP’s own: tell the client on its next response that this connection is finished.

server.prependListener("request", (req, res) => {
  if (closing) res.setHeader("Connection", "close");
});

Here closing is set just before server.close(). When a response carries Connection: close, Node marks it as the last message on that socket and destroys the socket once it has been written. Each busy connection serves exactly one more response, the client reads the header and opens a new connection elsewhere, and the close callback fires naturally. The same four-connection load drained in under 50 ms with no resets, on both Node versions.

Use prependListener, not on. http.createServer(handler) registers the handler as a request listener, so a listener added afterwards runs after it. Our first version did that, and a route that ended the response synchronously crashed the process with ERR_HTTP_HEADERS_SENT mid-shutdown. A handler that passes its own Connection header to writeHead overrides it too.

A deadline, and the sockets close() cannot see

The drain must be bounded. Node normally times out a half-sent request after requestTimeout, 300 seconds by default, but close() stops the checker that enforces it. We sent a request with an incomplete body and called close(): the connection was still open three seconds later, where without close() it got a 408 on time. A WebSocket never finishes at all. Put a timer on the drain and call server.closeAllConnections() when it expires. That destroys every HTTP connection, mid-request or not, which is what you want by then.

It does not touch sockets upgraded to another protocol, yet net.Server still counts them, so the close callback will not fire while a WebSocket is open. We checked: after close() and closeAllConnections(), the server still reported one connection and the client’s upgraded socket was open. Track upgraded sockets yourself and destroy them at the deadline, or have your WebSocket library close them with a proper close frame.

Putting it together

// shutdown.js
export function gracefulShutdown(server, { readinessDelayMs, drainTimeoutMs, cleanup = async () => {} }) {
  let draining = false;
  let closing = false;
  const upgraded = new Set();

  server.on("upgrade", (req, socket) => {
    upgraded.add(socket);
    socket.on("close", () => upgraded.delete(socket));
  });

  server.prependListener("request", (req, res) => {
    if (closing) res.setHeader("Connection", "close");
  });

  async function shutdown(signal) {
    if (draining) { console.error(`${signal} again, exiting now`); process.exit(1); }
    draining = true;

    // 1. Keep serving while the load balancer stops sending to us
    await new Promise((r) => setTimeout(r, readinessDelayMs));

    // 2. Stop accepting, close idle connections, let busy ones finish
    closing = true;
    const deadline = setTimeout(() => {
      server.closeAllConnections();
      for (const s of upgraded) s.destroy();
    }, drainTimeoutMs).unref();
    await new Promise((resolve) => server.close(resolve));
    clearTimeout(deadline);

    // 3. Release everything else, then let the event loop empty
    try { await cleanup(); } catch (err) { console.error("cleanup failed", err); process.exitCode = 1; }
  }

  process.on("SIGTERM", () => shutdown("SIGTERM"));
  process.on("SIGINT", () => shutdown("SIGINT"));
  return { get draining() { return draining; } };
}

The readiness route reads state.draining and returns 503 while it is set:

const state = gracefulShutdown(server, {
  readinessDelayMs: 5_000,
  drainTimeoutMs: 20_000,
  cleanup: () => pool.end(),
});

Three details are deliberate. The deadline timer is unref()’d so it cannot keep the process alive on its own. The function never calls process.exit(0), because the Node documentation warns that process.exit() cuts off pending asynchronous work, including writes to stdout; set process.exitCode if you need one and let the loop empty. So everything else holding the loop open must be released in cleanup: database pools, queue consumers, intervals. If the process does not exit, something was not. A second signal is the escape hatch for a person watching a stuck shutdown.

Background workers fit the same shape. The worker loop in our Postgres job queue takes an AbortSignal; abort it in cleanup and await the loop, so a job finishes or goes back to the queue rather than being cut off.

The test

We ran the module against a client that behaves like a load balancer: four pooled keep-alive connections sending requests back to back, new connections for other requests, and a readiness probe every 100 ms that stops opening connections once it sees a 503. Then we sent SIGTERM, with a one-second readiness delay.

The probe saw the 503 within 100 ms. The pooled connections were served as normal through the delay, about 160 requests. On close(), each received one response with Connection: close and the client’s pool emptied. The process exited with status 0 about 1.1 seconds after the signal, and the client recorded no errors of any kind. Without the header, against a client that keeps its connections busy, the same run lasted until the five-second deadline and ended with connection resets.

Run that test in CI against your own server. A shutdown path that only runs in production is a path nobody has seen work.

If you want help making a service survive its own deploys, see our backend development service.

Have something you'd like built?

Tell us what you're building. We'll reply within two working days with questions, an approach and next steps.

Start a project
Esc

↑ ↓ to move · Enter to open