Skip to content

Retry the right errors, log the request id

Write error handling for Claude calls that retries only transient errors with backoff, branches on the SDK's typed errors, logs the request id, and change code with Claude in small, checked steps.

Scenario

An order-tagging service wraps every Claude call in a helper: catch any exception, sleep one second, try again, five times.

On Tuesday a template change leaves a required field out of the request. Every order now makes six identical calls, all rejected with a 400, and the alert says only "Claude call failed". Nobody can tell which request failed, or why, and the retries made the queue six times longer.

The helper treated a broken request like a busy server.

Explanation

Two kinds of failure. Some errors say try again later; others say this request is wrong.

Status Type Retry?
429 rate_limit_error Yes, after a wait
500 api_error Yes, with backoff
504 timeout_error Yes; stream long requests
529 overloaded_error Yes, with backoff
connection error, timeout (no response) Yes
400 invalid_request_error No: fix the request
401, 403 authentication, permission No: fix the key or access
413 request_too_large No: send less

Retrying a 400 sends the same broken request again and gets the same answer. One 429 is an exception to watch for: when your organization reaches its usage tier's monthly spend cap, the 429 has no retry-after header and keeps failing until access resumes, so alert a person instead of retrying. (A spend limit you set yourself returns a 400.)

The SDK already retries. The official Python and TypeScript SDKs retry connection errors, 408, 409, 429 and 5xx errors twice by default, with exponential backoff, and honour retry-after. Tune that with max_retries (maxRetries in TypeScript) rather than wrapping calls in your own tight loop, which hammers an API that is already overloaded.

Branch on types, not on text. The SDK raises a typed error per status: BadRequestError (400), AuthenticationError (401), RateLimitError (429), InternalServerError (5xx), APIConnectionError (no response). Catch the most specific class first. Message wording can change between SDK versions; the class and status code are the contract.

Log the request id. Every response carries a request-id header (req_...), and error bodies repeat it as request_id. The Python and TypeScript SDKs expose it as _request_id on responses. Support needs it to find one failed call among millions.

Run calls concurrently, with a limit. Rate limits count requests and tokens per minute, and a sharp jump in traffic can hit acceleration limits. Cap how many calls are in flight (a semaphore or a worker pool) and ramp up rather than firing everything at once.

Change code in small, checked steps. When Claude refactors your integration, give it a check it can run (tests, a build), plan before a change that spans many files, and commit each step. A small diff that passes the tests is easy to review and easy to revert.

Worked example

Before: retries everything, matches on text, logs nothing useful.

for attempt in range(5):
    try:
        return client.messages.create(**req)
    except Exception as e:
        if "overloaded" in str(e):
            time.sleep(1)
            continue
        log.error("Claude call failed")
        raise

After: the SDK retries the transient errors with backoff; the code sorts what is left by type and logs the id.

client = anthropic.Anthropic(max_retries=4)
try:
    msg = client.messages.create(**req)
    log.info("tagged order rid=%s", msg._request_id)
except (anthropic.RateLimitError,
        anthropic.InternalServerError) as e:
    rid = e.response.headers.get("request-id")
    log.warning("status %s rid=%s", e.status_code, rid)
    queue.defer(order_id)
except anthropic.APIStatusError as e:
    rid = e.response.headers.get("request-id")
    log.error("status %s rid=%s", e.status_code, rid)
    raise

A 429 or 5xx (InternalServerError covers every status from 500 up) that survives four backed-off retries defers the order instead of blocking the queue. Every other status error, such as a 400, 401, 403 or 413, fails fast with an id you can hand to support or search in your logs.