How to Shut Down a Node.js API Without Dropping Requests
The AI briefing for Developers
Stay up to date with AI tools, model releases, and developer workflows that matter.
Weekly. Free. One click to leave.

- Premium Results
- Publish articles on SitePoint
- Daily curated jobs
- Learning Paths
- Discounts to dev tools
7 Day Free Trial. Cancel Anytime.
Every deploy, autoscaling event and node drain ends the same way for a running Node.js process: the platform sends it SIGTERM and waits. What happens next decides whether your users notice the deploy.
If the process has no handler for that signal, it exits on the spot. Any request that was halfway through, say a report that takes three seconds of database work, never gets a response. Here is what that looks like with a plain Express app and no signal handling:
$ kill -TERM <pid>
in-flight request: no response (curl: empty reply from server)
process exit code: 143
Exit code 143 is 128 plus 15, the number of SIGTERM: the process was killed by the signal rather than exiting on its own. The client gets an empty reply, and if that request was writing data, nobody knows whether the write finished.
A graceful shutdown fixes this by draining the process: it stops taking new work, finishes what it already started, closes its connections and then exits. This tutorial builds that sequence for an Express 5 API backed by PostgreSQL, tests it against a real database, and covers the container and Kubernetes details that decide whether the signal ever reaches your code.
The shutdown sequence
The order of operations matters more than any single line of code. A process that receives SIGTERM should go through four steps:
- Fail readiness, keep serving. Flip the readiness endpoint to
503so load balancers stop routing new traffic here, but keep answering requests for a few seconds. Load balancers poll on an interval, so some traffic will still arrive after the signal. - Stop accepting connections and wait for in-flight requests. Close the HTTP server. It refuses new connections and waits for the requests it is already handling to finish.
- Release everything else. Close database pools, message consumers and anything else holding a socket or a timer open.
- Exit, with a deadline. If any step hangs, exit with a non-zero code before the platform loses patience and sends
SIGKILL, which can't be caught or handled.
The first step is the one most implementations skip. If the server closes immediately, requests that the load balancer routes in the next second or two get connection errors, which is exactly what graceful shutdown was supposed to prevent.
Building it
Create an ES module project and install Express 5 and node-postgres:
npm init -y
npm pkg set type=module
npm install express@5 pg
Step 1: Configuration and resources
// server.js
import express from "express";
import pg from "pg";
import { setTimeout as sleep } from "node:timers/promises";
const PORT = Number(process.env.PORT ?? 3000);
const DRAIN_DELAY_MS = Number(process.env.DRAIN_DELAY_MS ?? 5000);
const SHUTDOWN_TIMEOUT_MS = Number(process.env.SHUTDOWN_TIMEOUT_MS ?? 20000);
const pool = new pg.Pool();
pool.on("error", (err) => console.warn(`idle database client error: ${err.message}`));
const app = express();
let shuttingDown = false;
Two timings drive the whole sequence. DRAIN_DELAY_MS is how long the process keeps serving after it fails readiness. It should be longer than your load balancer's health-check interval multiplied by its failure threshold. SHUTDOWN_TIMEOUT_MS is the hard deadline for the whole shutdown, and it must be shorter than the time your platform waits before sending SIGKILL.
The sleep helper comes from Node's promise-based timers API, so the shutdown code can await a delay without wrapping setTimeout by hand.
Step 2: Routes that know about shutdown
// While draining, ask keep-alive clients to open their next request elsewhere.
app.use((req, res, next) => {
if (shuttingDown) res.set("Connection", "close");
next();
});
app.get("/healthz", (req, res) => {
res.json({ status: "ok" });
});
app.get("/readyz", (req, res) => {
if (shuttingDown) return res.status(503).json({ status: "shutting_down" });
res.json({ status: "ok" });
});
// A deliberately slow endpoint: three seconds of database work.
app.get("/report", async (req, res) => {
const { rows } = await pool.query("SELECT pg_sleep(3), now() AS generated_at");
res.json({ generatedAt: rows[0].generated_at });
});
const server = app.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT} (pid ${process.pid})`);
});
The middleware handles a detail that is easy to miss. HTTP clients reuse connections with keep-alive, so a client that already has a socket open to this instance would keep sending requests down it. A Connection: close header on the response tells the client to close that socket and open a new one, which the load balancer will route to a healthy instance.
Liveness stays green during shutdown. The process isn't broken; it's leaving on purpose, and a failing liveness probe could get it restarted in the middle of draining.
Step 3: The shutdown function
async function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
console.log(`${signal} received, draining`);
// Last resort: if cleanup hangs, exit before the platform sends SIGKILL.
const forceExit = setTimeout(() => {
console.error("shutdown timed out, forcing exit");
process.exit(1);
}, SHUTDOWN_TIMEOUT_MS);
forceExit.unref();
try {
// 1. Fail readiness and keep serving while load balancers notice.
await sleep(DRAIN_DELAY_MS);
// 2. Stop accepting connections and wait for in-flight requests.
await new Promise((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()));
});
console.log("http server closed");
// 3. Release everything else the process holds open.
await pool.end();
console.log("database pool closed");
} catch (err) {
console.error(`shutdown failed: ${err.message}`);
process.exitCode = 1;
}
}
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));
A few choices here are deliberate:
- Readiness fails the moment the signal arrives. Setting
shuttingDownfirst means the very next readiness probe returns503, even though the server keeps answering everything else. server.close()** does the waiting.** It stops accepting new connections and calls back once every in-flight request has finished. Since Node.js 19 it also closes idle keep-alive connections, so a client that is connected but not sending anything doesn't hold the shutdown open.- The force-exit timer is
unref()'d. An unreferenced timer doesn't keep the event loop alive on its own, so it fires only if something else is still holding the process open when the deadline arrives. - There is no
process.exit(0)at the end. Once the server and the pool are closed, the event loop runs out of work and Node.js exits by itself with code 0. If something you forgot, such as asetIntervalor a message consumer, is still holding the process open, the deadline triggers instead and exits with code 1. That turns a silent resource leak into a visible failure. pool.end()** runs after the server closes**, so the requests being drained can still use the database.SIGINT** gets the same handler** asSIGTERM, so pressing Ctrl+C in development exercises the same code path as a production deploy. Node's signal events documentation lists which signals a handler can catch.
Testing the shutdown
Shutdown code rarely gets tested, because it only runs on deploys. You can test it locally with curl and kill. Start the server with a short drain delay, start the slow request, and send SIGTERM while it is running:
DRAIN_DELAY_MS=2000 node server.js &
PID=$!
curl -s localhost:3000/report & # takes 3 seconds
sleep 0.5
kill -TERM $PID
curl -s -w " [%{http_code}]\n" localhost:3000/readyz
curl -s -i localhost:3000/healthz | grep -i connection
sleep 2.2
curl -s -o /dev/null -w "%{http_code}\n" localhost:3000/healthz
wait $PID; echo "exit code: $?"
Here is the timeline from a run against PostgreSQL 16 on Node.js 22:
0.50s SIGTERM sent
0.81s /readyz -> {"status":"shutting_down"} [503]
0.82s /healthz -> 200 OK, Connection: close
3.03s new request after the drain delay -> connection refused
3.11s in-flight /report finished -> 200 {"generatedAt":"..."}
3.11s process exit code: 0
Everything the sequence promised shows up in order. Readiness failed within a third of a second, the instance kept answering during the drain delay, new connections were refused once the server closed, and the request that was already running finished with a 200 before the process exited cleanly. Compare that with the empty reply and exit code 143 at the start of this article.
Two more cases are worth running once:
- An idle keep-alive connection. Open a connection with a keep-alive agent, make one request, and leave the socket idle. With a 500 ms drain delay, the process still exited 0.5 seconds after
SIGTERM, becauseserver.close()closed the idle socket instead of waiting for it. - A shutdown that takes too long. With
DRAIN_DELAY_MS=0andSHUTDOWN_TIMEOUT_MS=1500, the three-second request can't finish in time. The process logsshutdown timed out, forcing exitand exits with code 1. That in-flight request is lost, which is why the deadline should be comfortably longer than your slowest normal request.
Making sure the signal reaches Node.js
All of this only works if SIGTERM actually arrives at the Node.js process. In containers, that is not a given.
Use the exec form in your Dockerfile
FROM node:22-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
USER node
# Exec form: node itself receives the signal.
CMD ["node", "server.js"]
The Dockerfile reference explains the difference between the shell and exec forms. With the shell form, CMD node server.js, Docker starts /bin/sh -c as the main process, and the shell does not pass SIGTERM on to Node.js. Your handler never runs, docker stop waits out its grace period (10 seconds by default), and then the container is killed. For the same reason, start node directly rather than through an npm script or a shell wrapper, so there is no extra process between the platform and your code.
Consider an init process
The first process in a container runs as PID 1, which the Linux kernel treats specially: signals whose default action is to terminate are ignored unless the process installs a handler. The code above installs handlers, so Node.js shuts down correctly as PID 1. But any code path that relies on default signal behavior won't, and PID 1 also has to reap orphaned child processes. Running the container with docker run --init puts a tiny init process in front of Node.js that forwards signals and reaps zombies, and it costs nothing to add.
Line up the timings with Kubernetes
When Kubernetes deletes a pod, it removes the pod from Service endpoints and sends SIGTERM at roughly the same time, not one after the other. That race is the reason for the drain delay: for a few seconds after the signal, traffic can still arrive. After the grace period, 30 seconds by default, the kubelet sends SIGKILL. The pod termination documentation describes the full sequence, including preStop hooks, which run before SIGTERM and count toward the same grace period.
The timings need to nest inside each other:
spec:
terminationGracePeriodSeconds: 30
containers:
- name: api
image: my-api:1.4.2
env:
- name: DRAIN_DELAY_MS
value: "5000"
- name: SHUTDOWN_TIMEOUT_MS
value: "20000"
readinessProbe:
httpGet:
path: /readyz
port: 3000
periodSeconds: 2
failureThreshold: 1
livenessProbe:
httpGet:
path: /healthz
port: 3000
periodSeconds: 10
With a 2-second readiness period and a failure threshold of 1, a 5-second drain delay leaves a comfortable margin for the pod to leave rotation. The 20-second shutdown deadline sits well inside the 30-second grace period, so the process exits on its own terms instead of being killed. If your slowest legitimate request takes longer than about 15 seconds, raise terminationGracePeriodSeconds along with the deadline rather than letting those requests be cut off.
A short checklist
- Handle both
SIGTERMandSIGINT, and make the handler safe to call twice. - Fail readiness first, then keep serving for longer than your load balancer needs to notice.
- Send
Connection: closewhile draining, so keep-alive clients move to another instance. - Close the HTTP server and wait for in-flight requests before closing the database pool.
- Let the process exit on its own, with an
unref()'d deadline that exits with code 1 if something hangs. - Keep the deadline inside the platform's grace period, and start
nodewith the exec form so the signal reaches it. - Test it: one slow request, one
kill -TERM, and check that the request finishes and the exit code is 0.
Graceful shutdown is about forty lines of code, and it runs on every single deploy. Getting it right means a release is something your users never notice, which is exactly how a release should feel.