Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

02 blocks

Graceful shutdown

Validated

Stop new traffic, drain in-flight requests, and close resources in priority order.

The graceful shutdown block coordinates process shutdown. It stops accepting new work, waits for active requests to finish, runs cleanup tasks from highest priority to lowest, and enforces a hard timeout.

The root index.ts exports the core and constants. Framework adapters live in adapters/.

Quick start

pnpm dlx blockend-cli init
pnpm dlx blockend-cli add graceful-shutdown
import { createServer } from "node:http";
import express from "express";
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 tracker = createExpressTracker(server);
const shutdown = new GracefulShutdown({
  connectionTracker: tracker,
  drainTimeoutMs: 10_000,
  hardTimeoutMs: 30_000
});

// Register this before routes so new requests get 503 during shutdown.
app.use(createShutdownMiddleware(shutdown));

app.get("/api/slow", async (_req, res) => {
  await sleep(2_000);
  res.json({ ok: true });
});

// The server task is required. The tracker does not close the listener.
shutdown.addTask(createExpressShutdownTask(server));

shutdown.addTask({
  name: "db-pool",
  priority: PRIORITY.DB_POOL,
  handler: () => db.end()
});

server.listen(3000);

On SIGTERM, the order is:

  1. isShuttingDownState becomes true. The middleware returns 503 for new requests.
  2. The tracker waits for in-flight requests, up to drainTimeoutMs.
  3. The server task closes the listener.
  4. The database task closes the pool.
  5. The process exits with code 0 if no task failed, otherwise code 1.

Files

graceful-shutdown/
├── adapters/
│   ├── express.ts
│   ├── fastify.ts
│   └── hono.ts
├── core/
│   ├── connection-tracker.ts
│   └── shutdown.ts
├── utils/
│   ├── http.ts
│   ├── index.ts
│   ├── state.ts
│   └── timeout.ts
├── constants.ts
├── index.ts
└── types.ts

Installation

pnpm dlx blockend-cli add graceful-shutdown

The CLI copies the core, constants, types, one adapter, and the tests.

Copy the base files and one adapter into blocks/graceful-shutdown. Keep the relative layout.

Core

import { EventEmitter } from "node:events";

import {
  DEFAULT_DRAIN_TIMEOUT_MS,
  DEFAULT_HARD_TIMEOUT_MS,
  DEFAULT_PRIORITY,
  DEFAULT_TASK_TIMEOUT_MS
} from "../constants";
import { withTimeout } from "../utils/index";
import type { ConnectionTracker } from "../types";
import type {
  GracefulShutdownOptions,
  ShutdownReason,
  ShutdownResult,
  ShutdownStateProvider,
  ShutdownTask,
  TaskFailure
} from "../types";

/**
 * Coordinates and executes the cleanup tasks that run on shutdown.
 *
 * Emits lifecycle events: `beforeShutdown`, `draining`, `drained`,
 * `drainTimeout`, and `afterShutdown`.
 *
 * Lifecycle:
 *   1. `beforeShutdown` — listeners stop starting new work.
 *   2. Drain active connections (if a tracker is configured) — in-flight
 *      requests keep their resources until they finish.
 *   3. Run registered tasks in priority order (highest first).
 *   4. `afterShutdown` — with the aggregate result.
 *
 * A hard timeout (unconfigurable to disable) forces `process.exit(1)` if the
 * whole run exceeds `hardTimeoutMs`.
 */
export class GracefulShutdown extends EventEmitter implements ShutdownStateProvider {
  // States
  private _isShuttingDown = false;
  private shutdownPromise: Promise<ShutdownResult> | null = null;

  // Configuration
  private readonly hardTimeoutMs: number;
  private readonly defaultTaskTimeoutMs: number;
  private readonly stopOnError: boolean;
  private readonly onTaskComplete?: GracefulShutdownOptions["onTaskComplete"];
  private readonly connectionTracker: ConnectionTracker | undefined;
  private readonly drainTimeoutMs: number;

  // Registry
  private tasks: Map<string, ShutdownTask> = new Map();

  constructor(options: GracefulShutdownOptions = {}) {
    super();
    this.hardTimeoutMs = options.hardTimeoutMs ?? DEFAULT_HARD_TIMEOUT_MS;
    this.defaultTaskTimeoutMs = options.defaultTaskTimeoutMs ?? DEFAULT_TASK_TIMEOUT_MS;
    this.stopOnError = options.stopOnError ?? false;
    this.onTaskComplete = options.onTaskComplete;
    this.connectionTracker = options.connectionTracker;
    this.drainTimeoutMs = options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;

    // Disable signal handling when the caller invokes shutdown() manually
    // (e.g. in tests, or when the app provides its own signal wiring).
    if (options.installSignalHandlers !== false) {
      this._installSignalHandlers();
    }
  }

