Graceful Shutdown Draining In Flight Work

A shutdown coordinator that stops accepting work, waits for in-flight tasks to settle, and force-cancels whatever remains after a deadline.

JavascriptResilience

Code

export async function drain(tracked, options = {}) {
  const { deadlineMs = 5000, onForceCancel } = options;
  if (!Array.isArray(tracked)) throw new TypeError("tracked must be an array");
  if (tracked.length === 0) {
    return { completed: 0, cancelled: 0, timedOut: false };
  }

  const settled = tracked.map((p) => Promise.resolve(p).then(() => "done", () => "failed"));
  let timedOut = false;
  const outcomes = await Promise.race([
    Promise.all(settled),
    new Promise((resolve) =>
      setTimeout(() => {
        timedOut = true;
        if (onForceCancel) onForceCancel();
        resolve(tracked.map(() => "cancelled"));
      }, deadlineMs),
    ),
  ]);

  const completed = outcomes.filter((o) => o === "done" || o === "failed").length;
  const cancelled = outcomes.filter((o) => o === "cancelled").length;
  return { completed, cancelled, timedOut };
}

Killing a process on SIGTERM drops in-flight requests and leaves half written state, so clients see errors the server could have avoided.

Use case: engineers running long lived workers or servers

Inputs / outputs

  • Input: tracked task promises, a drain deadline, an optional force cancel callback
  • Output: a settlement report naming completed, cancelled and timed out work

Error conditions

  • deadline exceeded with work still pending
  • no tracked work at shutdown
  • a task rejects during drain

Approach

close the intake gate; await all tracked promises with a deadline race; on timeout invoke the cancel hook and report what was abandoned.

Implementation

export async function drain(tracked, options = {}) {
  const { deadlineMs = 5000, onForceCancel } = options;
  if (!Array.isArray(tracked)) throw new TypeError("tracked must be an array");
  if (tracked.length === 0) {
    return { completed: 0, cancelled: 0, timedOut: false };
  }

  const settled = tracked.map((p) => Promise.resolve(p).then(() => "done", () => "failed"));
  let timedOut = false;
  const outcomes = await Promise.race([
    Promise.all(settled),
    new Promise((resolve) =>
      setTimeout(() => {
        timedOut = true;
        if (onForceCancel) onForceCancel();
        resolve(tracked.map(() => "cancelled"));
      }, deadlineMs),
    ),
  ]);

  const completed = outcomes.filter((o) => o === "done" || o === "failed").length;
  const cancelled = outcomes.filter((o) => o === "cancelled").length;
  return { completed, cancelled, timedOut };
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { drain } from "./example.mjs";

test("waits for in-flight work to settle", async () => {
  const report = await drain([
    new Promise((r) => setTimeout(() => r("a"), 20)),
    new Promise((r) => setTimeout(() => r("b"), 40)),
  ], { deadlineMs: 500 });
  assert.deepEqual(report, { completed: 2, cancelled: 0, timedOut: false });
});

test("force cancels after the deadline", async () => {
  let cancelled = false;
  const report = await drain([
    new Promise((r) => setTimeout(() => r("slow"), 5000)),
  ], {
    deadlineMs: 20,
    onForceCancel: () => { cancelled = true; },
  });
  assert.deepEqual(report, { completed: 0, cancelled: 1, timedOut: true });
  assert.equal(cancelled, true);
});

test("reports an empty drain", async () => {
  const report = await drain([], { deadlineMs: 10 });
  assert.deepEqual(report, { completed: 0, cancelled: 0, timedOut: false });
});

test("a rejecting task still counts as settled", async () => {
  const report = await drain([Promise.reject(new Error("boom"))], { deadlineMs: 100 });
  assert.equal(report.completed, 1);
  assert.equal(report.timedOut, false);
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node example.mjs

Limitations and error handling

cannot cancel promises that ignore the cancel hook; single process only.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic