الانتقال إلى المحتوى
Claude وأدوات الـ AI للبرمجةClaude API و Tool Use· 8 دقائق للقراءة

Not Every Claude API Error Deserves a Retry: 400s, 429s and 529s

The status code says whether to fix the request or wait. The SDK already retries the transient ones; your code decides the rest.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Claude API
محتويات المقال

On Monday morning, the ticket-tagging queue hasn't moved since Friday's switch to Claude Opus 5.5. No alert fired and the worker never crashed. Its log holds one line, repeated every second all weekend: a 400 saying "This model does not support assistant message prefill." The migration kept a prefilled assistant turn that newer models reject, and the worker's while True retry loop turned a bug that should have failed on the first call into three days of silence.

The common misconception

"Any failed Claude API call should simply be retried in a loop until it succeeds." It sounds like resilience:

  • 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.

The half-truth: retrying is the right answer for transient failures. But the status code already tells you whether a failure is transient, and a retry can't fix a request that's wrong.

What actually happens

The status code says who has to act

Every error comes back as JSON with an 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:

Statuserror.typeRetry it?What to do
400invalid_request_errorNoFix the format or content of the request
401 / 403authentication_error / permission_errorNoFix the API key or its workspace access
413request_too_largeNoSend less: the Messages API accepts up to 128 MB
429rate_limit_errorUsually, after retry-afterUnless it's the spend cap (see below)
500api_errorYes, with exponential backoffContact support with the request ID if it persists
529overloaded_errorYes, with backoffThe API is busy for everyone, not just you

A 402 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

From the errors page: "The official SDK automatically retries transient failures (such as connection errors, rate limits, and 5xx server errors) with exponential backoff, twice by default, honoring the 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.

So when a 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

are measured per model class in requests, input tokens and output tokens per minute, with a token bucket that refills continuously. Short bursts count: the docs' example is a 60 RPM limit enforced as 1 request per second. The 429 says which limit you hit, and its 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.

Then there's the monthly spend cap of your usage tier. Reaching it also returns a 429 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:

JSON 429 response body
{  "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"}

A spend limit you set yourself, below the tier's cap, behaves differently again: it returns a 400 invalid_request_error whose message starts with "You have reached your specified API usage limits".

529 isn't about you

A 429 is about your organization's limits. A 529 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

The first version treats every failure the same. The second lets the SDK handle short transient failures, decides what to do with each class that survives its retries, and lets request bugs fail on the first call:

Python tagger.py
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")

With the second version's handling, Friday's prefill bug would have raised 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

  1. Find your retry wrappersSearch for except Exception around messages.create, and for retry decorators. Remove the ones that only repeat what the SDK already does.
  2. Catch typed exceptions, most specific firstHandle RateLimitError and InternalServerError explicitly, and let request errors such as BadRequestError reach your error tracker with the request ID.
  3. Read the 429 before you waitUse retry-after when it's there. When it isn't, check error.details.error_code for the spend cap and alert someone instead of retrying.
  4. Retry at the right levelIn 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.
  5. Ramp traffic and watch headroomRaise volume gradually to avoid acceleration limits, and watch the anthropic-ratelimit-*-remaining headers 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_reached and no retry-after won'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.

📚 المصادر

  1. Claude API errors — Claude API Docs
  2. Rate limits — Claude API Docs
  3. Python SDK — Claude API Docs
  4. Streaming Messages — Claude API Docs

التعليقات (0)