  // ─── Public API ─────────────────────────────────────────────────────────────

  /** `true` while the application is shutting down. Used by readiness probes. */
  get isShuttingDownState(): boolean {
    return this._isShuttingDown;
  }

  /**
   * Register a shutdown task. Tasks with the same name replace existing ones.
   *
   * If shutdown has already started, the task runs immediately instead.
   */
  addTask(task: ShutdownTask): this {
    if (this._isShuttingDown) {
      console.warn(
        `[shutdown] Task "${task.name}" added after shutdown started — running immediately`
      );
      Promise.resolve(task.handler()).catch((err) =>
        console.error(`[shutdown] Immediate task "${task.name}" failed:`, err)
      );
      return this;
    }

    this.tasks.set(task.name, task);
    return this;
  }

  /**
   * Remove a previously registered task by name. Returns `true` if it existed.
   */
  removeTask(name: string): boolean {
    return this.tasks.delete(name);
  }

  /** Returns registered task names, ordered highest priority first. */
  getTaskNames(): string[] {
    return [...this.tasks.values()]
      .sort((a, b) => (b.priority ?? DEFAULT_PRIORITY) - (a.priority ?? DEFAULT_PRIORITY))
      .map((task) => task.name);
  }

  /**
   * Start (or resume) a graceful shutdown.
   *
   * Idempotent — every caller receives the exact same in-flight result promise,
   * identical by reference. Concurrent callers can race to trigger shutdown and
   * all await the same run.
   *
   * Deliberately NOT `async`: an `async` function wraps the value it returns in
   * a fresh adapter promise, which would break reference identity and make the
   * second call return a different object than the first.
   */
  shutdown(reason: ShutdownReason = "manual"): Promise<ShutdownResult> {
    // Each caller shares the same promise, so shutdown runs exactly once.
    if (this.shutdownPromise) return this.shutdownPromise;

    this._isShuttingDown = true;
    const startMs = Date.now();
    console.info(`[shutdown] Starting graceful shutdown. Reason: ${reason}`);

    // Reserve the shared promise NOW so any re-entrant call — e.g. from a
    // beforeShutdown listener emitted below — receives the same run instead of
    // recursively starting a second one.
    let finish!: (result: ShutdownResult) => void;
    let fail!: (err: unknown) => void;
    const reserved = new Promise<ShutdownResult>((res, rej) => {
      finish = res;
      fail = rej;
    });
    this.shutdownPromise = reserved;

    // Hard timeout — last resort. Cannot be disabled.
    const hardTimer = setTimeout(() => {
      console.error(`[shutdown] Hard timeout of ${this.hardTimeoutMs}ms exceeded. Forcing exit.`);
      process.exit(1);
    }, this.hardTimeoutMs);
    hardTimer.unref(); // Don't keep the event loop alive if we finish first.

    // Defer everything that can throw (listeners, draining, tasks) into an
    // async runner so any failure settles the shared `reserved` promise. This
    // keeps `shutdown()` a plain synchronous function that hands every caller
    // the exact same promise object — the property both idempotency and
    // re-entrancy rely on.
    void (async () => {
      try {
        // Allow listeners to do pre-shutdown work (e.g. stop cron jobs) BEFORE
        // we begin draining.
        this.emit("beforeShutdown", reason);
        // Kick off the drain + task sequence and settle the reserved promise
        // with its outcome, clearing the hard timer when it completes.
        finish(await this._performShutdown(startMs));
      } catch (err) {
        fail(err);
      } finally {
        clearTimeout(hardTimer);
      }
    })();

    return this.shutdownPromise;
  }

  // ─── Internals ──────────────────────────────────────────────────────────────

  /** Drain active connections, then run registered tasks. */
  private async _performShutdown(startMs: number): Promise<ShutdownResult> {
    // Drain step — skipped entirely if no tracker is configured.
    // Connections are drained FIRST so the resources (DB, cache) they may be
    // using are still alive until every in-flight request has finished.
    if (this.connectionTracker) {
      this.emit("draining");
      try {
        await this.connectionTracker.waitForDrain(this.drainTimeoutMs);
        this.emit("drained");
      } catch {
        // Drain timed out — log and continue; tasks still need to run.
        console.warn("[shutdown] Connection drain timed out — proceeding to tasks");
        this.emit("drainTimeout");
      }
    }

    // Stop the server and run the remaining registered tasks.
    return this._runTasks(startMs);
  }

