Graceful shutdown and health checks
Overview
Your app is restarted far more often than you might think: every deploy, every scale-down, every platform maintenance. If the process simply dies, any request being handled at that moment fails — a user sees an error during checkout, or a half-finished write leaves data inconsistent.
A graceful shutdown lets in-flight work finish before the process exits. Health checks tell the platform when your instance is ready for traffic and when it’s in trouble. Together, they make deploys invisible to users.
How platforms stop a process
Docker, Kubernetes, systemd and hosting platforms all follow the same pattern:
- Send
SIGTERM— “please stop”. - Wait for a grace period (Docker: 10 s by default; Kubernetes: 30 s).
- If the process is still running, send
SIGKILL— which can’t be caught; the process dies immediately.
When you press Ctrl+C in a terminal, the process gets SIGINT. By default, Node exits immediately on both signals. To shut down gracefully, you handle them:
Implementing graceful shutdown
// src/server.js
import { createApp } from './app.js';
import { pool } from './db.js';
import { redis } from './redis.js';
import { logger } from './logger.js';
const state = { ready: true };
const app = createApp({ state });
const server = app.listen(process.env.PORT ?? 3000, () => logger.info('Listening'));
let shuttingDown = false;
async function shutdown(signal) {
if (shuttingDown) return; // ignore a second signal
shuttingDown = true;
logger.info({ signal }, 'Shutting down');
// 1. Tell the load balancer to stop sending new traffic.
state.ready = false;
// 2. Safety net: never hang forever.
setTimeout(() => {
logger.error('Shutdown timed out, forcing exit');
process.exit(1);
}, 10_000).unref();
try {
// 3. Stop accepting connections; wait for in-flight requests to finish.
await new Promise((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()));
server.closeIdleConnections(); // close keep-alive sockets that aren't busy
});
// 4. Close everything else that keeps the process alive.
await Promise.all([pool.end(), redis.quit()]);
logger.info('Shutdown complete');
process.exit(0);
} catch (err) {
logger.error({ err }, 'Error during shutdown');
process.exit(1);
}
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);Key details:
server.close()stops accepting new connections and calls back once all existing connections have ended. Browsers and proxies keep idle keep-alive connections open, which would delay that —server.closeIdleConnections()closes the idle ones, while busy ones finish their current request first.- The force-exit timer must be shorter than the platform’s grace period, so you exit on your own terms (with a log line) rather than being killed silently.
.unref()means the timer itself doesn’t keep the process alive. - Order matters: stop taking requests first, then close the database — closing the pool first would make in-flight requests fail.
- Background workers need the same treatment: BullMQ’s
await worker.close()waits for the current job to finish. WebSocket servers should close client connections with a “going away” code (1001) so clients reconnect to another instance.
In Docker, signals must reach Node
If your container starts with CMD npm start, the signal goes to npm, which may not forward it to Node — and your shutdown code never runs. Start Node directly:
CMD ["node", "src/server.js"]The exec form (a JSON array) also matters: the shell form (CMD node src/server.js) wraps Node in /bin/sh, which doesn’t forward signals either. You’ll see this again in Docker for Node.js apps.
Health checks
Platforms ask your app two different questions.
| Endpoint | Question | If it fails… | Should check |
|---|---|---|---|
Liveness /livez |
Is the process alive and not stuck? | the platform restarts the container | almost nothing — can the event loop respond? |
Readiness /readyz |
Should this instance receive traffic right now? | the load balancer stops routing to it (no restart) | not shutting down; critical dependencies reachable |
// src/routes/health.js
import { Router } from 'express';
export function makeHealthRouter({ state, pool, redis }) {
const router = Router();
router.get('/livez', (req, res) => res.json({ status: 'ok' }));
router.get('/readyz', async (req, res) => {
if (!state.ready) return res.status(503).json({ status: 'shutting down' });
try {
await Promise.all([
pool.query('SELECT 1'),
redis.ping(),
]);
res.json({ status: 'ready' });
} catch (err) {
req.log.warn({ err }, 'Readiness check failed');
res.status(503).json({ status: 'dependency unavailable' });
}
});
return router;
}Mount the health router before authentication and rate limiting, so the platform can always reach it, and exclude it from request logs if it’s called every few seconds.
The liveness trap
It’s tempting to check the database in liveness too. Don’t. If the database has a brief outage, every instance fails liveness, the platform restarts all of them at once — and they come back to the same unavailable database, now with a stampede of reconnections. Restarting your app can’t fix the database. Liveness should only fail when restarting this process would actually help: a deadlock, or an event loop so blocked it can’t answer.
Startup
Mark the app ready only when it’s truly ready: after migrations have been checked, connections are established and caches are warm. Until then, /readyz returns 503 and the platform won’t route traffic to the new instance — which is what makes rolling deploys safe: new instances start, become ready, then old ones receive SIGTERM and drain.
Test it. Start your app, run a slow request (
curl localhost:3000/slow), and sendkill -TERM <pid>while it’s running. The request should complete, and the logs should show a clean shutdown.
Shut down without dropping requests
Write src/server.js that starts the app, and on SIGTERM or SIGINT: marks the app as not ready (so /readyz returns 503), stops accepting connections with server.close(), closes idle keep-alive connections, then closes the database pool and exits with code 0. If shutdown takes longer than 10 seconds, log an error and exit with code 1. A second signal should not start shutdown twice.
import { createApp } from './app.js';
import { pool } from './db.js';
import { logger } from './logger.js';
const state = { ready: true };
const app = createApp({ state });
const server = app.listen(process.env.PORT ?? 3000);
// your code hereimport { createApp } from './app.js';
import { pool } from './db.js';
import { logger } from './logger.js';
const state = { ready: true };
const app = createApp({ state });
const server = app.listen(process.env.PORT ?? 3000, () => logger.info('Listening'));
let shuttingDown = false;
async function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
logger.info({ signal }, 'Shutting down');
state.ready = false;
const forceExit = setTimeout(() => {
logger.error('Shutdown timed out, forcing exit');
process.exit(1);
}, 10_000);
forceExit.unref();
try {
await new Promise((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()));
server.closeIdleConnections();
});
await pool.end();
logger.info('Shutdown complete');
process.exit(0);
} catch (err) {
logger.error({ err }, 'Error during shutdown');
process.exit(1);
}
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
// in app.js:
// app.get('/livez', (req, res) => res.json({ status: 'ok' }));
// app.get('/readyz', (req, res) => state.ready ? res.json({ status: 'ready' }) : res.status(503).json({ status: 'shutting down' }));Summary
- Platforms stop containers with SIGTERM, then SIGKILL after a grace period.
- On SIGTERM: fail readiness, stop accepting connections, finish in-flight requests, close resources, then exit.
- Always add a force-exit timeout so a stuck connection can't block shutdown forever.
- Liveness (
/livez) answers 'is the process alive?'; readiness (/readyz) answers 'should it get traffic?' - Keep liveness checks simple — don't fail liveness just because the database is down.