Retry Budget With Total Deadline
A retry policy that stops when the total deadline is reached instead of retrying a fixed count, returning the last error and the attempt log.
Code
export async function withRetryBudget(call, options) {
const {
deadlineMs,
delayMs = 100,
now = () => Date.now(),
sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
} = options;
if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) {
throw new RangeError("deadlineMs must be a positive number");
}
const start = now();
const attempts = [];
let lastError = null;
while (true) {
const elapsed = now() - start;
if (elapsed >= deadlineMs) {
return { ok: false, reason: "deadline-exceeded", attempts, lastError };
}
const attemptNo = attempts.length + 1;
try {
const value = await call(attemptNo);
attempts.push({ attempt: attemptNo, ok: true });
return { ok: true, value, attempts };
} catch (err) {
attempts.push({ attempt: attemptNo, ok: false, error: String(err) });
lastError = err;
const remaining = deadlineMs - (now() - start);
if (remaining <= delayMs) {
return { ok: false, reason: "deadline-exceeded", attempts, lastError };
}
await sleep(delayMs);
}
}
}A fixed retry count can exceed the caller budget by multiplying per-attempt timeouts, so the total latency blows past the SLA.
Use case: engineers who need retries bounded by wall-clock time, not attempt count
Inputs / outputs
- Input: a call function, total deadline ms, per-attempt delay, injectable clock and sleep
- Output: the result on success, or a deadline error with the attempt history
Error conditions
- deadline already reached before the first attempt
- all attempts fail within the deadline
Approach
loop while now < deadline; check the remaining budget before sleeping; abort the loop when the next attempt cannot fit; return the last failure with the attempt count.
Implementation
export async function withRetryBudget(call, options) {
const {
deadlineMs,
delayMs = 100,
now = () => Date.now(),
sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
} = options;
if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) {
throw new RangeError("deadlineMs must be a positive number");
}
const start = now();
const attempts = [];
let lastError = null;
while (true) {
const elapsed = now() - start;
if (elapsed >= deadlineMs) {
return { ok: false, reason: "deadline-exceeded", attempts, lastError };
}
const attemptNo = attempts.length + 1;
try {
const value = await call(attemptNo);
attempts.push({ attempt: attemptNo, ok: true });
return { ok: true, value, attempts };
} catch (err) {
attempts.push({ attempt: attemptNo, ok: false, error: String(err) });
lastError = err;
const remaining = deadlineMs - (now() - start);
if (remaining <= delayMs) {
return { ok: false, reason: "deadline-exceeded", attempts, lastError };
}
await sleep(delayMs);
}
}
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { withRetryBudget } from "./example.mjs";
test("returns the first success", async () => {
let calls = 0;
const result = await withRetryBudget(
async () => { calls += 1; return "done"; },
{ deadlineMs: 1000, delayMs: 1 },
);
assert.equal(result.ok, true);
assert.equal(result.value, "done");
assert.equal(calls, 1);
});
test("stops when the deadline is reached", async () => {
let calls = 0;
const result = await withRetryBudget(
async () => { calls += 1; throw new Error("always down"); },
{ deadlineMs: 30, delayMs: 5 },
);
assert.equal(result.ok, false);
assert.equal(result.reason, "deadline-exceeded");
assert.ok(calls >= 1);
assert.ok(calls < 100);
assert.equal(result.attempts.length, calls);
});
test("reports attempt history on failure", async () => {
const result = await withRetryBudget(
async () => { throw new Error("boom"); },
{ deadlineMs: 10, delayMs: 100 },
);
assert.equal(result.ok, false);
assert.equal(result.attempts.length, 1);
assert.equal(result.attempts[0].ok, false);
assert.match(result.attempts[0].error, /boom/);
});
test("rejects a non-positive deadline", async () => {
await assert.rejects(withRetryBudget(async () => 1, { deadlineMs: 0 }), RangeError);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node example.mjs
Limitations and error handling
single call chain; no jitter; no circuit breaking across calls.
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
Report a problem with this exampleOpens a pre-filled issue on GitHub.