  /** Run all registered tasks in priority order, collecting results. */
  private async _runTasks(startMs: number): Promise<ShutdownResult> {
    const completed: string[] = [];
    const failed: TaskFailure[] = [];

    const sorted = [...this.tasks.values()].sort(
      (a, b) => (b.priority ?? DEFAULT_PRIORITY) - (a.priority ?? DEFAULT_PRIORITY)
    );

    for (const task of sorted) {
      const taskStart = Date.now();
      const timeout = task.timeout ?? this.defaultTaskTimeoutMs;

      try {
        await withTimeout(Promise.resolve(task.handler()), timeout, task.name);
        const duration = Date.now() - taskStart;
        completed.push(task.name);
        this.onTaskComplete?.(task.name, duration);
        console.info(`[shutdown] Task "${task.name}" completed in ${duration}ms`);
      } catch (err) {
        const duration = Date.now() - taskStart;
        const error = err instanceof Error ? err : new Error(String(err));
        failed.push({ name: task.name, error });
        this.onTaskComplete?.(task.name, duration, error);
        console.error(`[shutdown] Task "${task.name}" failed after ${duration}ms:`, error.message);

        if (this.stopOnError) {
          console.error(`[shutdown] stopOnError=true — aborting remaining tasks`);
          break;
        }
      }
    }

    const result: ShutdownResult = {
      success: failed.length === 0,
      completed,
      failed,
      durationMs: Date.now() - startMs
    };

    // Emit after all tasks, whether successful or not.
    this.emit("afterShutdown", result);
    console.info(
      `[shutdown] Complete. ${completed.length} succeeded, ${failed.length} failed. Total: ${result.durationMs}ms`
    );

    return result;
  }

  /**
   * Install OS signal handlers. Called once at construction, unless
   * `installSignalHandlers: false`.
   *
   * `uncaughtException` / `unhandledRejection` are intentionally NOT handled
   * here — those are application-level concerns. Handle them in your app entry
   * point, then call `shutdown('uncaughtException')`.
   */
  private _installSignalHandlers(): void {
    const handle = (signal: ShutdownReason) => {
      // If shutdown is already underway, a further signal means "hurry up": the
      // first signal starts a graceful drain, any subsequent signal forces exit
      // so a stuck process can never outlive the caller's patience forever.
      if (this._isShuttingDown) {
        console.error(`[shutdown] Second signal (${signal}) — forcing immediate exit.`);
        process.exit(1);
        return;
      }

      console.info(`[shutdown] Signal received: ${signal}`);
      this.shutdown(signal)
        .then((result) => process.exit(result.success ? 0 : 1))
        .catch((err) => {
          console.error("[shutdown] Unexpected error during shutdown:", err);
          process.exit(1);
        });
    };

    // `on` (not `once`) so a repeated signal is still observed and can force exit.
    process.on("SIGTERM", () => handle("SIGTERM"));
    process.on("SIGINT", () => handle("SIGINT"));
    process.on("SIGQUIT", () => handle("SIGQUIT"));
  }
}

/**
 * Pre-built singleton for apps that need a single shutdown manager.
 *
 * Created on first use so importing the root module does not install signal
 * handlers as a side effect. Prefer creating a fresh `GracefulShutdown` per
 * process so tests and workers stay isolated.
 */
let singleton: GracefulShutdown | undefined;

export const gracefulShutdown: GracefulShutdown = new Proxy({} as GracefulShutdown, {
  get(_target, property, receiver) {
    singleton ??= new GracefulShutdown();
    const value = Reflect.get(singleton, property, receiver);
    return typeof value === "function" ? value.bind(singleton) : value;
  },
  set(_target, property, value, receiver) {
    singleton ??= new GracefulShutdown();
    return Reflect.set(singleton, property, value, receiver);
  }
});

Connection tracker

import type { Server } from "node:http";

import { DRAIN_POLL_INTERVAL_MS } from "../constants";
import type { AttachableConnectionTracker, ConnectionTracker } from "../types";

/**
 * A Node.js HTTP connection tracker that attaches to a `Server` and counts
 * in-flight requests.
 *
 * `waitForDrain` resolves as soon as `activeCount` reaches zero, or rejects
 * once `timeoutMs` elapses.
 */
export class NodeConnectionTracker implements AttachableConnectionTracker {
  private _activeCount = 0;

  get activeCount(): number {
    return this._activeCount;
  }

  /**
   * Attach the tracker to a Node `http.Server`. Must be called before the
   * server starts accepting requests so no request is missed.
   */
  attach(server: Server): this {
    server.on("request", (_req, res) => {
      this._activeCount++;

      // Both 'finish' and 'close' fire on a completed request, and 'close' also
      // fires when the client disconnects mid-request. Use a one-shot guard so
      // a single request is only ever decremented once.
      let released = false;
      const done = () => {
        if (released) return;
        released = true;
        this._activeCount = Math.max(0, this._activeCount - 1);
      };

      res.once("finish", done); // response sent successfully
      res.once("close", done); // client disconnected mid-request
    });

    return this;
  }

