How to test retry logic: 429s, Retry-After and backoff with jitter

25 November 2026 · 7 min read

Most retry code ships without ever seeing a real 429. It gets written during an incident, reviewed by someone who nods at the word "backoff", and covered by a unit test that mocks fetch to throw once. Then a payment provider starts rate limiting on a busy Friday, and the logs show your client retrying forty times in a second, ignoring the Retry-After: 30 it was handed on every response.

This guide covers what correct retry logic has to get right, a small fetch wrapper that does it (tested against a real server), and how to test retry logic against failures that behave like production: a 503 that clears up, a 429 with Retry-After, and a 422 that must never be retried.

Why retry logic is so rarely tested

Retries only run when something else goes wrong, so the happy path never exercises them. The usual unit test replaces the HTTP client with a stub that returns an error, which checks that a retry happens but says nothing about when it happens, what it sends, or when it stops.

The bugs that hurt in production are almost all about timing and judgment:

  • retrying instantly, so a struggling server gets hit again before it can recover
  • ignoring Retry-After, which turns a short rate limit into a long ban
  • retrying errors that will never succeed, like a 400 or a 422
  • retrying a POST without an idempotency key and charging a card twice
  • never giving up, so one bad dependency ties up every worker you have
  • waiting forever on a request that will never answer

A stub can't show you any of these. You need a server that fails the way real ones do, and a way to see every attempt your client made.

What correct retry logic has to get right

Retry only failures that can go away

Some failures are transient: the server was busy, a deploy was rolling, a connection dropped. Others are a verdict on your request, and sending it again gets the same answer.

Response Retry? Why
Network error, connection reset, timeout Yes Nothing reached a decision
408 Request Timeout Yes The server gave up waiting for you
429 Too Many Requests Yes, after Retry-After You're over a limit that resets
500, 502, 503, 504 Yes Server-side, often temporary
400, 401, 403, 404, 422 No The request itself is the problem

Honor Retry-After in both formats

RFC 9110 defines Retry-After as either a number of seconds or an HTTP-date:

Retry-After: 120
Retry-After: Fri, 31 Dec 1999 23:59:59 GMT

Servers send it with 503 (and RFC 6585 allows it on 429). Plenty of clients only parse the integer form, then fall back to their own short backoff when they meet a date. If the server tells you when to come back, that number wins over your backoff. And if it says "come back in an hour", the right move is usually to stop and surface the error rather than hold a request open for 3,600 seconds.

Back off exponentially, with jitter

Each retry should wait longer than the last, and the waits should be randomized so that a thousand clients failing at the same moment don't all come back at the same moment. AWS's write-up on exponential backoff and jitter compares the common variants. "Full jitter" (a random wait between zero and the ceiling) spreads load best, but it can also pick a wait of a few milliseconds, which is a retry that hammers. "Equal jitter" keeps half the wait fixed and randomizes the other half, so the first retry still waits a reasonable amount.

Cap attempts, and time out each one

Three or four attempts is plenty for most calls. Each attempt also needs its own timeout: a request that hangs for five minutes isn't a failure your retry loop can see, it's just a stuck worker.

Send the same Idempotency-Key on every retry

GET, PUT and DELETE are idempotent by definition, so repeating them is safe. POST isn't. If a payment request times out, you don't know whether the charge went through. APIs like Stripe solve this with an Idempotency-Key header (there's an IETF draft standardizing it): send one unique key per logical operation, the same key on every retry, and the server returns the original result instead of doing the work twice. A retry that generates a fresh key on each attempt is worse than no key at all.

A retry wrapper for fetch in TypeScript

This wraps the standard fetch (Node 18+ or any browser) and does everything above. We ran it against a local server that answers 503, then 429 with Retry-After, then 200, plus the edge cases: an HTTP-date Retry-After, 400/401/422, a POST with and without a key, a hung request and an exhausted budget.

const RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);
const IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);

type RetryOptions = {
  maxAttempts?: number; // total tries, including the first
  baseDelayMs?: number; // first backoff ceiling
  maxDelayMs?: number; // backoff never grows past this
  maxRetryAfterMs?: number; // give up rather than wait longer than this
  timeoutMs?: number; // per attempt
};

