Handle Claude API Errors, Rate Limits and Retries
- Errors come back as JSON with a top-level
errorobject (typeandmessage) and arequest_id. Log therequest-idresponse header; support asks for it. - Documented codes: 400
invalid_request_error, 401authentication_error, 402billing_error, 403permission_error, 404not_found_error, 409conflict_error, 413request_too_large, 429rate_limit_error, 500api_error, 504timeout_error, 529overloaded_error. - The official SDK already retries transient failures with exponential backoff, 2 times by default, and honors
retry-afterwhen present. Setmax_retriesto change or disable it. The Python SDK page lists connection errors, 408, 409, 429 and 5xx as retried. - For a 429, wait
retry-afterseconds; earlier retries fail. Not every 429 has that header. A spend-cap 429 never has it and keeps failing until access resumes, so checkerror.details.error_codeforenforced_spend_limit_reached. - Rate limits are counted in requests, input tokens and output tokens per minute, with a token bucket that refills continuously. For most models, cache reads do not count toward input tokens per minute.
- Streaming can fail after a 200 response, and that error does not follow these rules.
- On 2026-11-04 I read three official pages and tested only the decision function of the demo script locally. I did not call the real API (no API key, no
anthropicpackage), so the retry loop itself is untested here.
What you’ll be able to do after this tutorial
Section titled “What you’ll be able to do after this tutorial”- Read an error response and decide whether to fix the request, wait and retry, or stop.
- Tell a normal rate limit 429 from a spend-cap 429.
- Use the SDK’s built-in retries instead of writing your own, and know when your own layer still helps.
- Read the rate limit headers and the
request-idto debug and to report problems.
Concepts to know first
Section titled “Concepts to know first”| Term | Meaning |
|---|---|
| Transient error | A failure that may succeed if you try again: connection problems, 429, 5xx. |
| Exponential backoff | Waiting longer after each failed try, for example 1, 2, 4 seconds. |
retry-after |
A response header with the number of seconds to wait. The docs say earlier retries will fail. |
| Token bucket | The docs say rate limiting uses this algorithm, so capacity refills continuously up to the maximum instead of resetting at fixed times. |
| Request ID | The request-id header, also the request_id field in error bodies. Include it when you contact support. |
Step-by-step guide
Section titled “Step-by-step guide”-
Read the error shape
Every error is JSON with
type: "error", anerrorobject with its owntypeandmessage, and arequest_id:{"type": "error","error": {"type": "not_found_error","message": "The requested resource could not be found."},"request_id": "req_011CSHoEeqs5C35K2UUqR7Fy"}The docs warn that the values inside these objects may expand over time, so do not assume the list of
typevalues is closed. Also, a 400invalid_request_errormay be used for other 4XX codes not listed. -
Sort the status codes into three groups
This grouping is my reading of the docs’ descriptions, not a table from the docs.
Group Codes (docs name) What to do Fix the request or account, then resend 400 invalid_request_error, 401authentication_error, 402billing_error, 403permission_error, 404not_found_error, 413request_too_largeRetrying the same request will not help. Check the format, the API key, billing in the Console, workspace access, the endpoint path, or the request size. Resolve, then retry 409 conflict_errorThe docs say to resolve the conflict, then retry. Temporary, retry with backoff 429 rate_limit_error, 500api_error, 504timeout_error, 529overloaded_errorThe docs say to retry a 500 with exponential backoff, and to wait retry-afterseconds on a 429 when it is present.Details worth knowing from the docs:
- A 400 is also returned when usage reaches a spend limit you set yourself (the message starts with
You have reached your specified API usage limits). Raise or remove the limit to restore access sooner. - A 401 starting with
CORS requests are not allowed for this Organizationis not an API key problem. The request had anOriginheader (browsers add it), and your organization cannot call the API directly from a browser. Send the request from your own back end. - A 529 means the API is temporarily overloaded and can happen under high traffic across all users. In rare cases a sharp rise in your own usage can cause 429 errors from acceleration limits; increase traffic gradually.
- A 504
timeout_errorcan also appear with other status codes, for example a 500 when a request hits the server time limit before the response starts. - The Messages API request size limit is 128 MB (Batch API 256 MB, Files API 500 MB). Larger requests get a 413.
- A 400 is also returned when usage reaches a spend limit you set yourself (the message starts with
-
Let the SDK retry first
You do not have to write a retry loop for the common cases. The docs say the official SDK retries transient failures (connection errors, rate limits, 5xx) with exponential backoff, twice by default, honoring
retry-after. The Python SDK page also lists 408 and 409 and says the backoff is short. Configure it on the client or per request:from anthropic import Anthropicclient = Anthropic(max_retries=0) # default is 2; 0 turns retries offclient.with_options(max_retries=5).messages.create(max_tokens=1024,messages=[{"role": "user", "content": "Hello, Claude"}],model="claude-opus-5-5",)Timeouts are separate: the default is 10 minutes, set with
timeout, and a timeout raisesAPITimeoutError. Timed-out requests are retried twice by default too, so a short timeout multiplied by retries can mean a long wait. -
Catch the SDK’s typed exceptions
The SDK raises subclasses of
APIErrorinstead of returning raw JSON. Catch the specific classes first, and do not string-match messages:Status Python class 400 BadRequestError401 AuthenticationError403 PermissionDeniedError404 NotFoundError409 ConflictError422 UnprocessableEntityError429 RateLimitError500 and above InternalServerErrorno response APIConnectionErrorOther languages have their own names; the errors page links each SDK’s page. The Python page notes that
e.status_codeande.responseare available onAPIStatusError. -
Know the two kinds of 429
A rate limit 429 is about speed: you sent too many requests, input tokens or output tokens in a short time. The response tells you which limit, and usually has
retry-after. Waiting is the fix.A spend-cap 429 is about money: the usage tier’s monthly spend cap was reached. The docs give these caps per tier: Start $500, Build $1,000, Scale $200,000 per month; Custom has none. Usage pauses until 00:00 UTC on the first day of the next month unless you get a higher limit. The error body looks like this (message shortened):
{"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"}The type is the same
rate_limit_error, but there is noretry-afterheader, and retrying, including the SDK’s automatic retries, fails until access resumes. On the Messages API useerror.details.error_codeto tell them apart. Spend limits on the Claude Code workspace are checked separately and can return a 429 that does carryretry-after. -
Add a small layer of your own
Save this as
safe_call.py. It turns the SDK’s own retries off (max_retries=0) so there is only one retry layer, stops at once on errors that retrying cannot fix, and for the rest waitsretry-after(or 1, 2, 4 seconds) before one more attempt from your code. The jitter (a random fraction of a second) is common practice, not from the docs.import randomimport timeimport anthropicMODEL = "claude-opus-5-5"# The SDK already retries connection errors, 408, 409, 429 and >=500# 2 times by default (honoring retry-after). Here we turn that off.client = anthropic.Anthropic(max_retries=0) # one retry layer: this script's loopdef decide(status, headers, body):"""Return (action, note). action is "fix", "stop", or "wait"."""error = (body or {}).get("error", {})code = (error.get("details") or {}).get("error_code")if status == 429 and code == "enforced_spend_limit_reached":return "stop", "Monthly spend cap reached. Retrying will keep failing."if status == 429 and "retry-after" not in headers:return "stop", "429 without retry-after. Check the message before retrying."if status in (400, 401, 402, 403, 404, 413):return "fix", f"{error.get('type')}: {error.get('message')}"if status in (429, 500, 504, 529):return "wait", f"{error.get('type')}: temporary"return "fix", f"unexpected status {status}"def ask(prompt, tries=3):for attempt in range(tries):try:return client.messages.create(model=MODEL,max_tokens=300,messages=[{"role": "user", "content": prompt}],)except anthropic.APIStatusError as e:try:body = e.response.json()except ValueError:body = {}action, note = decide(e.status_code, e.response.headers, body)print(f"status {e.status_code} | request-id {e.response.headers.get('request-id')} | {note}")if action != "wait" or attempt == tries - 1:raiseseconds = float(e.response.headers.get("retry-after") or 2 ** attempt)time.sleep(seconds + random.random()) # small jitterexcept anthropic.APIConnectionError:print("could not reach the API")if attempt == tries - 1:raisetime.sleep(2 ** attempt)if __name__ == "__main__":reply = ask("Say hello in one short sentence.")print(reply.content[0].text)I compiled it and tested
decidewith made-up status codes, headers and bodies; it classified a spend-cap body as “stop”, a 429 withretry-afteras “wait”, a 429 without it as “stop”, a 529 as “wait”, and a 400 as “fix”. The loop was not run against the real API. Readinge.response.json()ande.response.headersfollows thee.responseattribute shown on the Python SDK page; I did not confirm the exact body accessors beyond that.SDK retries are off here, so the script makes at most 3 attempts in total. If you keep the SDK’s retries on instead, drop your own loop: two stacked layers multiply the attempts (for example 3 x 5 = 15) and add load during an outage.
-
Read the rate limit headers
Every response carries headers that show the limit, what is left and when it refills. The docs list these (replace
...with the limit type):Header Meaning retry-afterSeconds to wait; earlier retries fail. Not on every 429 anthropic-ratelimit-requests-limit/-remaining/-resetRequest limit, requests left, refill time (RFC 3339) anthropic-ratelimit-input-tokens-limit/-remaining/-resetSame for input tokens (remaining is rounded to the nearest thousand) anthropic-ratelimit-output-tokens-limit/-remaining/-resetSame for output tokens anthropic-ratelimit-tokens-*The most restrictive limit currently in effect (total of input and output when no workspace limit applies) In Python,
client.messages.with_raw_response.create(...)givesresponse.headers, andresponse.parse()returns the normal message. Use this to slow down before you hit zero, for example by pausing when-remaininggets low. Priority Tier has its ownanthropic-priority-*headers.To raise limits, the docs point to Request tier increase on the Rate limits page of the Console, or Anthropic support. You can also set lower limits per workspace so one project cannot use up the whole organization. Your own limits and tier appear in the Console at
platform.claude.com/usage/limits; I did not read your numbers, so look them up there. -
Cut how often you hit limits
- Cache the repeated part. The docs say that for most models only uncached input tokens count toward input tokens per minute:
input_tokensandcache_creation_input_tokenscount,cache_read_input_tokensdoes not. See Dev 19. - Use batches for work that can wait. The Message Batches API has its own rate limits. See Dev 16.
- Stream long outputs. For long requests, especially over 10 minutes, the docs recommend streaming or batches. Some networks drop idle connections, and the SDK checks that non-streaming requests are not expected to exceed 10 minutes. See Dev 15.
- Ramp up gradually to stay clear of acceleration limits.
Copy and paste this promptReview my Claude API error handling. List which HTTP status codes my code retries and which it gives up on, and check them against this rule set: 400, 401, 402, 403, 404 and 413 need a fix before resending; 429 uses the retry-after header when present; a 429 with no retry-after or with error_code enforced_spend_limit_reached should stop; 500, 504 and 529 use exponential backoff. Also tell me whether my retries stack on top of the SDK default of 2 retries, whether I log the request-id header, and what happens if an error arrives in the middle of a stream. Do not invent rate limit numbers; tell me where to look them up. Here is my code with the API key removed: (paste your code)
- Cache the repeated part. The docs say that for most models only uncached input tokens count toward input tokens per minute:
Quick reference
Section titled “Quick reference”| Item | Value (official docs, as of 2026-11-04) |
|---|---|
| Error body | type: "error", error.type, error.message, request_id |
| Retry-worthy | Connection errors, 429, 5xx (Python page also lists 408 and 409) |
| SDK default | 2 retries with exponential backoff, honors retry-after; max_retries to change |
| Python timeout | 10 minutes by default; APITimeoutError; timeouts are retried too |
retry-after |
Seconds to wait; absent on a spend-cap 429 |
| Spend-cap code | error.details.error_code = enforced_spend_limit_reached |
| Monthly spend cap | Start $500, Build $1,000, Scale $200,000; Custom none |
| Request size | Messages 128 MB, Token Counting 128 MB, Batch 256 MB, Files 500 MB |
| Limits measured in | Requests, input tokens, output tokens per minute, per model class |
| Mid-stream errors | Can occur after a 200 response; see Error events in the streaming docs |
Common sticking points
Section titled “Common sticking points”The SDK seems to hang before it fails
Section titled “The SDK seems to hang before it fails”- Cause: Automatic retries with backoff, and
retry-afterwaits, happen inside the call. With the default 10-minute timeout also retried, a call can take much longer than one timeout. - Fix: Lower
max_retriesortimeoutfor interactive code, and log each failure with its request-id.
A 429 keeps coming back no matter how long I wait
Section titled “A 429 keeps coming back no matter how long I wait”- Cause: It may be a spend-cap 429, which has no
retry-afterand lasts until access resumes (or until your tier is raised). A spend limit you set yourself returns a 400 instead. - Fix: Check
error.details.error_codeand the message, which states when access returns. Look at the Billing page and tier in the Console.
Retries do not help a 400
Section titled “Retries do not help a 400”- Cause: The request itself is wrong, or a limit you set was reached.
- Fix: Read
error.message. The docs also list common validation errors such as prefill not being supported on newer models, thinking blocks being modified, and thinking settings the model does not accept.
I got a 200 but the output stopped with an error
Section titled “I got a 200 but the output stopped with an error”- Cause: With streaming (server-sent events), an error can occur after the 200 response, and it does not follow the standard error mechanisms.
- Fix: Handle error events in the stream. See Error events in the streaming docs and Dev 15.
Browser calls fail with a 401 about CORS
Section titled “Browser calls fail with a 401 about CORS”- Cause: The request includes an
Originheader and your organization cannot call the API from a browser. - Fix: Call the API from your own back end.
Practical tips
Section titled “Practical tips”- Log
request-id, status,error.typeand the time for every failure, but never log the API key or full prompts that hold personal data. - Make the code that gets a “stop” answer loud: alert a person instead of retrying all night.
- Give retried writes a way to avoid doing the same work twice in your own system, since a request that timed out may or may not have been processed. This is general advice, not from the docs.
- Test failure paths on purpose, for example with a wrong API key, before you need them.
- Tie spend caps and rate limits back to cost work: Dev 2 and Dev 11.
Next tutorials
Section titled “Next tutorials”- 1. Build a work bot with tool use — a loop where retries and errors matter
- 15. Streaming responses (real-time output) — errors that arrive mid-stream
- 16. Large jobs with the Batches API (half price) — a different path for work that can wait
- 19. Prompt caching — fewer input tokens counted against the limit
- C16. Getting started with the API
Sources
Last verified: Nov 4, 2026
- Claude API errors platform.claude.com
- Rate limits platform.claude.com
- Python SDK (handling errors, retries, timeouts) platform.claude.com
Prices, limits, and menu names change often. Before making an important decision, check the official pages above for the latest details.
Finished this tutorial?
Progress is saved only in this browser and never sent anywhere.