  waitForDrain(timeoutMs: number): Promise<void> {
    if (this._activeCount === 0) return Promise.resolve();

    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => {
        clearInterval(interval);
        reject(new Error(`Drain timed out: ${this._activeCount} requests still active`));
      }, timeoutMs);
      timer.unref();

      const interval = setInterval(() => {
        if (this._activeCount === 0) {
          clearInterval(interval);
          clearTimeout(timer);
          resolve();
        }
      }, DRAIN_POLL_INTERVAL_MS);
    });
  }
}

/**
 * Type guard — checks at runtime whether a tracker supports attachment,
 * without casting.
 */
export function isAttachable(tracker: ConnectionTracker): tracker is AttachableConnectionTracker {
  return typeof (tracker as AttachableConnectionTracker).attach === "function";
}

Constants

/**
 * Centralised defaults and suggested priority levels.
 *
 * Keeping them here lets callers tune behaviour and guarantees the core and its
 * utilities never drift out of sync.
 */

/** Priority used when a task does not specify one. */
export const DEFAULT_PRIORITY = 50;

/** Hard kill timeout — process exits regardless once this elapses. */
export const DEFAULT_HARD_TIMEOUT_MS = 30_000;

/** Default per-task timeout when `task.timeout` is not set. */
export const DEFAULT_TASK_TIMEOUT_MS = 10_000;

/** Default timeout for waiting on active connections to drain. */
export const DEFAULT_DRAIN_TIMEOUT_MS = 10_000;

/** HTTP servers need more time to drain active requests than most tasks. */
export const DEFAULT_HTTP_CLOSE_TIMEOUT_MS = 15_000;

/** How often `waitForDrain` polls whether requests have finished. */
export const DRAIN_POLL_INTERVAL_MS = 50;

/**
 * Suggested priority levels. Higher values run first.
 *
 * The ordering is deliberate: stop accepting new work before flushing the
 * resources that depend on it.
 */
export const PRIORITY = {
  /** HTTP servers — stop traffic first. */
  HTTP_SERVER: 100,
  /** Message queue consumers — stop consuming before flushing. */
  QUEUE_CONSUMER: 80,
  /** Job queues / workers. */
  JOB_QUEUE: 60,
  /** Database connection pools. */
  DB_POOL: 40,
  /** Caches (Redis etc.). */
  CACHE: 20,
  /** Loggers / telemetry — flush last so we keep logs from everything above. */
  LOGGERS: 10
} as const;

Types

/**
 * Shared types and contracts for the graceful-shutdown block.
 */

// ─── Tasks ────────────────────────────────────────────────────────────────────

/** A function that performs part of the cleanup. May be sync or async. */
export type ShutdownHandler = () => Promise<void> | void;

/**
 * The reason a shutdown was triggered. Free-form strings are allowed so callers
 * can use custom reasons, e.g. `'deploy'`.
 */
export type ShutdownReason =
  | "SIGTERM"
  | "SIGINT"
  | "SIGQUIT"
  | "uncaughtException"
  | "unhandledRejection"
  | "manual"
  | (string & {});

/** A single unit of cleanup work registered against the shutdown manager. */
export interface ShutdownTask {
  /** Human-readable name, used in logs and results. Should be unique. */
  name: string;
  /** The cleanup work to run. */
  handler: ShutdownHandler;
  /** Per-task timeout in ms. Overrides `defaultTaskTimeoutMs`. */
  timeout?: number;
  /**
   * Higher = runs first. See {@link PRIORITY} for suggested conventions,
   * e.g. `PRIORITY.HTTP_SERVER` (100).
   */
  priority?: number;
}

/** A task that failed during shutdown, together with the error it threw. */
export interface TaskFailure {
  name: string;
  error: Error;
}

/** The final, aggregate outcome of a shutdown run. */
export interface ShutdownResult {
  /** `true` when no task failed. */
  success: boolean;
  /** Names of tasks that completed successfully. */
  completed: string[];
  /** Tasks that threw an error or timed out. */
  failed: TaskFailure[];
  /** Total time taken to run the tasks, in ms. */
  durationMs: number;
}

// ─── Shutdown state ───────────────────────────────────────────────────────────

/** Any object that exposes the current shutdown status, for observability. */
export interface ShutdownStateProvider {
  /** `true` while the application is shutting down. Used by readiness probes. */
  readonly isShuttingDownState: boolean;
}

// ─── Options ──────────────────────────────────────────────────────────────────

