Explain it simply
Graceful shutdown in plain language
Every time a new version is deployed, the platform sends the old process a signal meaning 'stop now', usually SIGTERM. Graceful shutdown means that on receiving it, the process does not die on the spot: it finishes the work in hand, closes its connections properly, and only then exits.
It is like closing a shop: hang the 'closed' sign, let the customers already inside finish paying, then switch off the lights and lock up. And if one customer lingers for half an hour, the door still has to close at some point.
Problem → Why → Solution
The problem: 502 errors on every deploy
A team deploys about ten times a day, and every deploy gives some users 502 Bad Gateway and leaves half-finished payment requests behind. The code calls process.exit(0) the moment SIGTERM arrives. Another service has no signal handler at all, so its container hangs until the timeout and is killed with SIGKILL.
const server = app.listen(3000);
process.on('SIGTERM', () => {
// In-flight responses are cut off, buffered logs may be lost,
// and the database never hears that the connections are gone.
process.exit(0);
});Why exiting immediately is wrong
When the signal arrives, some requests may still be waiting on the database, and the load balancer may still be sending new requests to this process. process.exit() cuts all of that off and can lose log lines still sitting in a pipe. Having no handler is a problem too: a process running as PID 1 in a container ignores SIGTERM without a handler, so the platform waits and then sends SIGKILL.
Core concept: shutdown is an ordered state machine
Handle two signals: SIGTERM is sent by Docker, Kubernetes and process managers, and SIGINT arrives when you press Ctrl+C in a terminal. After SIGTERM, Kubernetes waits terminationGracePeriodSeconds (30 seconds by default) and docker stop waits 10 seconds by default, then they send SIGKILL. SIGKILL cannot be caught, so the whole shutdown must finish inside that deadline.
Do the steps in order. (1) Set a shuttingDown flag so the readiness endpoint returns 503, and wait a few seconds for the load balancer to stop sending traffic here. (2) Call server.close(): it closes the listening socket so no new connections arrive, and calls back once in-flight requests finish. Since Node 19, close() also closes idle keep-alive connections, and adding Connection: close to responses that finish during the drain lets their sockets close quickly. (3) Close dependencies such as the database pool, queue consumers and log buffers only after requests finish, because those requests may still use them. (4) Set the exit code and let Node exit on its own.
Make the shutdown function idempotent: if SIGINT arrives after SIGTERM, cleanup must not start a second time. Add a force-exit timer too, so one stuck connection cannot hold the whole deploy hostage. Calling unref() on that timer means it never keeps the process alive when cleanup finishes in time.
Testing shutdown does not require a real signal. process.emit('SIGTERM', 'SIGTERM') calls the registered listeners exactly as if the signal had arrived. On Windows you can listen for SIGTERM, but kill never triggers that listener and simply stops the process, so emitting gives the same result on every OS. In tests you can also call the handler directly and await the promise it returns.
- Signal: readiness 503 + deadline
- Wait for the load balancer
- server.close(): drain in-flight
- Close DB and queue clients
- Set exitCode and leave
If the deadline passes, skip the remaining steps and exit with code 1; leaving yourself beats being SIGKILLed.
General pattern
let shuttingDown = false;
async function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true; // readiness now reports 503
setTimeout(() => process.exit(1), DEADLINE_MS).unref();
await waitForLoadBalancer();
await new Promise((resolve) => server.close(resolve));
await closeDependencies();
process.exitCode = 0;
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);The guard makes it run once, the unref'd timer enforces the deadline, and awaiting each step keeps the order explicit.
Worked example: draining an in-flight request
This demo starts a server on port 0 and begins a report request that takes 400 ms. As soon as the request starts, it simulates the signal with process.emit('SIGTERM', 'SIGTERM'); on Windows, kill never triggers a SIGTERM handler, so this keeps the demo identical on every OS. During the grace period /ready answers 503, the report still completes, and after the server closes a new request gets ECONNREFUSED. The client-side results are printed after shutdown, so the output order never changes.
import { createServer } from 'node:http';
import { setTimeout as sleep } from 'node:timers/promises';
const READINESS_GRACE_MS = 250; // several seconds in production; short for the demo
const database = {
async close() {
await sleep(20);
console.log('database pool closed');
},
};
let shuttingDown = false;
let reportStarted;
let shutdownFinished;
const started = new Promise((resolve) => (reportStarted = resolve));
const finished = new Promise((resolve) => (shutdownFinished = resolve));
function send(res, status, body) {
if (shuttingDown) res.setHeader('Connection', 'close'); // no keep-alive while draining
res.statusCode = status;
res.end(body);
}
const server = createServer(async (req, res) => {
if (req.url === '/ready') {
return send(res, shuttingDown ? 503 : 200, shuttingDown ? 'draining' : 'ready');
}
console.log('slow report started');
reportStarted();
await sleep(400); // work that is already in flight when the signal arrives
send(res, 200, 'report done');
});
function closeServer() {
return new Promise((resolve, reject) => {
// close() stops new connections and calls back once in-flight requests end
server.close((err) => (err ? reject(err) : resolve()));
});
}
async function shutdown(signal) {
if (shuttingDown) return; // a second signal must not start a second cleanup
shuttingDown = true;
console.log(`${signal} received: readiness is now 503`);
const forceExit = setTimeout(() => {
console.error('drain deadline passed, forcing exit');
server.closeAllConnections();
process.exit(1);
}, 10_000);
forceExit.unref(); // this timer alone must not keep the process alive
await sleep(READINESS_GRACE_MS); // give the load balancer time to stop routing here
await closeServer();
console.log('http server closed: in-flight requests finished');
await database.close();
clearTimeout(forceExit);
process.exitCode = 0; // let Node exit on its own instead of calling process.exit()
shutdownFinished();
}
process.on('SIGTERM', shutdown); // container stop, kill <pid>
process.on('SIGINT', shutdown); // Ctrl+C in a terminal
// ---- simulate a deployment stopping this process ----
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const report = fetch(`${base}/report`).then((res) => res.text());
await started;
// Simulate the signal so the demo behaves the same on every OS:
process.emit('SIGTERM', 'SIGTERM');
const ready = await fetch(`${base}/ready`);
const readyText = `${ready.status} ${await ready.text()}`;
const reportText = await report;
await finished;
const late = await fetch(`${base}/ready`).catch((error) => error.cause?.code);
console.log(`client: /ready during grace -> ${readyText}`);
console.log(`client: in-flight report -> ${reportText}`);
console.log(`client: new request after close -> ${late}`);Code breakdown
- Idempotent guard
if (shuttingDown) return; // a second signal must not start a second cleanupPressing Ctrl+C after SIGTERM does not call server.close() and database.close() a second time.
- Deadline that does not hold the process
forceExit.unref(); // this timer alone must not keep the process aliveIf cleanup takes more than 10 seconds, closeAllConnections() cuts the sockets and the process exits with code 1. Because of unref, the timer does not hold the process for 10 seconds when cleanup finishes early.
- Stop keep-alive while draining
if (shuttingDown) res.setHeader('Connection', 'close'); // no keep-alive while drainingA response that finishes during the drain does not leave a keep-alive socket open, so server.close()'s callback does not wait for the client's idle timeout.
- Drain, then dependencies
await closeServer();This await continues only after the report request finishes, so the database is never closed while a request still needs it.
- Exit without process.exit()
process.exitCode = 0; // let Node exit on its own instead of calling process.exit()Once the server and database are closed the event loop is empty, so Node exits by itself and gets the chance to flush any log output still pending.
slow report started
SIGTERM received: readiness is now 503
http server closed: in-flight requests finished
database pool closed
client: /ready during grace -> 503 draining
client: in-flight report -> report done
client: new request after close -> ECONNREFUSEDDoes the signal actually reach node in a container?
Perfect shutdown code is useless if the signal never reaches the node process. With the shell form in a Dockerfile (CMD node server.js), PID 1 in the container is /bin/sh, which typically does not forward signals to node. Wrappers such as npm start also put another process between the signal and node. Run node directly with the exec form, and use an init process such as docker run --init or tini for the PID 1 issues.
FROM node:22-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
USER node
# Exec form: node itself receives SIGTERM (no shell in between).
CMD ["node", "src/server.js"]| Platform | How it stops a process |
|---|---|
| docker stop | SIGTERM, waits 10 s by default, then SIGKILL |
| Kubernetes | SIGTERM, terminationGracePeriodSeconds (default 30 s), then SIGKILL |
| Terminal | Ctrl+C sends SIGINT |
In real projects
During a real production deploy
In a Kubernetes rolling update, old pods get SIGTERM once new pods are ready. Removing a pod from the Service endpoints and sending SIGTERM happen at the same time, so without a readiness grace period (or a preStop sleep) new requests can still arrive after the signal.
- Grace period plus drain plus dependency closing must add up to less than terminationGracePeriodSeconds, for example a 5 s grace, a 15 s drain deadline and a 30 s platform limit.
- Queue consumers stop taking new messages and acknowledge the current one before closing, or messages get processed twice.
- Long-lived connections such as WebSockets or server-sent events can hold a drain open forever, so send clients a reconnect message and close them.
Common mistakes
Common shutdown mistakes
Calling process.exit() straight from the handler
In-flight responses are cut off and clients see 502s, transactions are left half done, and log lines still in a pipe can vanish. Drain the server, close dependencies and set process.exitCode; keep process.exit() for the deadline fallback only.
Having no deadline
One hung database query or a WebSocket that never closes can hold server.close()'s callback forever. The whole deploy waits until the platform's SIGKILL, and not a single cleanup log line survives. Add an unref'd force-exit timer.
Closing dependencies before the server
Closing the database pool first and then draining the server makes in-flight requests fail with 'pool is closed' errors. The order is always: stop traffic, let requests finish, then close what they used.
Mini challenge
Mini challenge: idempotent shutdown with a deadline
Write createShutdown(steps, { deadlineMs }). However many times the returned shutdown(reason) function is called, the cleanup steps run once and every caller gets the same promise. Close the steps in order, and resolve with exit code 1 if the deadline passes. Simulate SIGTERM and SIGINT back to back with process.emit, and also try a step that hangs forever.
- A second call returns the first promise instead of creating a new one
- Await the steps in order with for...of
- Add the deadline with Promise.race and clear its timer when done
- Resolve with 0 on success and 1 when the deadline is hit
import { setTimeout as sleep } from 'node:timers/promises';
function createShutdown(steps, { deadlineMs }) {
let pending = null;
async function runSteps(reason) {
// TODO: log who started it, then await each [name, close] step in order
}
return function shutdown(reason) {
// TODO: if pending exists, return it
// TODO: race runSteps(reason) against a timer that resolves to 1
// TODO: clear the timer, log the outcome, return the exit code
};
}
// TODO: scenario 1 - three quick steps; emit SIGTERM then SIGINT,
// check that two calls return the very same promise
// TODO: scenario 2 - one step that never resolves, deadlineMs: 200Expected: Scenario 1 prints 'shutdown started by SIGTERM' only once, closes the three steps in order and returns exit code 0. Scenario 2 closes the http server and then reports deadline of 200 ms hit (1).
Show hint
Assign pending to the whole promise chain (race plus then). Build the deadline promise yourself with setTimeout and keep a cancel function, so the timer does not hold the process once the steps finish quickly.
Show solution
import { setTimeout as sleep } from 'node:timers/promises';
function createShutdown(steps, { deadlineMs }) {
let pending = null;
async function runSteps(reason) {
console.log(`shutdown started by ${reason}`);
for (const [name, close] of steps) {
await close();
console.log(` closed ${name}`);
}
return 0;
}
function deadline() {
let timer;
const promise = new Promise((resolve) => {
timer = setTimeout(() => resolve(1), deadlineMs);
});
return { promise, cancel: () => clearTimeout(timer) };
}
return function shutdown(reason) {
if (pending) return pending; // later callers share the first run
const limit = deadline();
pending = Promise.race([runSteps(reason), limit.promise]).then((code) => {
limit.cancel();
console.log(code === 0 ? 'clean exit (0)' : `deadline of ${deadlineMs} ms hit (1)`);
return code;
});
return pending;
};
}
// Scenario 1: SIGTERM, then an impatient SIGINT while cleanup is still running.
const healthy = createShutdown([
['http server', () => sleep(30)],
['job queue', () => sleep(20)],
['database pool', () => sleep(10)],
], { deadlineMs: 1_000 });
process.once('SIGTERM', healthy);
process.once('SIGINT', healthy);
process.emit('SIGTERM', 'SIGTERM');
process.emit('SIGINT', 'SIGINT');
console.log('one shared promise:', healthy('again') === healthy('and again'));
console.log('exit code:', await healthy('final check'));
// Scenario 2: a dependency that never finishes closing.
const stuck = createShutdown([
['http server', () => sleep(10)],
['message broker', () => new Promise(() => {})], // hangs forever
], { deadlineMs: 200 });
const code = await stuck('SIGTERM');
console.log('a real process would now call process.exit(' + code + ')');Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Platforms send SIGTERM and SIGKILL after a deadline (10 s for docker stop, 30 s by default on Kubernetes).
- Order: readiness 503 → wait for the load balancer → drain with server.close() → close dependencies → set exitCode.
- Make shutdown idempotent with a guard and add an unref'd force-exit timer.
- process.emit('SIGTERM', 'SIGTERM') lets you test shutdown deterministically on any OS.
- In containers, run node directly with an exec-form CMD so the signal actually arrives.
Process — Node.js