Write the retry spec before the agent writes the retry loop
Agents produce retry wrappers that retry everything, ignore Retry-After and double-charge customers. Ten fake-timer tests written first catch all of it. About 20 minutes to try.

Ask any coding agent for “a fetch wrapper that retries on failure” and the result usually looks fine: a loop, an exponential delay, a clean return. It also retries a 400 five times, replays a POST /orders that already went through, sleeps for one second when the server said to wait thirty, and has no ceiling on the delay. None of that shows up in a demo against a healthy server.
The fix is to write the policy down as tests first, in a form that doesn’t depend on real time. Below is a ten-test spec for a retry wrapper in TypeScript, using Vitest fake timers, plus what happens when a naive implementation meets it: 8 of the 10 fail. The method works with any agent that can read files and run a shell, because the spec and the check are plain files and a plain npx vitest run.
Decide the policy before anyone writes code
A retry wrapper is mostly decisions, and an agent will make them silently if the prompt doesn’t. Write them as a short list first. These are the ones that matter:
- What is retryable? Network failures and 429, 502, 503 and 504. Never other 4xx codes: a 400 will fail identically every time.
- Which methods?
fetchdoesn’t reject on HTTP errors, only on network failure (it rejects with aTypeError, per the MDN page forfetch), so the wrapper has to inspect status itself. RFC 9110 defines PUT, DELETE and the safe methods as idempotent, so those can be replayed. A POST is replayed only if the caller sent anIdempotency-Keyheader, and only if your server really deduplicates on it. - Who sets the pace? If the server sends
Retry-After, that wins over the client’s own backoff. RFC 9110 says the value is either an HTTP-date or a number of seconds. - What is the ceiling? A maximum delay, and a rule for a
Retry-Afterbeyond it. Here, the wrapper gives up and returns the response instead of sleeping for an hour. - How is the delay spread? Exponential backoff with jitter, so a thousand clients that failed together don’t all return together.
Each decision becomes one or more tests. Time is the hard part: nobody wants a suite that sleeps for real, and nobody wants to inject a clock into every function. Vitest’s vi.useFakeTimers() replaces timers and Date until vi.useRealTimers() is called, and vi.advanceTimersByTimeAsync(ms) runs timers, including ones scheduled from inside promise callbacks, which is exactly the shape of a retry loop.
The spec
Set up a project with npm i -D vitest typescript and save this as src/retry.test.ts. It imports a module that doesn’t exist yet, so the first run fails, which is the point.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fetchWithRetry } from "./retry";
const opts = { maxAttempts: 4, baseDelayMs: 100, maxDelayMs: 5_000, random: () => 0.5 };
const res = (status: number, headers: Record<string, string> = {}) =>
new Response(null, { status, headers });
beforeEach(() => vi.useFakeTimers({ now: new Date("2026-11-11T12:00:00Z") }));
afterEach(() => vi.useRealTimers());
describe("fetchWithRetry", () => {
it("retries a GET on 503 and returns the success", async () => {
const f = vi.fn().mockResolvedValueOnce(res(503)).mockResolvedValueOnce(res(200));
const p = fetchWithRetry("https://x.test/a", undefined, { ...opts, fetchImpl: f });
await vi.advanceTimersByTimeAsync(1_000);
expect((await p).status).toBe(200);
expect(f).toHaveBeenCalledTimes(2);
});
it("never retries a 400", async () => {
const f = vi.fn().mockResolvedValue(res(400));
const r = await fetchWithRetry("https://x.test/a", undefined, { ...opts, fetchImpl: f });
expect(r.status).toBe(400);
expect(f).toHaveBeenCalledTimes(1);
});
it("does not retry a POST without an Idempotency-Key", async () => {
const f = vi.fn().mockResolvedValue(res(503));
const r = await fetchWithRetry("https://x.test/orders", { method: "POST" }, { ...opts, fetchImpl: f });
expect(r.status).toBe(503);
expect(f).toHaveBeenCalledTimes(1);
});
it("retries a POST that carries an Idempotency-Key", async () => {
const f = vi.fn().mockResolvedValueOnce(res(503)).mockResolvedValueOnce(res(201));
const init = { method: "POST", headers: { "Idempotency-Key": "k1" } };
const p = fetchWithRetry("https://x.test/orders", init, { ...opts, fetchImpl: f });
await vi.advanceTimersByTimeAsync(1_000);
expect((await p).status).toBe(201);
});
it("waits for Retry-After seconds, not the backoff", async () => {
const f = vi.fn().mockResolvedValueOnce(res(429, { "Retry-After": "3" })).mockResolvedValueOnce(res(200));
const p = fetchWithRetry("https://x.test/a", undefined, { ...opts, fetchImpl: f });
await vi.advanceTimersByTimeAsync(2_999);
expect(f).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
expect((await p).status).toBe(200);
});
it("honours a Retry-After HTTP-date", async () => {
const f = vi.fn()
.mockResolvedValueOnce(res(503, { "Retry-After": "Wed, 11 Nov 2026 12:00:02 GMT" }))
.mockResolvedValueOnce(res(200));
const p = fetchWithRetry("https://x.test/a", undefined, { ...opts, fetchImpl: f });
await vi.advanceTimersByTimeAsync(1_999);
expect(f).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
expect((await p).status).toBe(200);
});
it("gives up at once when Retry-After is longer than maxDelayMs", async () => {
const f = vi.fn().mockResolvedValue(res(503, { "Retry-After": "3600" }));
const r = await fetchWithRetry("https://x.test/a", undefined, { ...opts, fetchImpl: f });
expect(r.status).toBe(503);
expect(f).toHaveBeenCalledTimes(1);
});
it("backs off with jitter and never exceeds the cap", async () => {
const f = vi.fn().mockResolvedValue(res(503));
const p = fetchWithRetry("https://x.test/a", undefined,
{ ...opts, maxAttempts: 10, baseDelayMs: 1_000, random: () => 0.999, fetchImpl: f });
await vi.advanceTimersByTimeAsync(5_000 * 9);
expect((await p).status).toBe(503);
expect(f).toHaveBeenCalledTimes(10);
});
it("stops after maxAttempts", async () => {
const f = vi.fn().mockResolvedValue(res(502));
const p = fetchWithRetry("https://x.test/a", undefined, { ...opts, fetchImpl: f });
await vi.advanceTimersByTimeAsync(10_000);
expect((await p).status).toBe(502);
expect(f).toHaveBeenCalledTimes(4);
});
it("retries a network TypeError on GET and rethrows on the last attempt", async () => {
const f = vi.fn().mockRejectedValue(new TypeError("fetch failed"));
const p = fetchWithRetry("https://x.test/a", undefined, { ...opts, fetchImpl: f });
const assertion = expect(p).rejects.toThrow("fetch failed");
await vi.advanceTimersByTimeAsync(10_000);
await assertion;
expect(f).toHaveBeenCalledTimes(4);
});
});
Three details in there are deliberate. The fetchImpl option lets tests pass a mock instead of stubbing a global. The fixed clock (now: new Date("2026-11-11T12:00:00Z")) makes the HTTP-date test deterministic: the header is two seconds ahead of it. And the Retry-After tests advance to 2,999 ms and assert nothing has happened yet, then advance one more millisecond. Boundary assertions like that are what separate “waited about right” from “waited the right amount”.
The last test needs care. A rejected promise with no handler attached while the timers run is an unhandled rejection, so the assertion is attached before time advances and awaited after.
Give the agent the spec, not the idea
The prompt is short, because the tests carry the detail:
Create src/retry.ts exporting fetchWithRetry(url, init, opts) and the RetryOptions
interface so that every test in src/retry.test.ts passes. Run `npx vitest run` and
`npx tsc --noEmit --strict`. Don't edit the test file. If a test seems wrong, stop
and say which one and why.
The last sentence matters. An agent that is blocked by a test will sometimes edit the test, and a diff that touches the spec file deserves a harder look than the implementation.
Here’s what a passing implementation looks like. The version below passes all ten tests and the strict type check under TypeScript 7.0.2.
export interface RetryOptions {
maxAttempts: number; // total tries, including the first
baseDelayMs: number;
maxDelayMs: number; // also the longest Retry-After the client will wait
random?: () => number;
fetchImpl?: typeof fetch;
}
const RETRYABLE_STATUS = new Set([429, 502, 503, 504]);
const IDEMPOTENT = new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
export function retryAfterMs(header: string | null, now: number): number | null {
if (header === null) return null;
if (/^\d+$/.test(header.trim())) return Number(header) * 1000;
const at = Date.parse(header);
return Number.isNaN(at) ? null : Math.max(0, at - now);
}
function mayRetry(init: RequestInit | undefined): boolean {
const method = (init?.method ?? "GET").toUpperCase();
if (IDEMPOTENT.has(method)) return true;
return new Headers(init?.headers).has("Idempotency-Key");
}
export async function fetchWithRetry(
url: string,
init: RequestInit | undefined,
opts: RetryOptions,
): Promise<Response> {
const doFetch = opts.fetchImpl ?? fetch;
const random = opts.random ?? Math.random;
const canRetry = mayRetry(init);
for (let attempt = 1; ; attempt++) {
let response: Response | undefined;
try {
response = await doFetch(url, init);
} catch (error) {
if (!(error instanceof TypeError) || !canRetry || attempt >= opts.maxAttempts) throw error;
}
if (response) {
if (!RETRYABLE_STATUS.has(response.status) || !canRetry || attempt >= opts.maxAttempts) {
return response;
}
}
const hinted = retryAfterMs(response?.headers.get("Retry-After") ?? null, Date.now());
if (hinted !== null && hinted > opts.maxDelayMs) return response!;
const ceiling = Math.min(opts.maxDelayMs, opts.baseDelayMs * 2 ** (attempt - 1));
const delay = hinted ?? Math.floor(random() * ceiling);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
Run it and the output ends with:
Test Files 1 passed (1)
Tests 10 passed (10)
The jitter here is “full jitter”: a random delay between zero and the exponential ceiling. That’s a design choice, not the only one, and the spec only pins the cap, so a different jitter scheme would pass too. If the team has a preference, add a test for it.
What the naive version does
This is the version an agent often writes first when the prompt is “add retries”, about twelve lines:
export async function fetchWithRetry(url: string, init: RequestInit | undefined, opts: RetryOptions): Promise<Response> {
const doFetch = opts.fetchImpl ?? fetch;
let last: Response | undefined;
for (let attempt = 0; attempt < opts.maxAttempts; attempt++) {
last = await doFetch(url, init);
if (last.ok) return last;
await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
}
return last!;
}
Point the same spec at it and it fails 8 tests and passes 2:
× never retries a 400
× does not retry a POST without an Idempotency-Key
× waits for Retry-After seconds, not the backoff
× honours a Retry-After HTTP-date
× gives up at once when Retry-After is longer than maxDelayMs
× backs off with jitter and never exceeds the cap
× stops after maxAttempts
× retries a network TypeError on GET and rethrows on the last attempt
Tests 8 failed | 2 passed (10)
Read the failures as a defect list. It retries a 400 and a bare POST (the double-charge bug). It sleeps by its own schedule whatever the server asks. Its delays double without a cap, so the tenth wait is 512 seconds. It sleeps after the final attempt before returning. And a network error escapes on the first try, because nothing catches it. The two passing tests are the happy path and the plain retry on 503, which is all a demo exercises.
Make it yours
Change the policy numbers, not the method. A server-to-server client can raise maxAttempts and maxDelayMs. A browser call behind a button should keep both low, since a user won’t wait thirty seconds. If the API has a different idempotency mechanism, change mayRetry and its two tests, and nothing else.
Two things the spec doesn’t cover yet and the next tests should: an AbortSignal on init (a cancelled request must stop the loop, not sleep through it) and a Retry-After of 0. Write each as a failing test first, then ask the agent for the change.
Where this falls short
Fake timers prove the schedule, not the network. They won’t tell you whether your server actually deduplicates on Idempotency-Key; that needs a test against the server or a contract test. They also mock Date, so code that reads the clock for other reasons (logging, token expiry) sees frozen time in these tests.
Skip all of this if the project already depends on an HTTP client with a maintained retry policy. Then the work is configuring it and writing a couple of tests that pin the settings, not writing a loop.
First 20 minutes
Copy the test file into a scratch project, run npx vitest run and watch it fail on the missing module. Hand the prompt above to whichever agent you use, and read its diff for any change to the test file before reading the implementation. Then run the spec against the retry code already in your own codebase; if it fails more than two of these, that’s the next ticket.