My default Node.js graceful shutdown was short. Listen for SIGTERM, call server.close(), wait for the callback, exit. It looks complete, and I'd have pasted it into a service without a second thought.
So I measured it. I built a small lab, pointed 200 requests per second at four different servers, sent SIGTERM mid-flight, and counted every request that didn't come back with a 200.
server.close() saved the requests already in flight, and in my tests that was all it reliably saved. Four other assumptions sit around that one fact (your test client, your load balancer, your keep-alive timeout and the way your container starts), and each one changed the result. Here are the five, with the numbers.
| Mistake | What I measured |
|---|---|
1. Treating server.close() as the whole shutdown |
0 in-flight requests lost, but new connections were refused |
| 2. Testing with a client that reuses connections | Plain node:http failed 7 requests with a pooled client and 200 with a fresh connection per request |
| 3. Pausing for less time than the load balancer lag | About 200 failures when the pause was 1000 ms too short |
| 4. Ignoring the keep-alive timeout | 6.2 seconds to exit with the default timeouts and about 1.5 with Connection: close, and Fastify still waiting at 8 seconds |
| 5. Assuming SIGTERM reaches Node | It didn't through sh -c or npm start, on a Linux host or in Docker |
Short answer. server.close() is necessary and not enough. Pause longer than your load balancer's lag, send Connection: close on requests that arrive while draining, start node directly (exec form, with a SIGTERM handler or --init), and test with both a pooled and a fresh-connection client.
How I tested it
One repeatable scenario. Start a server, send steady load, send SIGTERM a second in, count what failed.
-
Servers. A plain
node:httpserver, Express 5.3.0, Fastify 5.12.8, and Hono 4.13.18 with@hono/node-server2.1.8, on Node.js 22.23.4 and 24.22.3. - Load. 200 requests per second, open loop, so the client keeps sending whether or not earlier requests succeeded, like a real load balancer. The handler waits 150 ms, so about 30 requests are in flight at any moment.
- Load balancer lag. After SIGTERM the client keeps sending for 0, 1000 or 2500 ms, as if the instance were still in the balancer's list.
-
Force exit. A timer inside the test server calls
process.exit(1)if shutdown hasn't finished after 8 seconds. That's my cutoff for a stuck shutdown. An orchestrator would send SIGKILL from outside instead, and the exit status would be 137. - Repeats. Each case ran 2 or 3 times on one laptop, Ubuntu under WSL2, with loopback networking only. The tables show Node 22.23.4 means, and Node 24.22.3 matched within a few requests.
This isn't Kubernetes or a real network. The balancer is a model of one behavior, which is requests arriving for a while after SIGTERM.
Mistake 1. Treating server.close() as the whole shutdown
First the baseline. With no SIGTERM handler, or a handler that calls process.exit(0) straight away, about 30 requests died every time on every framework, nearly everything in flight. Every failure was an ECONNRESET. An instant exit only changes the exit code in your logs.
With the usual server.close() handler, in-flight requests lost dropped to 0 in every run, on every server, at every lag. That part of the advice holds.
The part it never counts is new requests. Once close() runs, the server stops accepting new connections, so anything that needs a fresh connection is refused. With 1000 ms of load balancer lag, about 200 new requests arrived after SIGTERM, and the per-case averages of failures ranged from 7 to 12 across both Node versions. At 2500 ms, 17 to 22 of about 500 failed.
Those are small numbers. Don't trust them yet, because of mistake 2.
Mistake 2. Testing with a client that reuses connections
I ran every scenario twice, once with a keep-alive client that reuses sockets and once with a client that opens a new connection per request. Same server, same shutdown code, 1000 ms of lag.
Mean new requests failed per run (about 200 sent after SIGTERM, plain server.close(), Node 22.23.4) |
node:http |
Express | Fastify | Hono |
|---|---|---|---|---|
| Client reuses connections | 7 | 7 | 7 | 7 |
| New connection per request | 200 | 200.7 | 200.3 | 200.7 |
The same code failed a few percent of requests in one test and essentially all of them in the other. For Fastify, plain server.close() here means the Node server underneath it, app.server.close(). Fastify's own close() behaves differently, and mistake 3 covers it.
server.close() closes idle connections, but a connection that's busy with a request is left alone, and under steady load sockets are rarely idle. A client that keeps reusing its sockets keeps getting answers from a server that's technically shutting down. A client with nothing to reuse knocks on a closed door every time.
My lab's pooled client is a deliberate choice, but plenty of test setups end up with one by accident. Since Node 19, http.globalAgent has keep-alive enabled by default with a 5-second timeout, so a client that calls http.get() or http.request() without its own agent reuses sockets. Other clients and load tools have their own defaults (fetch doesn't use that agent, for one), so check yours. A staging test with a pooled client can pass while real traffic that arrives on fresh connections gets refused.
Run your shutdown test with both.
import http from "node:http";
const pooled = new http.Agent({ keepAlive: true });
const fresh = new http.Agent({ keepAlive: false });
Then report both numbers, and weigh them by what your production traffic looks like.
Mistake 3. Pausing for less time than your load balancer lags
The usual fix is a pause. Mark the instance unready, keep serving while the balancer catches up, then close. I tested that with a 1500 ms pause, and whether it passes depends on one comparison.
Mean new requests failed per run (new connection per request, node:http) |
Lag 1000 ms (pause is longer) | Lag 2500 ms (pause is shorter) |
|---|---|---|
Plain server.close()
|
200 | 500 |
| Pause, then close | 0 | 199.7 |
Pause, send Connection: close, then close |
0 | 199.7 |
When the pause outlasted the lag, nothing failed. When it didn't, the failures were almost exactly the requests sent in the gap, since (2500 − 1500) ms at 200 requests per second is 200 requests. The other three servers landed within a request or two.
The third row adds a Connection: close header to every response while draining. With the pooled client at 2500 ms of lag, the plain pause showed only 0 to 14 failures per run, because open sockets kept working. With the header, the real figure appeared, about 200.
Fastify behaves differently. Its docs say that once close() is called, new requests get a 503 with a Connection: close header by default. With the pooled client and 1000 ms of lag, fastify.close() with no pause failed essentially all 200 new requests. The same 1500 ms pause before fastify.close() brought it to 0.
The pause has to come from a measurement, not from this post. Log the time between SIGTERM and the last request your instance receives during a staging rollout, then set the pause above it. Kubernetes starts evaluating the pod's removal from EndpointSlices at the same time the kubelet starts shutdown. Terminating endpoints aren't removed immediately and always report ready as false, so load balancers shouldn't use them for regular traffic. How fast a given proxy or cloud balancer notices is up to its own implementation. That propagation delay is the lag you're covering, and my simulated lag stands in for it.
Mistake 4. Never looking at the keep-alive timeout
The handler's work takes 150 ms, yet a plain server.close() took over six seconds to exit on Node, Express and Hono, with no failed requests and nothing in the logs to explain it.
A socket that was busy when close() ran doesn't close afterwards. Once its response is sent, it sits idle until keepAliveTimeout plus keepAliveTimeoutBuffer has passed, and the process can't exit while any socket is open. The Node docs list 5000 ms and 1000 ms as the defaults. I changed the timeout on a plain server and shut it down with no further traffic.
keepAliveTimeout |
Exit time after SIGTERM |
|---|---|
| 3000 ms | 4159 ms |
| 5000 ms (default) | 6160 ms |
| 8000 ms | 9158 ms |
In every row, that's the 150 ms request plus the timeout plus the 1000 ms buffer, give or take 10 ms.
At 1000 ms the formula predicts about 2150 ms. The process exited in about 150 ms, and the cause was my own client. With that setting the server advertises Keep-Alive: timeout=1. Node's HTTP agent subtracts agentKeepAliveTimeoutBuffer (1000 ms by default) from the server's hint, which leaves no time at all, so it drops the socket right after the response. The option is in the Node docs and was added in v22.20.0 and v24.7.0. To confirm it, I set the buffer to 0 on the agent and exit went back to about 2.1 seconds. A raw TCP socket that ignores the hint gave the same figure. The 3000 ms row above used the same client and matched the formula, so the effect only shows up when the server's hint is short enough for the buffer to use all of it. The takeaway is that your clients help decide how long your shutdown takes, and you can't see that from the server.
Fastify makes this worse by default. Its keepAliveTimeout default is 72 seconds, and the server logs in my runs confirmed 72000 ms. With the pooled client and no further traffic, both server.close() and fastify.close() were still waiting when my 8-second limit ended. I created Fastify with its default options, so forceCloseConnections was "idle", which the docs say closes only the persistent connections that aren't sending or waiting for a request. Setting it to true destroys the sockets of persistent connections instead, which would also reach connections that are mid-request, and I didn't test that. I didn't wait out the 72 seconds and I didn't run Kubernetes. Its default grace period is 30 seconds, after which it sends SIGKILL, so a default Fastify service with keep-alive clients can be killed mid-shutdown. With the new-connection-per-request client, the same server exited in about 150 ms.
The best fix I found was the Connection: close header again, not a smaller timeout. While draining, each new request gets a response telling the client not to reuse its socket. The 150 ms requests that were in flight at SIGTERM had long finished before server.close() ran after the 1500 ms pause, so their sockets were idle and got closed, and nothing was left behind. That exit took about 1.5 seconds (1506 to 1534 ms at 0 and 1000 ms of lag) on all four servers and both Node versions, which is the 1500 ms pause plus a few milliseconds. A request that outlives the pause is a different case, and the module section covers it.
There's a second option worth knowing. Since Node 19, server.close() closes the connections that are idle at the moment you call it. A socket that was still busy at that moment becomes idle afterwards and waits out the timeout. In a separate single-run experiment on Node 22, 24 and 26, I called server.close(), let the in-flight response finish, then called server.closeIdleConnections(). The exit dropped from about 6.1 seconds to about 0.3 seconds. The Node docs say to call it after server.close() when you use both, to avoid race conditions with new connections. That was an exploratory check and not part of the repeated matrix, so treat it as a lead and not a result. server.closeAllConnections() is a different tool. It also destroys active connections, so it cuts off in-flight requests, and it belongs at your deadline, not in your drain.
I'd be careful about lowering keepAliveTimeout globally. If it falls below the idle timeout of the load balancer in front of you, the balancer can send a request down a connection the server has just closed. I didn't test that, so treat it as a caution and not a result.
Mistake 5. Assuming SIGTERM reaches Node at all
Everything above assumes your handler runs. I started a tiny Node process through four launchers, sent SIGTERM to the process I'd launched, waited three seconds, and checked whether Node was still alive.
| How the app was started | Did SIGTERM reach Node? |
|---|---|
node app.js |
Yes. The handler ran, or the default action stopped the process. |
sh -c "node app.js" |
No. The shell died and Node kept running. |
sh -c "node app.js; echo done" |
No. Same result. |
npm start |
No. Same result. |
This was Linux with /bin/sh pointing to dash, npm 10.9.9 and Node 22.23.4. Other shells and npm versions can behave differently, so read it as a reason to test your own launch command. The wrapper got SIGTERM, exited, and left the app running with nobody to stop it. That's why Docker's documentation recommends the exec form of CMD and ENTRYPOINT.
The second trap is PID 1. In a container, the first process is PID 1 of its own PID namespace, and Linux treats it specially. The pid_namespaces manual page says a process in an ancestor namespace can send signals to the init process of a child namespace only if that process has set up a handler for the signal. SIGKILL and SIGSTOP are the exceptions. I reproduced that with unshare --pid.
| Node process as PID 1 | Two seconds after SIGTERM |
|---|---|
| With a SIGTERM handler | Stopped, handler ran |
| No SIGTERM handler | Still running |
In a container, a Node app without a handler running as PID 1 should sit there until SIGKILL arrives at the end of the grace period. I checked that with docker stop -t 10 on Docker Desktop 29.9.2, using the node:22-slim image, which was Node 22.23.5 that day.
| Container command | Stop time | Exit code | Did the handler run? |
|---|---|---|---|
node app.js with a handler |
0.3 s | 0 | Yes |
node app.js, no handler |
10.3 s | 137 | Not applicable |
sh -c "node app.js" |
10.3 s | 137 | No |
npm start |
0.8 s | 1 | No |
node app.js with --init, no handler |
0.2 s | 143 | Not applicable |
The prediction held. The exec form without a handler ran out the full 10 seconds and got SIGKILL, and --init fixed it. sh -c did the same even with a handler in the app, because the shell was PID 1 and never passed the signal on.
npm start is the sneaky one. The container stopped in under a second, which looks like a clean shutdown, yet the container log never showed my handler's GOT SIGTERM line. npm exited and the container went down around the app. A fast docker stop doesn't prove your shutdown code ran, so look for a log line from it. I didn't run Kubernetes, so its grace period figures come from its docs.
What the five have in common
Every one of them was an assumption about something outside my handler. The code was the same in each test, and the result changed with the client, the balancer, the timeout or the launcher.
The Node.js graceful shutdown module I'd ship
This works with node:http, Express and Hono's Node server, because all of them expose a standard http.Server. It covers the HTTP server only. The onShutdown hook is where you close pools and queues, and I didn't test any of that. I did measure what abandoned queries do to a connection pool in Does AbortSignal Cancel a Node.js Database Query?. Queries that outlive their clients keep pool connections busy, which is worth knowing before you close the pool. I didn't test pool.end() itself.
The final process.exit() is deliberate. It ends the process even if something left a timer or handle open, and it cuts off any async work still running, so decide what you can afford to abandon. The Node docs say to prefer setting process.exitCode and letting the process exit on its own, because process.exit() can cut off pending writes to stdout and stderr. I kept process.exit() because that's the code my tests ran. If you swap in process.exitCode, keep the force-exit timer and rerun your own checks, since I didn't test that variant. A second SIGTERM or SIGINT while it's shutting down is ignored by design.
One more limit, which I found while checking the module. The Connection: close header goes only on requests that arrive after the signal, so a request that is still running when server.close() starts keeps its keep-alive socket. In a single run on Node 22, 24 and 26 (experiments/long-request.mjs in the repo), a 3 second request outlived a 500 ms pause, and the process exited 8.8 seconds after SIGTERM, which is the rest of the request plus the 6 second keep-alive wait. With a 5 second pause the request had finished first, and the exit came 5 seconds after SIGTERM. If you have slow requests, set delayMs above them and keep forceExitMs as the ceiling. A request whose client has already left keeps running too unless you cancel it, which I tested in Does AbortController Cancel Server Work?. I haven't tested closeIdleConnections() inside the module.
// graceful-shutdown.mjs
import { setTimeout as sleep } from "node:timers/promises";
export function gracefulShutdown(
server,
{
delayMs = 5000, // keep serving while the load balancer catches up. Must be longer than its lag.
forceExitMs = 25000, // hard stop. Keep it below your platform's grace period.
onShutdown = async () => {}, // close database pools, flush queues, and so on
} = {},
) {
let draining = false;
// Ask clients to drop their sockets on requests that arrive while draining.
server.prependListener("request", (req, res) => {
if (draining) res.setHeader("Connection", "close");
});
async function shutdown(signal) {
if (draining) return;
draining = true;
console.error(`${signal} received, draining`);
// Left referenced on purpose, so a cleanup that never finishes still ends with exit code 1.
const force = setTimeout(() => {
console.error("shutdown took too long, forcing exit");
process.exit(1);
}, forceExitMs);
let code = 0;
try {
await sleep(delayMs); // 1. keep serving while the balancer catches up (/health reports 503 via isDraining)
await new Promise((resolve) => server.close(resolve)); // 2. stop listening, finish in-flight requests
await onShutdown(); // 3. now it is safe to close the database pool
} catch (err) {
console.error("error during shutdown", err);
code = 1;
}
clearTimeout(force);
process.exit(code);
}
for (const signal of ["SIGTERM", "SIGINT"])
process.on(signal, () => shutdown(signal));
return { isDraining: () => draining };
}
With Express it looks like this.
import express from "express";
import { gracefulShutdown } from "./graceful-shutdown.mjs";
const app = express();
const server = app.listen(3000);
const shutdown = gracefulShutdown(server, {
delayMs: 5000,
onShutdown: () => pool.end(), // your database pool
});
// Report unready as soon as SIGTERM arrives.
app.get("/health", (req, res) =>
res.status(shutdown.isDraining() ? 503 : 200).send("ok"),
);
The order inside shutdown() matters most. Pause first, then close, and the database pool last, because closing it earlier pulls connections out from under requests that are still running.
I ran this module through the lab on all four servers, on both Node versions, with and without keep-alive clients, using a 1500 ms pause and the 8-second force-exit limit. In-flight requests lost were 0 every time. At 1000 ms of lag, new requests failed 0 times every time. At 2500 ms of lag, about 200 failed, which is the arithmetic from mistake 3 working in reverse. Exit took about 1.5 seconds at 0 and 1000 ms of lag and about 1.65 seconds at 2500 ms, with one slower run at 1.84 seconds.
For Fastify, the module also passed when wired to app.server, but that bypasses Fastify's own close(), so onClose hooks and plugin cleanup won't run. For a real Fastify app I'd use the same pause followed by await app.close(), which also failed 0 requests at 1000 ms of lag in my runs.
A short audit of your own Node.js graceful shutdown
- Look at how your container starts the app. If
CMDisnpm startor a shell string, switch to the exec form (CMD ["node", "server.js"]), send SIGTERM to the container and watch the handler run. - Check that your handler does more than call
process.exit(). In my runs that saved nothing. - Run your shutdown test with a pooled client and a fresh-connection client, and compare.
- Measure your balancer lag in staging and set the pause above it.
- Check which
keepAliveTimeoutyour framework uses (Fastify's is 72 seconds), and time your exit. - Make sure
terminationGracePeriodSecondscovers the pause, your longest request and your cleanup, and thatforceExitMsis below it. ApreStophook runs inside the same grace period, so budgetforceExitMsagainst what's left after the hook, not the full value. The default is 30 seconds, and the Kubernetes docs say to raise it if the hook runs long. - Close the database pool after the server, never before.
What this doesn't prove
These numbers describe one controlled setup.
- No real load balancer. There's no Kubernetes, ingress or cloud balancer here, only a model of requests arriving after SIGTERM. Real propagation delays vary.
- A timer is the handler. Every request waits 150 ms and returns. Handlers that hit a database, call other services or burn CPU will behave differently.
-
A short list of servers. I didn't test Next.js, HTTPS, HTTP/2, WebSockets or server-sent events. Fastify's docs note that upgraded connections such as WebSockets aren't tracked by the HTTP server and will prevent
server.close()from completing, which I didn't test either. -
Two Node versions in the matrix. I ran Node 22.23.4 and 24.22.3. Node 26 is an LTS release now. I ran only the two keep-alive experiments and the long-request check on it, not the framework matrix or the module matrix. The Node docs say
keepAliveTimeoutBufferwas added in v22.19.0 and v24.6.0, so older versions won't include that extra second in exit times. - Small samples. Each case ran two or three times on one machine under WSL2, and counts moved by a few requests between runs.
- Nothing on the database side. I didn't test what happens to database queries or pool cleanup during shutdown. That's a separate investigation.
- No Kubernetes runs. The Docker results come from Docker Desktop on one machine, and the 30-second figure comes from the Kubernetes docs.
Run it yourself
Every number here comes from a repository you can run. The quick checks take a few minutes and the full matrix takes about 15 minutes per Node version. The repository is nodejs-graceful-shutdown-tests on GitHub. The README separates what I tested from what I didn't, and docker/run-docker-test.sh reruns the docker stop checks on your own machine. If your numbers differ from mine, I'd like to see them, especially from a real cluster.
What I'd do differently
The handler I'd have pasted passed in the situation I'd have tested it in. Change the client, the pause, the timeout or the launch command, and the same lines of code gave a different answer. If you've tested your own shutdown, I'd like to know which client you used, and whether you've tried the other kind.
Sources
-
Node.js HTTP documentation for
server.close(),keepAliveTimeout,keepAliveTimeoutBuffer,http.globalAgentandagentKeepAliveTimeoutBuffer -
Fastify server reference for
keepAliveTimeout,forceCloseConnectionsandreturn503OnClosing -
Kubernetes, Termination of Pods for the grace period, SIGTERM and SIGKILL,
preStopand endpoint removal - Docker, JSONArgsRecommended build check for exec form and signal handling
- Linux manual page pid_namespaces(7) for signals sent to the init process of a PID namespace
Last verified against these pages on 2026-11-25, using Node.js 22.23.4 and 24.22.3. The Docker runs used the node:22-slim image, which was Node.js 22.23.5.
Top comments (3)
Oh, this was interesting to read, di 😀 I honestly wouldn't have thought about how many things could affect graceful shutdown beyond just calling
server.close(). Loved that you actually tested all these scenarios and shared what you found!Thank you so much, Hema! ❤️ I'm glad you enjoyed it. It was interesting to see how much the results changed with different client connection behaviour, keep-alive settings and the way Node was started. Testing these scenarios made me look at graceful shutdown quite differently.
I think the pooled versus fresh client result is the part that surprised me most.