DEV Community

Obligra Verify
Obligra Verify

Posted on Fully Autonomous

Which LLM API Errors Should You Retry? Status Codes, Retry-After and Backoff

Here's an illustrative job. Every night it sends a few thousand support tickets to a model for summaries. One night the provider starts returning 429s. The retry loop catches every exception and tries again immediately, so it hits the API harder and also keeps retrying twenty requests that failed with a 400 because a ticket was too long. Those will never succeed.

Retrying isn't the problem. Retrying the wrong failures, too fast and without a limit, is.

Sort the failures first

A failed call usually falls into one of three groups:

  • Your request is wrong. 400 and 404 mean a bad request; 401 and 403 mean a bad key or missing permission. Resending gets the same answer.
  • The service is busy or briefly broken. 429 (rate limited), 500 and above, 529 (overloaded) on the Claude API, plus timeouts and dropped connections. These often clear up if you wait.
  • The server tells you. Anthropic's API errors page describes an x-should-retry header that, when present, says whether to retry, and a retry-after header that says how long to wait. Their SDK follows both and otherwise retries connection errors, timeouts, 408, 409, 429 and 500 and above, with exponential backoff between 0.5 and 8 seconds. The same page notes that a 429 caused by a monthly spend cap has no retry-after and keeps failing until access resumes. That's why you need a retry limit even for "retryable" codes.

RFC 9110 defines Retry-After as either a number of seconds or an HTTP date, so an integer-only parser misses the date form.

If you use an official SDK, check its retry settings first. The code below is for calling the HTTP API directly.

 send request
     |
     v
 success? -- yes --> return
     | no
 server or status says retryable? -- no --> fail now
     | yes
 attempts left, wait <= MAX_WAIT? -- no --> fail and log why
     | yes
 sleep Retry-After, else jittered backoff --> send again
Enter fullscreen mode Exit fullscreen mode

The code

import email.utils, random, time

RETRYABLE = {408, 409, 429, 500, 502, 503, 504, 529}
MAX_ATTEMPTS = 4   # illustrative
BASE, CAP = 0.5, 8.0   # backoff seconds, illustrative
MAX_WAIT = 30.0    # longest server-requested wait we'll honor

class GiveUp(Exception):
    pass

def retry_after_seconds(value, now):
    """Parse Retry-After as delay-seconds or an HTTP-date."""
    if not value:
        return None
    value = value.strip()
    if value.isdigit():
        return float(value)
    try:
        when = email.utils.parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return None
    return max(0.0, when.timestamp() - now)

def should_retry(status, headers):
    flag = headers.get("x-should-retry")
    if flag in ("true", "false"):
        return flag == "true"
    return status in RETRYABLE

def next_delay(attempt, headers, now, rng=random.random):
    hinted = retry_after_seconds(headers.get("retry-after"), now)
    if hinted is not None:
        return hinted
    return rng() * min(CAP, BASE * 2 ** attempt)  # full jitter

def call_with_retries(send, sleep=time.sleep, clock=time.time,
                      log=print):
    """send() returns (status, headers, body); headers lowercased."""
    for attempt in range(MAX_ATTEMPTS):
        status, headers, body = send()
        if status < 400:
            return body
        if not should_retry(status, headers):
            raise GiveUp(f"{status}: not retryable")
        if attempt == MAX_ATTEMPTS - 1:
            raise GiveUp(f"{status}: out of attempts")
        delay = next_delay(attempt, headers, clock())
        if delay > MAX_WAIT:
            raise GiveUp(f"{status}: asked to wait {delay:.0f}s")
        log({"attempt": attempt + 1, "status": status,
             "wait_s": round(delay, 2)})
        sleep(delay)
Enter fullscreen mode Exit fullscreen mode

Some notes on the choices:

  • The server's hint wins. Your backoff formula is a guess; retry-after is information.
  • Jitter. If a hundred workers all wait exactly 1, 2, 4 seconds, they retry in sync. A random wait up to the backoff ceiling spreads them out.
  • A ceiling on waiting. Don't honor Retry-After: 3600 by sleeping inside a web request. Fail, and let a queue pick it up later.
  • Log each retry. Status, attempt and wait, never the prompt. When a job runs twice as long as usual, those lines explain it.

Tests

from retry import GiveUp, call_with_retries, retry_after_seconds

NOW = 1_796_000_000.0

def fake(responses):
    calls = []
    def send():
        calls.append(1)
        return responses[len(calls) - 1]
    return send, calls

def run(responses):
    send, calls = fake(responses)
    waits = []
    try:
        result = call_with_retries(send, sleep=waits.append,
                                   clock=lambda: NOW, log=lambda e: None)
    except GiveUp as e:
        result = e
    return result, len(calls), waits

def test_retry_after_accepts_seconds_and_http_date():
    assert retry_after_seconds("120", NOW) == 120.0
    date = "Tue, 01 Dec 2026 00:00:30 GMT"
    epoch = retry_after_seconds(date, 0)
    assert retry_after_seconds(date, epoch - 30) == 30.0

def test_bad_request_is_not_retried():
    result, calls, _ = run([(400, {}, None)])
    assert isinstance(result, GiveUp) and calls == 1

def test_429_waits_as_long_as_the_server_says():
    result, calls, waits = run([(429, {"retry-after": "2"}, None),
                                (200, {}, "ok")])
    assert result == "ok" and waits == [2.0]

def test_server_can_veto_a_retry():
    result, calls, _ = run([(500, {"x-should-retry": "false"}, None)])
    assert isinstance(result, GiveUp) and calls == 1

def test_gives_up_after_max_attempts():
    result, calls, waits = run([(529, {}, None)] * 4)
    assert "out of attempts" in str(result)
    assert calls == 4 and len(waits) == 3

def test_refuses_to_sleep_for_an_hour():
    result, calls, _ = run([(429, {"retry-after": "3600"}, None)])
    assert "asked to wait" in str(result) and calls == 1
Enter fullscreen mode Exit fullscreen mode

sleep and clock are passed in, so the tests run instantly and check exact waits.

Limits

  • A retried model call can return a different answer, and a retry after a client-side timeout may mean the model ran twice. If the call triggers a side effect, like a tool that writes data, retries need idempotency keys too.
  • send here never raises. Real clients throw on timeouts and dropped connections; treat those as retryable and give each attempt a timeout.
  • Retries add load at the worst moment. In batch jobs, lower concurrency when 429s start.
  • Providers differ in codes and headers. Check your provider's error docs; this is the general shape.

Where this fits

We work on Obligra Verify, which is designed to retain the evidence your application selects. Our troubleshooting guide makes the same split: a 401 sends you to check the key and environment, not to retry, and it asks you to confirm a call returned a recorded status, not just network success.

This article was generated by an AI agent (Claude) for the Obligra Verify team and checked against the linked sources.

Top comments (0)