Node.js · Backend · DevOps · WebSocket
Graceful Shutdown in Node.js: SIGTERM, Keep-Alive Connections and WebSockets
How to shut down a Node.js service without dropping requests: handling SIGTERM, readiness probes, keep-alive sockets, draining WebSocket clients and a hard timeout.

Every deploy is a shutdown. On the real-time services behind live device sessions, a careless restart did not show up as a log line but as a tester whose screen froze in the middle of a session. Most of the fixes were not clever: catch the signal, stop taking new work, finish what is in flight, tell long-lived clients to reconnect, and give up after a deadline. This post walks through that sequence for an HTTP plus WebSocket service.
What actually happens when a container stops
Docker and Kubernetes send SIGTERM to PID 1, wait for a grace period (Kubernetes defaults to 30 seconds), then send SIGKILL. Node has no default handler that drains anything: without your own handler, the process just exits and every open request is cut off.
Two preconditions trip people up:
- The signal must reach Node.
CMD ["node", "dist/server.js"]works;npm startor a shell-formCMDmay swallow it. The multi-stage Dockerfile guide covers this. - The load balancer must stop sending traffic first. In Kubernetes, removing a pod from the Service endpoints and sending
SIGTERMhappen in parallel. For a few seconds, new requests can still arrive after the signal.
The shutdown sequence
| Step | Why |
|---|---|
| 1. Flip readiness to failing | Load balancer stops routing new traffic |
| 2. Wait a few seconds | Endpoint removal propagates |
3. server.close() | Stop accepting new connections |
| 4. Close idle keep-alive sockets | They would otherwise hold the server open |
| 5. Ask WebSocket clients to leave | Long-lived connections never finish on their own |
| 6. Drain queues, close DB and Redis | Flush in-flight work |
7. Hard timeout, then process.exit | Never outlive the grace period |
A complete handler
import http from 'node:http';
import { setTimeout as sleep } from 'node:timers/promises';
import { WebSocketServer } from 'ws';
let shuttingDown = false;
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
app.get('/healthz/ready', (_req, res) => {
res.status(shuttingDown ? 503 : 200).end();
});
async function shutdown(signal: string) {
if (shuttingDown) return;
shuttingDown = true;
console.info({ signal }, 'shutdown started');
// Safety net: exit before the orchestrator sends SIGKILL.
setTimeout(() => {
console.error('shutdown timed out, forcing exit');
process.exit(1);
}, 25_000).unref();
await sleep(5_000); // let readiness failures propagate
const closed = new Promise<void>((resolve) => server.close(() => resolve()));
server.closeIdleConnections();
for (const ws of wss.clients) {
ws.close(1001, 'server restarting');
}
await closed;
await Promise.allSettled([db.end(), redis.quit()]);
console.info('shutdown complete');
process.exit(0);
}
process.once('SIGTERM', () => shutdown('SIGTERM'));
process.once('SIGINT', () => shutdown('SIGINT'));
Note the order: readiness first, wait, then close. If you call server.close() immediately, requests that the load balancer still routes to this pod get connection refused.
Keep-alive connections
server.close() stops listening, but its callback only fires after every existing connection ends. Browsers and HTTP clients keep idle sockets open for reuse, so a server with keep-alive enabled can wait far longer than you expect.
server.closeIdleConnections()(Node 18.2+) closes sockets that have no request in progress. Since Node 19,server.close()does this for you, but calling it explicitly documents the intent.- For requests that arrive on a reused socket during shutdown, send
Connection: closeso the client opens a fresh connection, which will go to a healthy instance:
app.use((_req, res, next) => {
if (shuttingDown) res.setHeader('Connection', 'close');
next();
});
server.closeAllConnections()exists too, but it cuts active requests. Keep it for the hard-timeout path only.
WebSockets need an explicit goodbye
A WebSocket never "finishes", so server.close() will wait on it forever. Close each client with code 1001 (Going Away) and make the client treat it as "reconnect soon", not as an error.
On the client, reconnect with backoff and jitter. If every client reconnects at the same millisecond, the remaining instances take a thundering herd:
function reconnectDelay(attempt: number) {
const base = Math.min(30_000, 500 * 2 ** attempt);
return base / 2 + Math.random() * (base / 2);
}
If a session has state that cannot be rebuilt from scratch, send a resume token before closing and let the client present it on reconnect. The WebSocket architecture post goes into heartbeats and message brokers, which matter here because the reconnecting client may land on a different instance.
Background work and queues
HTTP requests are only part of the picture. Before closing database connections:
- Stop pulling new jobs from the queue (
worker.pause()or the equivalent in your library). - Let the current job finish, or make jobs idempotent so a retry after a kill is harmless.
- Clear
setIntervaltimers that would otherwise keep scheduling work.
Idempotency is the real safety net. A graceful shutdown reduces the number of interrupted jobs; it never guarantees zero, because machines also die without warning.
Kubernetes settings that go with it
spec:
terminationGracePeriodSeconds: 40
containers:
- name: api
readinessProbe:
httpGet: { path: /healthz/ready, port: 3000 }
periodSeconds: 2
failureThreshold: 1
Keep the in-process hard timeout (25 s above) below terminationGracePeriodSeconds, so your own logs say what was still open rather than the process vanishing on SIGKILL. Some teams use a preStop hook with a short sleep instead of the in-process wait; either works, as long as one of them exists.
Testing it
Run the service locally, start a slow request and a WebSocket client, then send kill -TERM <pid>. Check that the slow request completes, the WebSocket receives 1001, and the process exits with code 0 before the timeout. A load generator running during a rolling deploy in staging is the best end-to-end test: the error count should stay at zero.
Conclusion
Graceful shutdown is a short checklist: fail readiness, wait, stop listening, close idle sockets, send WebSocket clients away with 1001, drain background work, and exit before the orchestrator kills you. Pair it with idempotent jobs and jittered client reconnects, and deploys stop being visible to users. For handling the errors that do slip through, see error handling in a TypeScript Node.js API.