/** Options accepted by `GracefulShutdown`. */
export interface GracefulShutdownOptions {
  /** Hard kill timeout. After this, `process.exit(1)` fires regardless. Default: 30s */
  hardTimeoutMs?: number;
  /** Default per-task timeout if `task.timeout` is not set. Default: 10s */
  defaultTaskTimeoutMs?: number;
  /** If `true`, stop running tasks on the first failure. Default: `false` */
  stopOnError?: boolean;
  /**
   * If `true`, register SIGTERM/SIGINT/SIGQUIT handlers automatically.
   * Set to `false` to call `shutdown()` manually (e.g. in tests). Default: `true`
   */
  installSignalHandlers?: boolean;
  /**
   * Called when a task completes or fails. Use for metrics/observability,
   * e.g. recording task duration to Prometheus.
   */
  onTaskComplete?: (name: string, durationMs: number, error?: Error) => void;
  /** Optional connection tracker the shutdown waits on before running tasks. */
  connectionTracker?: ConnectionTracker;
  /** How long to wait for active connections to drain. Default: 10s */
  drainTimeoutMs?: number;
}

// ─── HTTP 503 helper ──────────────────────────────────────────────────────────

/** Options for the `handleNode503` request-interception helper. */
export interface Node503Options {
  /** HTTP status code returned. Default: `503`. */
  statusCode?: number;
  /** Response body. Objects are JSON-serialised. Default: a JSON error body. */
  body?: Record<string, unknown> | string;
  /** Additional response headers to set. */
  headers?: Record<string, string | number | readonly string[]>;
}

// ─── Connection tracker ───────────────────────────────────────────────────────

/**
 * The contract an in-flight-request tracker must fulfill.
 *
 * The shutdown manager depends on this interface only — never on a concrete
 * implementation.
 */
export interface ConnectionTracker {
  /**
   * Current number of requests that have started but not yet finished.
   *
   * Readonly — only the tracker itself mutates it. External code reads it for
   * observability (metrics, logging, health checks).
   */
  readonly activeCount: number;

  /**
   * Resolves when `activeCount` reaches `0`, or rejects if that has not
   * happened within `timeoutMs`. Resolves immediately if already drained.
   *
   * @param timeoutMs How long to wait before giving up.
   */
  waitForDrain(timeoutMs: number): Promise<void>;
}

/**
 * Optional extension for trackers that attach to and detach from a server.
 *
 * Not required by the core, but useful for adapters that need explicit
 * lifecycle control (e.g. `NodeConnectionTracker`).
 */
export interface AttachableConnectionTracker extends ConnectionTracker {
  /**
   * Attach the tracker to a server instance. Must be called before the server
   * starts accepting requests. Returns `this` for fluent chaining.
   */
  attach(server: unknown): this;
  /** Detach from the server. Implement when secure reuse across tests is needed. */
  detach?(): void;
}

Express adapter

import type { NextFunction, Request, Response } from "express";
import type { Server } from "node:http";
import type { ShutdownStateProvider, ShutdownTask } from "../types";
import { NodeConnectionTracker } from "../core/connection-tracker";
import { createHttpShutdownTask } from "../utils/http";

// ─── Middleware ───────────────────────────────────────────────────────────────

/**
 * Express middleware that rejects incoming requests with 503
 * when the application is shutting down.
 *
 * Register this as the FIRST middleware — before routes, before auth,
 * before everything. A request that arrives during shutdown should
 * never reach your route handlers.
 *
 * Usage:
 *   app.use(createShutdownMiddleware(shutdown));
 */
export function createShutdownMiddleware(provider: ShutdownStateProvider) {
  return (req: Request, res: Response, next: NextFunction): void => {
    if (!provider.isShuttingDownState) {
      next();
      return;
    }

    res
      .set("Connection", "close")
      .set("Retry-After", "30")
      .set("Content-Type", "application/json")
      .status(503)
      .json({
        error: "service_unavailable",
        message: "Server is shutting down"
      });
  };
}

// ─── Tracker factory ──────────────────────────────────────────────────────────

/**
 * Creates and attaches a NodeConnectionTracker to an Express server.
 *
 * Call this after createServer() but before server.listen().
 * Pass the returned tracker to GracefulShutdown via the constructor
 * or setConnectionTracker().
 *
 * Usage:
 *   const server = createServer(app);
 *   const tracker = createExpressTracker(server);
 *   const shutdown = new GracefulShutdown({ connectionTracker: tracker });
 */
export function createExpressTracker(server: Server): NodeConnectionTracker {
  return new NodeConnectionTracker().attach(server);
}

// ─── Shutdown task factory ────────────────────────────────────────────────────

