
Not Every Claude API Error Deserves a Retry: 400s, 429s and 529s
- كاتب موثّق
- Claude API
محتويات المقال
while True retry loop turned a bug that should have failed on the first call into three days of silence.
The common misconception
Networks drop connections and services have bad minutes, and "retry with " is standard advice. Some Claude API errors really are transient, and the docs themselves say to retry a 500 with exponential backoff. In development, the only errors you meet are timeouts and rate limits, and a retry fixes both. A loop that never gives up looks robust: nothing crashes and nobody gets paged.
What actually happens
The status code says who has to act
error object holding a type and a message, plus a request_id. The docs list the codes, and sorted by who has to act, they fall into two groups:
error.type | |||
|---|---|---|---|
invalid_request_error | |||
authentication_error / permission_error | |||
request_too_large | |||
rate_limit_error | retry-after | ||
api_error | |||
overloaded_error |
billing_error and a 404 not_found_error join the "fix it" group. Two codes ask for a specific move instead of a blind retry: on a 409 conflict_error the docs say to resolve the conflict, then retry, and on a 504 timeout_error they point you to streaming for long requests. The docs also warn that the type values may grow over time, so code that maps types must have a default branch.
The SDK already retries for you
retry-after header when present." In Python, that covers connection errors, 408, 409, 429 and every status of 500 or above, and max_retries on the client changes the count.
RateLimitError reaches your code, it's already the third failed attempt. Wrap that call in your own loop of five and one bad minute becomes fifteen requests, most of them sent with a fixed one-second sleep that ignores how long the API asked you to wait. The non-retryable errors arrive at once, as typed exceptions: BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError. The docs' advice is to catch these typed classes "rather than string-matching error messages, handling the most specific classes first."
Not every 429 is a rate limit
retry-after header is "the number of seconds to wait until you can retry the request. Earlier retries will fail." A sharp jump in your traffic can also trigger 429s from acceleration limits, which is why the docs advise ramping up gradually.
rate_limit_error, but with no retry-after header, and usage pauses until 00:00 UTC on the first day of the next month. The docs are blunt: "Retrying, including the SDK's automatic retries, fails until access resumes." The body carries a code you can test:
{ "type": "error", "error": { "type": "rate_limit_error", "message": "You have reached your API usage limits: ...", "details": { "error_code": "enforced_spend_limit_reached" } }, "request_id": "req_018EeWyXxfu5pfWkrYcMdjWG"}invalid_request_error whose message starts with "You have reached your specified API usage limits".
529 isn't about you
overloaded_error means "the API is temporarily overloaded", and the docs add that it "can occur when the API experiences high traffic across all users." Both deserve backoff, but your rate-limit headers won't explain a 529, and hammering an overloaded API makes it worse for everyone, you included. With streaming, the same error can arrive after a 200, as an error event inside the stream.
Fixing the worker
import timeimport anthropicclient = anthropic.Anthropic()def tag(ticket: str): while True: # "the API is flaky, retry until it works" try: return client.messages.create( model="claude-opus-5-5", max_tokens=1024, messages=[ {"role": "user", "content": f"Tags for:\n{ticket}"}, {"role": "assistant", "content": "Tags:"}, # prefill ], ) except Exception as err: # a 400 loops here forever print(f"retrying in 1s: {err}") time.sleep(1)tag("Customer reports a double charge on order 1042")import anthropicSPEND_CAP = "enforced_spend_limit_reached"client = anthropic.Anthropic() # retries 408/409/429/5xx twice, with backoffdef tag(ticket: str): try: return client.messages.create( model="claude-opus-5-5", max_tokens=1024, messages=[{"role": "user", "content": f"Tags for:\n{ticket}"}], ) except anthropic.RateLimitError as err: # still 429 after the SDK's retries error = err.response.json()["error"] if error.get("details", {}).get("error_code") == SPEND_CAP: raise SpendCapReached(error["message"]) from err # page a human wait = int(err.response.headers.get("retry-after", 60)) requeue(ticket, delay=wait) except anthropic.InternalServerError: # 500 or 529 after the retries requeue(ticket, delay=300) # 400, 401, 403, 404 aren't caught: retrying can't fix themtag("Customer reports a double charge on order 1042")BadRequestError on the first call, with a message that names the problem. The docs suggest structured outputs or instructions in the system prompt in place of a prefill. A busy minute goes back to the queue with the delay the API asked for, and the spend cap reaches a person instead of a loop.
How to apply it in your project
Find your retry wrappers Search for except Exceptionaroundmessages.create, and for retry decorators. Remove the ones that only repeat what the SDK already does.Catch typed exceptions, most specific first Handle RateLimitErrorandInternalServerErrorexplicitly, and let request errors such asBadRequestErrorreach your error tracker with the request ID.Read the 429 before you wait Use retry-afterwhen it's there. When it isn't, checkerror.details.error_codefor the spend cap and alert someone instead of retrying.Retry at the right level In a request a user is waiting on, keep retries short and fail fast. In a background worker, put the job back on the queue with a delay instead of sleeping inside the handler. Ramp traffic and watch headroom Raise volume gradually to avoid acceleration limits, and watch the anthropic-ratelimit-*-remainingheaders or the Console's rate-limit charts before you hit the wall.
Key takeaways
The status code says whether to fix the request or wait: most 4xx errors won't change on a retry. 429, 500 and 529 are worth retrying with backoff, and the official SDK already retries them twice by default. A 429 with enforced_spend_limit_reachedand noretry-afterwon't clear by retrying: alert, don't loop.A 529 means the API is overloaded for everyone; a 429 means your organization hit a limit. Catch the SDK's typed exceptions and log the request ID, so bugs fail fast and outages are traceable.
التعليقات (0)