Production health checks and graceful shutdown
Separate liveness from readiness, drain in-flight requests, and close resources during a deploy.
Health checks and shutdown solve different problems:
- A liveness probe answers "is this process alive?" It should not call the database.
- A readiness probe answers "should this instance receive traffic?" It checks dependencies and the shutdown state.
- Graceful shutdown stops new traffic, waits for in-flight requests, then closes resources in a fixed order.
This guide wires both blocks into Express, Fastify, and Hono. Install the blocks first:
pnpm dlx blockend-cli add health-check
pnpm dlx blockend-cli add graceful-shutdownThe examples use the @/blocks alias. Change it if your blockend.json uses a different alias.
The health check block has no root index.ts. Import createHealth from
@/blocks/health-check/core/create-health. Importing from @/blocks/health-check will fail.
Express
import { createServer } from "node:http";
import express, { type Request, type Response } from "express";
import { createHealth } from "@/blocks/health-check/core/create-health";
import { GracefulShutdown, PRIORITY } from "@/blocks/graceful-shutdown";
import {
createExpressShutdownTask,
createExpressTracker,
createShutdownMiddleware
} from "@/blocks/graceful-shutdown/adapters/express";
const app = express();
const server = createServer(app);
const health = createHealth({
checks: [
{
name: "postgres",
critical: true,
timeoutMs: 3_000,
async run() {
await db.query("SELECT 1");
}
},
{
name: "redis",
critical: false,
timeoutMs: 2_000,
async run() {
await redis.ping();
}
}
]
});
const tracker = createExpressTracker(server);
const shutdown = new GracefulShutdown({
connectionTracker: tracker,
hardTimeoutMs: 30_000,
drainTimeoutMs: 12_000
});
// Must be registered before routes so new requests get 503 during shutdown.
app.use(createShutdownMiddleware(shutdown));
app.get("/health/live", (_req: Request, res: Response) => {
res.status(200).json({ status: "alive" });
});
app.get("/health/ready", async (_req: Request, res: Response) => {
const report = await health.run();
const statusCode = report.status === "unhealthy" ? 503 : 200;
res.status(statusCode).json(report);
});
app.get("/api/slow", async (_req: Request, res: Response) => {
await sleep(4_000);
res.json({ ok: true });
});
// Closing the server is required. The tracker only waits for requests.
shutdown.addTask(createExpressShutdownTask(server));
shutdown.addTask({
name: "queue-consumer",
priority: PRIORITY.QUEUE_CONSUMER,
handler: async () => {
await queueConsumer.close();
}
});
shutdown.addTask({
name: "db-pool",
priority: PRIORITY.DB_POOL,
handler: async () => {
await db.end();
}
});
shutdown.addTask({
name: "redis",
priority: PRIORITY.CACHE,
handler: async () => {
await redis.quit();
}
});
shutdown.addTask({
name: "logger",
priority: PRIORITY.LOGGERS,
handler: async () => {
await logger.flush();
}
});
server.listen(3000, () => {
console.log("Listening on http://localhost:3000");
});createServer(app) gives you the server object before listen(). That lets the tracker attach early enough to count every request. If you use app.listen(), attach the tracker after the server starts, which leaves a small gap.
Fastify
import Fastify from "fastify";
import { createHealth } from "@/blocks/health-check/core/create-health";
import { GracefulShutdown, PRIORITY } from "@/blocks/graceful-shutdown";
import {
createFastifyShutdownTask,
createFastifyTracker,
registerFastifyShutdownHooks
} from "@/blocks/graceful-shutdown/adapters/fastify";
const app = Fastify();
const health = createHealth({
checks: [
{
name: "postgres",
critical: true,
async run() {
await db.query("SELECT 1");
}
}
]
});
const tracker = createFastifyTracker(app);
const shutdown = new GracefulShutdown({ connectionTracker: tracker });
registerFastifyShutdownHooks(app, shutdown);
app.get("/health/live", async () => ({ status: "alive" }));
app.get("/health/ready", async (_request, reply) => {
const report = await health.run();
return reply.code(report.status === "unhealthy" ? 503 : 200).send(report);
});
shutdown.addTask(createFastifyShutdownTask(app));
shutdown.addTask({
name: "db-pool",
priority: PRIORITY.DB_POOL,
handler: () => db.end()
});
await app.listen({ port: 3000, host: "0.0.0.0" });registerFastifyShutdownHooks adds an onRequest hook, so call it before listen(). createFastifyShutdownTask calls fastify.close(), which runs your onClose hooks and waits for active requests.
Hono on Node
import { createServer } from "node:http";
import { getRequestListener } from "@hono/node-server";
import { Hono } from "hono";
import { createHealth } from "@/blocks/health-check/core/create-health";
import { GracefulShutdown, PRIORITY } from "@/blocks/graceful-shutdown";
import {
createHonoShutdownMiddleware,
createHonoShutdownTask,
createHonoTracker
} from "@/blocks/graceful-shutdown/adapters/hono";
const app = new Hono();
const server = createServer(getRequestListener(app.fetch));
const tracker = createHonoTracker(server);
const health = createHealth({
checks: [
{
name: "postgres",
critical: true,
async run() {
await db.query("SELECT 1");
}
}
]
});
const shutdown = new GracefulShutdown({ connectionTracker: tracker });
app.use("*", createHonoShutdownMiddleware(shutdown));
app.get("/health/live", (c) => c.json({ status: "alive" }));
app.get("/health/ready", async (c) => {
const report = await health.run();
return c.json(report, report.status === "unhealthy" ? 503 : 200);
});
shutdown.addTask(createHonoShutdownTask(server));
shutdown.addTask({
name: "db-pool",
priority: PRIORITY.DB_POOL,
handler: () => db.end()
});
server.listen(3000, () => {
console.log("Listening on http://localhost:3000");
});What happens during shutdown
SIGTERMorSIGINTcallsshutdown.shutdown(reason).isShuttingDownStatebecomestrue. The middleware returns 503 for every new request, including/health/liveand/health/ready. Readiness therefore fails and the load balancer stops routing to the instance.- The tracker waits for active requests to finish, up to
drainTimeoutMs. - Tasks run from highest priority to lowest. The HTTP server task closes the listener.
afterShutdownfires withcompleted,failed, anddurationMs.
The default hard timeout is 30 seconds. If tasks are still running, the process exits with code 1. A second signal exits immediately.
GracefulShutdown installs signal handlers by default. For tests, pass installSignalHandlers: false and call shutdown.shutdown("test") yourself.
Order tasks by dependency
PRIORITY provides suggested values:
| Priority | Value | Use for |
|---|---|---|
HTTP_SERVER | 100 | Stop accepting new requests |
QUEUE_CONSUMER | 80 | Stop consuming messages |
JOB_QUEUE | 60 | Stop background workers |
DB_POOL | 40 | Close database pools |
CACHE | 20 | Close Redis or other caches |
LOGGERS | 10 | Flush logs last |
A higher number runs first. If you leave out priority, the default is 50, which sits between job queues and database pools.
Kubernetes
Use separate probes:
livenessProbe:
httpGet:
path: /health/live
port: 3000
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 3000
periodSeconds: 5
failureThreshold: 2Keep liveness simple. If /health/live checks Postgres, a database outage will restart every pod even though restarting cannot fix the database.
The shutdown middleware also returns 503 from /health/live once draining starts. If your platform needs liveness to stay 200 during termination, register the liveness route before the middleware in Express or Hono, or leave the middleware out. The Fastify adapter installs a global onRequest hook, so route order cannot exempt liveness. If Fastify liveness must stay 200, skip registerFastifyShutdownHooks and apply the same shutdown check as a route-level hook to the routes that should reject new traffic.
Set the termination grace period longer than your hard timeout:
terminationGracePeriodSeconds: 40With a 30 second hard timeout, Kubernetes still has 10 seconds to kill the process if it ignores SIGTERM. Add a preStop sleep only if your load balancer needs time to remove the pod from its endpoint list:
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 5"]Docker
Docker sends SIGTERM by default. Give the process more time than your shutdown budget:
docker run --stop-timeout 35 my-appor in Compose:
services:
api:
stop_grace_period: 35sCommon mistakes
- Importing
createHealthfrom the block root. There is no root index. - Registering the shutdown middleware after routes, so requests still reach handlers while draining.
- Forgetting the HTTP server task. The tracker waits for requests but never closes the listening socket.
- Making the liveness probe check dependencies. That turns a database outage into a restart loop.
- Setting
drainTimeoutMsor task timeouts higher thanhardTimeoutMs. The process exits before tasks finish. - Running tests with signal handlers enabled. Pass
installSignalHandlers: false.