/**
 * Convenience re-export — Express uses the standard Node HTTP shutdown task.
 * No Express-specific logic needed here because server.close() works the same.
 *
 * IMPORTANT: registering this task is required. A ConnectionTracker only waits
 * for requests to drain; it never closes the server. Without this task the
 * listen handle stays alive and the process never exits.
 *
 * Usage:
 *   shutdown.addTask(createExpressShutdownTask(server));
 */
export function createExpressShutdownTask(
  server: Server,
  options?: { timeout?: number }
): ShutdownTask {
  // Express doesn't need anything beyond the base Node HTTP task.
  // This re-export exists so adapter users import from one place.
  return createHttpShutdownTask(server, options);
}

Fastify adapter

// Fastify is built directly on the Node http server, so the generic
// NodeConnectionTracker can attach to `fastify.server`. The 503 behaviour is
// wired through an onRequest hook (it must be registered before listen()).

import type { FastifyInstance } from "fastify";

import { DEFAULT_HTTP_CLOSE_TIMEOUT_MS, PRIORITY } from "../constants";
import type { ShutdownStateProvider, ShutdownTask } from "../types";
import { NodeConnectionTracker } from "../core/connection-tracker";

// ─── Tracker factory ──────────────────────────────────────────────────────────

/**
 * Creates and attaches a NodeConnectionTracker to a Fastify instance.
 *
 * Fastify wraps a Node http server (`fastify.server`), so the same request /
 * finish / close events drive the in-flight counter.
 *
 * Usage:
 *   const tracker = createFastifyTracker(fastify);
 *   const shutdown = new GracefulShutdown({ connectionTracker: tracker });
 */
export function createFastifyTracker(fastify: FastifyInstance): NodeConnectionTracker {
  return new NodeConnectionTracker().attach(fastify.server);
}

// ─── Shutdown hook (503) ──────────────────────────────────────────────────────

/**
 * Registers an `onRequest` hook that rejects new requests with 503 once the
 * application is shutting down.
 *
 * Must be called BEFORE `fastify.listen()`.
 *
 * Alternative (built into Fastify): call
 * `await fastify.listen({ port, return503OnClosing: true })` — that returns 503
 * only while `fastify.close()` is running. This hook covers the larger window
 * from when `shutdown()` starts until the server actually closes.
 *
 * Usage:
 *   registerFastifyShutdownHooks(fastify, shutdown);
 */
export function registerFastifyShutdownHooks(
  fastify: FastifyInstance,
  provider: ShutdownStateProvider
): void {
  fastify.addHook("onRequest", async (_request, reply) => {
    if (provider.isShuttingDownState) {
      return reply
        .code(503)
        .header("Connection", "close")
        .header("Retry-After", "30")
        .type("application/json")
        .send({ error: "service_unavailable", message: "Server is shutting down" });
    }
  });
}

// ─── Shutdown task factory ────────────────────────────────────────────────────

/**
 * Creates a shutdown task that gracefully closes a Fastify instance.
 *
 * `fastify.close()` stops accepting connections and waits for in-flight
 * requests and onClose hooks to finish. Idle keep-alive connections are closed
 * first so `close()` does not block on them.
 *
 * IMPORTANT: registering this task is required. A ConnectionTracker only waits
 * for requests to drain; it never closes the server.
 *
 * Usage:
 *   shutdown.addTask(createFastifyShutdownTask(fastify));
 */
export function createFastifyShutdownTask(
  fastify: FastifyInstance,
  options?: { timeout?: number }
): ShutdownTask {
  return {
    name: "fastify-server",
    priority: PRIORITY.HTTP_SERVER,
    timeout: options?.timeout ?? DEFAULT_HTTP_CLOSE_TIMEOUT_MS,
    handler: async () => {
      // Release idle keep-alive sockets so close() resolves promptly.
      if (typeof fastify.server.closeIdleConnections === "function") {
        fastify.server.closeIdleConnections();
      }

      try {
        await fastify.close();
      } catch (err) {
        // Already closed is not an error.
        if ((err as NodeJS.ErrnoException)?.code === "ERR_SERVER_NOT_RUNNING") {
          return;
        }
        throw err;
      }
    }
  };
}

Hono adapter

// Hono on Node (`@hono/node-server`) runs on a plain Node http server, so the
// generic NodeConnectionTracker attaches to that server and the Node HTTP
// shutdown task closes it. The 503 behaviour is a standard Hono middleware.

import type { Server } from "node:http";
import type { MiddlewareHandler } from "hono";

import type { ShutdownStateProvider, ShutdownTask } from "../types";
import { NodeConnectionTracker } from "../core/connection-tracker";
import { createHttpShutdownTask } from "../utils/http";

// ─── Middleware (503) ─────────────────────────────────────────────────────────

/**
 * Hono middleware that rejects incoming requests with 503 once the
 * application is shutting down.
 *
 * Register it before your routes:
 *   app.use('*', createHonoShutdownMiddleware(shutdown));
 */