/** Retry-After is either delay-seconds ("120") or an HTTP-date (RFC 9110, section 10.2.3). */
export function parseRetryAfter(value: string | null, now = Date.now()): number | null {
  if (!value) return null;
  const v = value.trim();
  if (/^\d+$/.test(v)) return Number(v) * 1000;
  const at = Date.parse(v);
  return Number.isNaN(at) ? null : Math.max(0, at - now);
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export async function fetchWithRetry(url: string, init: RequestInit = {}, opts: RetryOptions = {}): Promise<Response> {
  const { maxAttempts = 4, baseDelayMs = 500, maxDelayMs = 20_000, maxRetryAfterMs = 60_000, timeoutMs = 10_000 } = opts;

  // A POST is only safe to repeat if the server can deduplicate it.
  const method = (init.method ?? "GET").toUpperCase();
  const canRetry = IDEMPOTENT_METHODS.has(method) || new Headers(init.headers).has("Idempotency-Key");

  for (let attempt = 1; ; attempt++) {
    const last = !canRetry || attempt >= maxAttempts;
    let res: Response | undefined;
    try {
      res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
    } catch (err) {
      if (last) throw err; // network error or timeout: retry unless out of attempts
    }

    if (res && (last || !RETRYABLE_STATUS.has(res.status))) return res;

    // Exponential backoff with "equal jitter": half the ceiling, plus a random share of the other half.
    const ceiling = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
    const backoff = ceiling / 2 + Math.random() * (ceiling / 2);
    const serverWait = parseRetryAfter(res?.headers.get("retry-after") ?? null);
    if (res && serverWait !== null && serverWait > maxRetryAfterMs) return res; // not worth waiting

    await res?.body?.cancel(); // release the connection before sleeping
    await sleep(Math.max(backoff, serverWait ?? 0));
  }
}

A few details that are easy to miss:

  • The idempotency key lives outside the loop. Because init is reused, every attempt sends the same headers, so the key can't change between retries:

    const res = await fetchWithRetry("https://api.example.com/payments", {
      method: "POST",
      headers: { "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID() },
      body: JSON.stringify({ amount: 4200, currency: "usd" }),
    });
    
  • It returns the last response instead of throwing when attempts run out, so the caller still sees the real status and body.

  • The wait is the larger of the backoff and Retry-After. With the defaults, waits run 250 to 500 ms, then 500 to 1,000 ms, then 1 to 2 s.

  • Cancelling the body before sleeping lets the connection go back to the pool instead of being held open during the wait.

Python: urllib3's Retry does most of this

If you use requests, mount urllib3's Retry on a session:

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(
    total=4,                                   # retries, so up to 5 attempts
    status_forcelist=[408, 429, 500, 502, 503, 504],
    backoff_factor=0.5,
    backoff_jitter=0.5,                        # urllib3 2.0+
)
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))

We checked this against urllib3 2.8.0. Retry-After is honored by default (respect_retry_after_header=True), POST is left out of the default allowed_methods, and when retries run out requests raises RetryError. One thing surprised us: the first retry happens immediately. urllib3 only starts backing off from the second consecutive error, so unless the server sent Retry-After, the first retry goes out within milliseconds of the failure.

How to test retry logic against real failures

Now the part most teams skip. A local stub server (like the one we used to check the wrapper) is good for unit tests, but it only fails in the ways you thought to script. To test retry logic the way production will, point the client at a server that fails on purpose and records every attempt.

That's what Jitterbox does: it gives you a fake version of the API you call, at a real URL (https://<projectKey>.jitterbox.dev), and failure scenarios that make it slow, flaky or broken. In your tests, swap the real base URL for the Jitterbox one through an environment variable.

Fail twice, then succeed

The most useful retry test is deterministic: the first two attempts fail and the third succeeds. A scenario with a sequence trigger does exactly that. In jitterbox.yaml (applied with the CLI):

project: payments-api
endpoints:
  - method: POST
    path: /payments
    status: 201
    json: { id: pay_123, status: succeeded }
scenarios:
  - name: Fail twice then succeed
    enabled: false
    faults:
      - error: 503
        pattern: xx.     # x = fail, . = pass; the pattern repeats

The same thing is a few clicks in the dashboard: add a scenario, add an HTTP error, set the trigger to a sequence. Your test asserts that the call eventually returned 201, and Jitterbox's request log shows each of the three attempts with its timestamp.

