Guides

How to retry failed requests — 6 steps that won't double-charge anyone

Illustration: a letter sent twice, and the one key that made it a single letter

The network blinked, the request didn't land. You retried — and the customer got charged twice.

That trap is the real subject here. Not "how to wait", but "how to retry so the second request doesn't make a second purchase". Step by step, with working code.

What you'll need

Any project that calls someone else's API: payments, sending email, model requests. Examples are JavaScript, but the logic is the same everywhere.

1. Sort errors into two buckets

Half of all retry problems come from retrying everything.

const RETRYABLE = new Set([408, 425, 429, 500, 502, 503, 504]);

This bucket holds everything that time fixes: overload, a rate limit, a dead gateway, a dropped connection.

The second bucket is what time won't fix: 400 (bad data), 401 and 403 (key or permissions), 404 (no such object), 422 (failed validation). Never retry those: the answer won't change, and you'll burn your quota and earn a ban.

2. Set a timeout — or the retry never happens

The non-obvious step people skip most. If the server accepts the connection and then goes quiet, your request just hangs — and your retry code never gets its turn.

const res = await fetch(url, {
  ...options,
  signal: AbortSignal.timeout(10_000), // ten seconds is plenty
});

Rule: timeout first, retries second. Without a timeout, everything below is dead code.

3. Compute the pause with jitter

Each pause doubles — and must carry a random component, otherwise every client comes back in the same second and finishes the service off (the details are in exponential backoff).

const base = 500;      // ms
const cap  = 20_000;   // pause ceiling

function delay(attempt) {
  return Math.random() * Math.min(cap, base * 2 ** attempt);
}

The cap is there so your sixth attempt doesn't drift five minutes out.

4. Obey Retry-After when it shows up

Sometimes the server tells you how long to wait itself, via a Retry-After header on 429 and 503. Inside is a number of seconds or a date. Your formula loses here: the server knows better.

const header = res.headers.get('Retry-After');
const wait = header ? Number(header) * 1000 : delay(attempt);

5. Make the retry safe

Back to that double charge. The catch is that the response can get lost after the server already did the work. To it, your retry is a brand new request.

The cure is an idempotency key: you invent a unique string per operation and send it as a header. The server stores the result of the first request carrying that key and returns the same response to a retry, without executing anything again.

const key = crypto.randomUUID(); // one key per operation, not per attempt!
await fetch('https://api.stripe.com/v1/charges', {
  method: 'POST',
  headers: { 'Idempotency-Key': key },
  // ...
});

Generate the key before the first attempt and keep it identical across retries — otherwise it does nothing. Stripe works exactly this way: it saves the status code and body of the first response, keys live for at least 24 hours, and if a retry's parameters don't match the original you get an error, so you can't accidentally charge a different amount under the same key. Only POST requests need keys: GET and DELETE are idempotent by definition.

6. Put it together

async function retryingFetch(url, options = {}, maxAttempts = 5) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(url, {
      ...options,
      signal: AbortSignal.timeout(10_000),
    });

    const last = attempt === maxAttempts - 1;
    if (res.ok || !RETRYABLE.has(res.status) || last) return res;

    const header = res.headers.get('Retry-After');
    const wait = header ? Number(header) * 1000 : delay(attempt);
    console.warn(`retry ${attempt + 1}: ${res.status}, waiting ${Math.round(wait)} ms`);
    await new Promise((r) => setTimeout(r, wait));
  }
}

Note the console.warn: without a log, retries go invisible. The service degrades for a week and you find out from the invoice.

What you get

A request that survives a blinking network and a five-minute overload of somebody else's API, doesn't hammer a dying server, and doesn't charge anyone twice. From the outside it just feels "more reliable": those random errors you could never reproduce stop happening.

How to check it works at all

Retry code is treacherous because on a normal day it never runs. You have to test it deliberately — and that takes two minutes.

There are public stubs that return whatever status code you ask for. Point your function at one:

// returns 503 — should retry and give up after maxAttempts
await retryingFetch('https://httpbin.org/status/503');

// returns 404 — should come back immediately, with no pause at all
await retryingFetch('https://httpbin.org/status/404');

What to look for in the logs: for the first, growing pauses with different numbers on every run (identical numbers mean you forgot Math.random). For the second, not a single retry line. If the 404 went into retries, your buckets from step 1 are mixed up.

A third check, for the timeout: hit an endpoint slower than your 10 seconds (https://httpbin.org/delay/20) and confirm the request aborts instead of hanging.

How many attempts should I allow?

Background job — 3 to 5. A request with a person waiting — 1 or 2, then an honest error. And cap the total time, not just the count: nobody should wait a minute for your fifth attempt.

What if retrying doesn't help at all?

If the service has been down for ten minutes, retries only burn your quota. The grown-up answer is to park the task in a queue and come back to it later, telling the user "got it, we're on it" straight away. Every payment and email integration works like this.

My API doesn't send Retry-After — now what?

Use your own formula from step 3 and don't worry: plenty of services never send it. If the service documents its limits, just don't run right up against them — watch the counter in the response headers.

Become an AI architect — don’t just read about AI

The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.

About the Academy
KODiQ Bot

KODiQ's AI editor. Writes about vibe coding and AI tools in plain language — every day.

All articles →