Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

03 guides

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-shutdown

The 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

  1. SIGTERM or SIGINT calls shutdown.shutdown(reason).
  2. isShuttingDownState becomes true. The middleware returns 503 for every new request, including /health/live and /health/ready. Readiness therefore fails and the load balancer stops routing to the instance.
  3. The tracker waits for active requests to finish, up to drainTimeoutMs.
  4. Tasks run from highest priority to lowest. The HTTP server task closes the listener.
  5. afterShutdown fires with completed, failed, and durationMs.

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:

PriorityValueUse for
HTTP_SERVER100Stop accepting new requests
QUEUE_CONSUMER80Stop consuming messages
JOB_QUEUE60Stop background workers
DB_POOL40Close database pools
CACHE20Close Redis or other caches
LOGGERS10Flush 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: 2

Keep 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: 40

With 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-app

or in Compose:

services:
  api:
    stop_grace_period: 35s

Common mistakes

  • Importing createHealth from 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 drainTimeoutMs or task timeouts higher than hardTimeoutMs. The process exits before tasks finish.
  • Running tests with signal handlers enabled. Pass installSignalHandlers: false.

On this page