A 429 with Retry-After

To check that the client actually waits, return a rate limit with a header:

  - name: Rate limited
    enabled: false
    faults:
      - error: 429
        headers: { Retry-After: "2" }
        pattern: x.

A client that respects the header waits at least two seconds before its second attempt. One that ignores it comes back after its own backoff, and the timestamps make that obvious.

Force a fault on a single request

Scenarios apply to every matching request. For a one-off case inside a test, send the X-Jitterbox-Fault header instead. It forces a fault on that request and bypasses scenarios:

curl -i https://<projectKey>.jitterbox.dev/payments -X POST \
  -H 'X-Jitterbox-Fault: http_error=422'

That's the cheapest way to prove your client doesn't retry a validation error. Other directives include http_error=503, latency=1500 and timeout.

Read the resilience report

Watching timestamps by eye gets old. Jitterbox groups each logical call and its retries into an operation and grades how the client behaved (full details). Some of the checks:

Check Fails when
Retries transient failures the client stopped right after a 408, 429, 5xx, timeout or dropped stream
Respects Retry-After a retry came sooner than the server asked
Backs off a retry arrived within 200 ms of the failure
Gives up eventually more than 10 attempts
Doesn't retry permanent errors the client retried a 400, 401, 403, 404, 405, 410, 413 or 422
Keeps the idempotency key a retried POST dropped or changed its Idempotency-Key

Requests are grouped automatically, but in a test suite send X-Jitterbox-Operation with a unique value per logical call so the grouping is exact. The "Backs off" check is the one that catches the urllib3 behavior above: an immediate first retry arrives well inside 200 ms.

Run it in CI so it stays fixed

Retry logic regresses quietly. Someone swaps HTTP clients, a default changes in a major version, and nothing fails until the next incident. jitterbox run switches a scenario on, runs your tests against the fake API, switches it off, and fails the build if a check fails:

JITTERBOX_TOKEN=jb_… npx jitterbox run --scenario "Fail twice then succeed" -- npm test

There's also a GitHub Action, with an option to require specific checks such as respects-retry-after and backs-off. See Jitterbox in CI.

Your next step

Pick the one outbound call that would hurt most if it failed (payments, auth, the LLM call in your main feature), point its base URL at an environment variable, and run it once against a "fail twice, then succeed" scenario. Whatever the request log shows is how that call behaves in your next outage. The getting started guide gets you a fake endpoint in a couple of minutes, free during the beta.

Questions people ask

Which HTTP status codes should a client retry?

Retry failures that can clear up on their own: network errors and timeouts, 408, 429, 500, 502, 503 and 504. Don't retry 400, 401, 403, 404 or 422, because the request itself is the problem and sending it again gets the same answer. Only retry a POST if it carries an Idempotency-Key, so the server can deduplicate it.

What format does the Retry-After header use?

RFC 9110 allows two formats: a whole number of seconds, such as Retry-After: 120, or an HTTP-date, such as Retry-After: Fri, 31 Dec 1999 23:59:59 GMT. A client should parse both. If the date is in the past, retry now. If the wait is very long, it's usually better to stop and report the error than to hold the request open.

Should retries use exponential backoff with jitter?

Yes. Exponential backoff gives a struggling server more time with each attempt, and jitter randomizes the waits so many clients don't retry at the same instant. Full jitter can pick a near-zero wait, so a common compromise is equal jitter: half of the exponential wait is fixed and the other half is random. When the server sends Retry-After, wait at least that long.

How do I test retry logic without waiting for a real outage?

Point your client at a server that fails on purpose. A deterministic sequence such as fail, fail, succeed checks that retries happen and eventually stop; a 429 with Retry-After checks that the client waits; a forced 422 checks that it doesn't retry. Jitterbox provides these as failure scenarios at a real URL and grades the client's retries in a resilience report.

Does urllib3 Retry back off before the first retry?

No. urllib3 only applies backoff_factor from the second consecutive error, so the first retry goes out immediately unless the server sent a Retry-After header, which urllib3 honors by default for 413, 429 and 503. It also leaves POST out of its default allowed_methods, so POST requests aren't retried unless you opt in.

Try it on your own code

Jitterbox gives you a fake version of the APIs you call, at a real URL, and makes them fail on purpose. Free during the beta.