export function createHonoShutdownMiddleware(provider: ShutdownStateProvider): MiddlewareHandler {
  return async (c, next) => {
    if (!provider.isShuttingDownState) {
      return next();
    }

    return c.json({ error: "service_unavailable", message: "Server is shutting down" }, 503, {
      Connection: "close",
      "Retry-After": "30"
    });
  };
}

// ─── Tracker factory ──────────────────────────────────────────────────────────

/**
 * Creates and attaches a NodeConnectionTracker to the Node http server that
 * `@hono/node-server` created for a Hono app.
 *
 * Usage:
 *   const server = createServer(getRequestListener(app.fetch));
 *   const tracker = createHonoTracker(server);
 *   const shutdown = new GracefulShutdown({ connectionTracker: tracker });
 */
export function createHonoTracker(server: Server): NodeConnectionTracker {
  return new NodeConnectionTracker().attach(server);
}

// ─── Shutdown task factory ────────────────────────────────────────────────────

/**
 * Creates a shutdown task that closes the Node http server backing a Hono app.
 *
 * IMPORTANT: registering this task is required. A ConnectionTracker only waits
 * for requests to drain; it never closes the server.
 *
 * Usage:
 *   shutdown.addTask(createHonoShutdownTask(server));
 */
export function createHonoShutdownTask(
  server: Server,
  options?: { timeout?: number }
): ShutdownTask {
  return createHttpShutdownTask(server, options);
}

Configuration

const shutdown = new GracefulShutdown({
  hardTimeoutMs: 30_000,
  defaultTaskTimeoutMs: 10_000,
  drainTimeoutMs: 10_000,
  stopOnError: false,
  installSignalHandlers: true,
  connectionTracker: tracker,
  onTaskComplete(name, durationMs, error) {
    metrics.observe("shutdown_task_seconds", durationMs / 1000, { name });
  }
});
OptionDefaultDescription
hardTimeoutMs30000Forced process.exit(1) after this long. Cannot be disabled.
defaultTaskTimeoutMs10000Timeout for tasks without their own timeout.
drainTimeoutMs10000How long to wait for active requests before running tasks.
stopOnErrorfalseStop running tasks after the first failure.
installSignalHandlerstrueListen for SIGTERM, SIGINT, and SIGQUIT.
connectionTrackerNoneWaits for active requests before tasks run.
onTaskCompleteNoneCalled with name, durationMs, and an optional error.

Signal handlers call shutdown(reason) and exit. If a second signal arrives during shutdown, the process exits immediately.

uncaughtException and unhandledRejection are not handled. Wire those in your entry point and call shutdown.shutdown("uncaughtException") yourself.

Tasks

A task has a name, a handler, an optional timeout, and an optional priority:

shutdown.addTask({
  name: "cache",
  priority: PRIORITY.CACHE,
  timeout: 5_000,
  handler: async () => {
    await redis.quit();
  }
});

Higher priority runs first. Tasks with the same name replace each other. addTask returns the manager, so calls can chain.

PriorityValueUse for
HTTP_SERVER100Stop accepting requests
QUEUE_CONSUMER80Stop consuming messages
JOB_QUEUE60Stop background workers
DB_POOL40Close database pools
CACHE20Close Redis and other caches
LOGGERS10Flush logs last

The default priority is 50. A task that times out counts as failed and the next task still runs unless stopOnError is true. A timed-out task is not canceled; its handler can keep running while the next task starts.

If you add a task after shutdown starts, it runs immediately and is not tracked in the result.

The server task is required

The connection tracker only counts requests. It does not close the listening socket. Add the framework's server task:

shutdown.addTask(createExpressShutdownTask(server));
shutdown.addTask(createFastifyShutdownTask(app));
shutdown.addTask(createHonoShutdownTask(server));

Without it, shutdown never closes the listening socket. With signal handlers enabled, the process exits after the remaining tasks finish. If you call shutdown() yourself, close the server after it resolves or call process.exit.

Usage

Express

import { createServer } from "node:http";
import express from "express";
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 tracker = createExpressTracker(server);
const shutdown = new GracefulShutdown({ connectionTracker: tracker });

app.use(createShutdownMiddleware(shutdown));

app.get("/health", (_req, res) => {
  res.json({ status: "ok" });
});

shutdown.addTask(createExpressShutdownTask(server));
shutdown.addTask({
  name: "db",
  priority: PRIORITY.DB_POOL,
  handler: () => db.end()
});

server.listen(3000);

Create the server with createServer(app) before listen() so the tracker can attach early. The middleware must be registered before routes.

Fastify

