Handling API Errors and Retries
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Every production Claude integration will see errors: a rate limit at the busiest hour, an overloaded API, a dropped connection, a spend cap on the 28th. The difference between a robust app and a fragile one is having decided in advance what each error means and what to do about it. This lesson gives you that decision table and tested code.
Learning objectives
- Classify errors as retryable, fixable or terminal.
- Know what the official SDKs retry automatically and how to configure it.
- Tell a normal rate limit apart from a spend cap or a ramp limit.
- Write a retry wrapper with exponential backoff and jitter.
- Log the information support will ask for.
Prerequisites
The decision table
| Status / type | Meaning | Retry? | Action |
400 invalid_request_error | The request is wrong, or a spend limit you set was reached. | No | Fix the request; log it. |
401 authentication_error | Bad, expired or revoked key. | No | Alert an operator. |
402 billing_error | Billing problem. | No | Alert an operator. |
403 permission_error | Key lacks permission. | No | Fix workspace/key settings. |
404 not_found_error | Wrong endpoint, ID or model. | No | Fix code or config. |
413 request_too_large | Body too big. | No | Send less data. |
429 rate_limit_error | Rate limit, ramp limit or spend cap. | Sometimes | Honour retry-after if present; see below. |
500 api_error | Problem inside Anthropic's systems. | Yes | Exponential backoff; contact support with the request ID if it persists. |
504 timeout_error | Request timed out. | Yes | Use streaming for long requests. |
529 overloaded_error | API temporarily overloaded. | Yes | Backoff and retry. |
The API may also use invalid_request_error for other 4xx codes, and new error types can appear over time, so keep a default branch for statuses you did not list.
Three kinds of 429
- Rate limit: you exceeded RPM, ITPM or OTPM. Usually carries
retry-after (seconds). Wait that long.
- Ramp limit: a sharp increase in usage tripped a cap on how fast usage can grow, even when you are under your rate limits.
error.details.error_code is ramp_limit_exceeded. Wait for retry-after, hold traffic steady, then increase by at most one step per minute. Start bulk jobs slowly.
- Spend cap: your tier's monthly cap was reached. There is no
retry-after header and error.details.error_code is enforced_spend_limit_reached. Retrying, including the SDK's automatic retries, fails until access resumes.
A limit you set yourself in the Console returns 400, not 429. In both cases the correct reaction to a spend limit is to stop and alert someone, not to retry.
What the SDKs already do
The official SDKs automatically retry transient failures (connection errors, rate limits, 5xx errors and timeouts; the PHP SDK documentation also lists 408 and 409), twice by default, with exponential backoff, honouring retry-after when present. Configure with max_retries in Python and maxRetries in PHP. That means you rarely need to write low-level retry code. What the SDK cannot know is your product's policy: how long a user will wait, what message to show, and which errors should page someone.
Step by step: Python wrapper
This wrapper lets the SDK do its two retries, then adds a small outer policy: honour retry-after for rate limits, give up immediately on a spend-cap 429, back off with jitter on server and network errors, and raise one clean exception your UI can show:
import random
import time
import anthropic
# The SDK already retries connection errors, 429 and 5xx twice with backoff.
# This wrapper adds what the SDK cannot know: your own limits and what to tell the user.
client = anthropic.Anthropic(max_retries=2, timeout=60.0)
class ClaudeUnavailable(Exception):
"""Raised when the request failed in a way the caller should show to the user."""
def ask(prompt: str, attempts: int = 3) -> str:
for attempt in range(1, attempts + 1):
try:
message = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=300,
messages=[{"role": "user", "content": prompt}],
)
return "".join(b.text for b in message.content if b.type == "text")
except anthropic.RateLimitError as e:
# A spend-cap 429 has no retry-after header and never succeeds until the cap resets.
if e.response.headers.get("retry-after") is None:
raise ClaudeUnavailable("Usage limit reached. Try again later.") from e
wait = float(e.response.headers["retry-after"])
except (anthropic.InternalServerError, anthropic.APIConnectionError, anthropic.APITimeoutError):
wait = min(2**attempt, 20) + random.random() # exponential backoff with jitter
except anthropic.AuthenticationError as e:
raise ClaudeUnavailable("The server's API key is invalid.") from e
except anthropic.BadRequestError as e:
# 400: the request itself is wrong. Retrying the same request cannot help.
raise ClaudeUnavailable(f"Bad request (request id {e.response.headers.get('request-id')}).") from e
if attempt == attempts:
raise ClaudeUnavailable("Claude is busy right now. Please try again in a minute.")
time.sleep(wait)
raise ClaudeUnavailable("unreachable")
Run against a mock that returns the failures, this behaved as intended: two 529s then success returned an answer; a 400 and a 401 raised at once with no retries; a persistent 529 gave up with the friendly message after about 11 seconds.
Step by step: PHP
The PHP SDK throws typed exceptions, all subclasses of Anthropic\Core\Exceptions\APIException. Catch the specific ones first:
use Anthropic\Core\Exceptions\APIConnectionException;
use Anthropic\Core\Exceptions\APIStatusException;
use Anthropic\Core\Exceptions\AuthenticationException;
use Anthropic\Core\Exceptions\BadRequestException;
use Anthropic\Core\Exceptions\RateLimitException;
try {
$message = $client->messages->create(
maxTokens: 300,
messages: [['role' => 'user', 'content' => $prompt]],
model: config('services.anthropic.model'),
);
} catch (RateLimitException $e) {
// The SDK has already retried. Tell the caller to slow down.
return response()->json(['message' => 'Busy, try again shortly.'], 429);
} catch (AuthenticationException|BadRequestException $e) {
// Our bug or configuration. Alert, do not retry.
report($e);
return response()->json(['message' => 'The assistant is misconfigured.'], 500);
} catch (APIConnectionException|APIStatusException $e) {
// Includes 5xx and 529 (OverloadedException) after retries.
report($e);
return response()->json(['message' => 'The assistant is unavailable right now.'], 503);
}
Order matters: APIStatusException is the general class for status errors, so list the specific ones first. In testing against a mock, a persistent 529 raised OverloadedException, a 500 raised InternalServerException (both caught by APIStatusException), and an unreachable host raised APIConnectionException.
What to log
For every failure record: HTTP status, error type, the request_id from the error body or the request-id header, the model, and your own correlation ID. Do not log the key or the full prompt if it may contain personal data. The request ID is what Anthropic support needs.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
An invoice-processing job sends 5,000 documents overnight. Version one fired them all at once and tripped a ramp limit within seconds. Version two starts at a few requests per second, raises the rate every minute while errors stay at zero, and uses the Batch API for the largest nights. When a 429 with enforced_spend_limit_reached appears, it stops the whole job and emails the owner instead of hammering the API until morning.
Common errors and solutions
| Problem | Cause | Fix |
| Retry storm during an outage | Every client retries immediately. | Exponential backoff with jitter. |
| Job retries forever on 429 | Spend cap has no retry-after. | Detect the missing header or enforced_spend_limit_reached and stop. |
| Same bad request retried | Retrying a 400. | Never retry 4xx except 408, 409, 429. |
| Duplicate side effects after a retry | Retry re-ran code that sends emails or charges cards. | Keep side effects outside the retried call, or make them idempotent. |
| Error text shown to users contains internals | Raw exception message returned. | Return a fixed safe message; log the details. |
Security considerations
- Do not leak upstream error bodies to end users; they may include request IDs and internal details.
- A sudden run of 401s can mean a leaked-and-revoked key or an expired one; alert on it.
- Rate-limit your own endpoints so a bot cannot drive your account into 429 for everyone.
Performance and cost considerations
- Retries cost latency. Set a total time budget so users are not left waiting through five backoffs.
- A retried request that finally succeeds is a full request, so retries add both latency and (when a failure happened late) duplicated work. Prefer streaming for long jobs so a network blip does not force a restart.
- Cached input tokens do not count toward your input-tokens-per-minute limit, so caching also reduces 429s (lesson 2.9).
Key takeaways
- Retry 429 (with care), 500, 504, 529 and connection errors; never retry other 4xx.
- A 429 without
retry-after, or with enforced_spend_limit_reached, is a stop signal.
- The SDKs already retry twice with backoff; add policy, not duplicate retries.
- Log status, type and request ID; keep keys and personal data out.
Lesson recap: classify each error as retryable, fixable or terminal, and log what support needs.
Knowledge check
- Which of 400, 401, 429, 500 and 529 are normally worth retrying?
- How do you recognise a spend-cap 429?
- How many times do the SDKs retry by default, and how do you change it?
- Why add random jitter to backoff?
- Why must a retried call not send an email or charge a card inside it?
Answers and explanations
- 429 (depending on the cause), 500 and 529. A 400 means the request is wrong and a 401 means the key is wrong, so repeating them cannot succeed.
- It has no
retry-after header and error.details.error_code is enforced_spend_limit_reached. Retrying keeps failing until access resumes.
- Twice. Use
max_retries (Python) or maxRetries (PHP), set to 0 to disable.
- Without jitter, many clients retry at the same instant and overload the API again together.
- A retry would repeat the side effect. Do side effects once, outside the retried call, or make them idempotent.
Official references and further reading
Related tutorials