Skip to content

Cap retries and budget them

Retries feel free. They are not. Every retry sends the whole prompt again, and you pay for it again. The fix is not "no retries". It is retries with a plan.

Three rules

1. Retry in one place. HTTP clients, vendor SDKs, agent frameworks and your own code can all retry. Pick one layer, usually your own wrapper, and set the others to zero. Read your SDK docs for its default retry setting; many retry by default.

2. Retry only errors that can pass. Rate limits (429), timeouts and server errors (5xx) may work on a later try. A bad request, a prompt that is too long, or an auth error will fail the same way every time. Retrying them just burns money and quota.

3. Back off, add jitter, cap it. Wait longer after each failure, add randomness so many clients do not retry at the same moment, and stop after a few attempts. If the API sends a Retry-After header, respect it.

Python

import random, time

RETRIABLE = {429, 500, 502, 503, 504}

class APIError(Exception):
    def __init__(self, status): self.status = status

def call_with_retry(fn, max_attempts=3, base=0.5, cap=8.0, log=print):
    for attempt in range(1, max_attempts + 1):
        try:
            return fn()
        except APIError as e:
            if e.status not in RETRIABLE or attempt == max_attempts:
                log(f"giving up: status={e.status} attempt={attempt}")
                raise
            wait = random.uniform(0, min(cap, base * 2 ** attempt))  # full jitter
            log(f"retry {attempt}: status={e.status} wait={wait:.2f}s")
            time.sleep(wait)

if __name__ == "__main__":
    replies = iter([APIError(429), APIError(503), "ok"])
    def fake():
        r = next(replies)
        if isinstance(r, Exception): raise r
        return r
    print(call_with_retry(fake, base=0.01))
    try:
        call_with_retry(lambda: (_ for _ in ()).throw(APIError(400)))
    except APIError:
        print("400 not retried")

JavaScript

const RETRIABLE = new Set([429, 500, 502, 503, 504]);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function callWithRetry(fn, { maxAttempts = 3, baseMs = 500, capMs = 8000 } = {}) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (!RETRIABLE.has(err.status) || attempt >= maxAttempts) throw err;
      const wait = Math.random() * Math.min(capMs, baseMs * 2 ** attempt);
      console.log(`retry ${attempt}: status=${err.status} wait=${Math.round(wait)}ms`);
      await sleep(wait);
    }
  }
}

// demo
let n = 0;
callWithRetry(async () => {
  if (++n < 3) throw Object.assign(new Error("busy"), { status: 429 });
  return "ok";
}, { baseMs: 10 }).then(console.log);

Both use "full jitter": a random wait between zero and the current backoff limit.

Budget the retries

Treat attempts as part of the cost of a task. If a call path averages 1.5 attempts, it costs about 1.5 times what one call costs. Log the attempt number with every request. Then you can:

Watch for repair loops

A common pattern: the model returns bad JSON, so you send it back with "fix this". Each round adds the broken output to the prompt, so every try is longer than the last. Cap these loops at one or two rounds. Better yet, use your vendor's structured output or JSON mode if it has one, and validate in code.

Checklist

Background: Retry and cost multipliers.

All field notes