import Fastify from "fastify";
import { GracefulShutdown } from "@/blocks/graceful-shutdown";
import {
  createFastifyShutdownTask,
  createFastifyTracker,
  registerFastifyShutdownHooks
} from "@/blocks/graceful-shutdown/adapters/fastify";

const app = Fastify();
const tracker = createFastifyTracker(app);
const shutdown = new GracefulShutdown({ connectionTracker: tracker });

registerFastifyShutdownHooks(app, shutdown);
app.get("/health", async () => {
  return { status: "ok" };
});

shutdown.addTask(createFastifyShutdownTask(app));

await app.listen({ port: 3000 });

registerFastifyShutdownHooks adds an onRequest hook and must be called before listen(). The Fastify task calls fastify.close(), which runs onClose hooks.

Hono on Node

import { createServer } from "node:http";
import { getRequestListener } from "@hono/node-server";
import { Hono } from "hono";
import { GracefulShutdown } 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 shutdown = new GracefulShutdown({ connectionTracker: tracker });

app.use("*", createHonoShutdownMiddleware(shutdown));

app.get("/health", (c) => {
  return c.json({ status: "ok" });
});

shutdown.addTask(createHonoShutdownTask(server));

server.listen(3000);

Events

shutdown.on("beforeShutdown", (reason) => {
  console.log("Shutdown started", reason);
});

shutdown.on("draining", () => {
  console.log("Waiting for active requests");
});

shutdown.on("drained", () => {
  console.log("Active requests finished");
});

shutdown.on("drainTimeout", () => {
  console.warn("Drain timed out, running tasks anyway");
});

shutdown.on("afterShutdown", (result) => {
  console.log(result.success, result.completed, result.failed);
});

drainTimeout fires when the tracker does not reach zero in time. Tasks still run.

API reference

GracefulShutdown

class GracefulShutdown {
  constructor(options?: GracefulShutdownOptions);

  readonly isShuttingDownState: boolean;

  addTask(task: ShutdownTask): this;
  removeTask(name: string): boolean;
  getTaskNames(): string[];

  shutdown(reason?: ShutdownReason): Promise<ShutdownResult>;

  on(event: "beforeShutdown", listener: (reason: ShutdownReason) => void): this;
  on(event: "draining" | "drained" | "drainTimeout", listener: () => void): this;
  on(event: "afterShutdown", listener: (result: ShutdownResult) => void): this;
}

shutdown() is idempotent. Every caller gets the same promise. The first call sets isShuttingDownState to true.

ShutdownResult

interface ShutdownResult {
  success: boolean;
  completed: string[];
  failed: Array<{ name: string; error: Error }>;
  durationMs: number;
}

ShutdownTask

interface ShutdownTask {
  name: string;
  handler: () => Promise<void> | void;
  timeout?: number;
  priority?: number;
}

NodeConnectionTracker

class NodeConnectionTracker {
  attach(server: Server): this;
  detach?(): void;
  readonly activeCount: number;
  waitForDrain(timeoutMs: number): Promise<void>;
}

The tracker counts requests that have started and not finished. It listens to the Node HTTP server's request, finish, and close events.

Utility exports

The root also exports:

  • createHttpShutdownTask(server, options?)
  • gracefulShutdown, a lazily created singleton
  • handleNode503
  • shouldRejectRequest
  • withTimeout
  • isAttachable
  • Priority constants and shutdown types

Prefer new GracefulShutdown() over the singleton in tests and multi-tenant workers. The singleton is created on first use so importing the module does not install signal handlers.

Production notes

  • Set hardTimeoutMs below your platform's stop timeout. Kubernetes terminationGracePeriodSeconds and Docker's --stop-timeout should leave room for the forced exit.
  • Register the shutdown middleware before routes so draining instances do not accept new work.
  • Keep the liveness probe independent of dependencies. The shutdown middleware returns 503 for new requests, including liveness, once shutdown starts. With Express or Hono, you can register the liveness route before the middleware to keep it at 200. The Fastify hook is global, so leave the hook out or add an explicit exemption if liveness must stay at 200.
  • Use a drain timeout shorter than the hard timeout. With the defaults, the drain can take 10 seconds and the HTTP close task can take 15 seconds, leaving room inside 30 seconds. Each additional task can consume its own timeout, so budget the sum of task timeouts as well.
  • Do not close the database before in-flight requests finish. The tracker drains first, then tasks run.
  • Flush logs last, after the resources that may write logs.
  • Run tests with installSignalHandlers: false so the test process does not exit.

When not to use it

  • Serverless functions with no long-lived process. The platform controls the lifecycle.
  • Short-lived scripts that do not own a listening socket or shared resources.
  • Apps that already use a shutdown coordinator and cannot register another signal handler.

On this page