Reliability and Error Handling
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.
The API will fail sometimes. Not often, but across thousands of requests it's certain: a 529 when the service is busy, a connection that drops, a 429 when you ramp up too fast. What matters is the experience on those days. A reliable application retries what's worth retrying, stops quickly on what isn't, doesn't make a bad situation worse, and always has something sensible to tell the user. This lesson builds that layer and tests every path.
What you'll learn
- The documented error codes and which ones deserve a retry.
- Exponential backoff with jitter, honouring
retry-after.
- Falling back to another model, and a circuit breaker.
- The special cases: spend limits, ramp limits, refusals, truncation.
- Why you should keep exactly one layer of retries.
Before you start
The errors, from the documentation
| Status | Type | Meaning | Retry? |
| 400 | invalid_request_error | Problem with the request. Also returned when a spend limit you set is reached | No (fix it) |
| 401 | authentication_error | Problem with your key | No |
| 402 | billing_error | Billing or payment problem | No |
| 403 | permission_error | Key lacks permission | No |
| 404 | not_found_error | Resource not found | No |
| 413 | request_too_large | Over the size limit | No |
| 429 | rate_limit_error | Rate limit, ramp limit, or tier spend cap | Depends (see below) |
| 500 | api_error | Unexpected error on Anthropic's side | Yes, with backoff |
| 504 / some 500 | timeout_error | Request timed out while processing | Yes; consider streaming for long requests |
| 529 | overloaded_error | API temporarily overloaded | Yes, with backoff |
Error bodies are JSON with a top-level error object (type and message) and a request_id. The documentation warns that new error types can appear, so code against the broad class, not just the ones listed.
Three 429s need telling apart, and the SDK has classes for them: an ordinary rate limit (retry after retry-after), a ramp limit (error.details.error_code is ramp_limit_exceeded: you grew usage too fast, so hold traffic steady and raise it by a step at a time) and the tier spend cap (enforced_spend_limit_reached), which has no retry-after header and keeps failing until access resumes. Retrying the last one is pure waste. The installed SDK (version 2.8.0 when we tested) has RateLimitError, RampLimitExceededError, EnforcedSpendLimitReachedError and OverloadedError among its exception classes.
One layer of retries
The official SDK already retries transient failures, twice by default, with exponential backoff, and it honours retry-after. If you add your own retry loop on top without turning that off, you multiply attempts: three tries around three tries is nine requests, which makes an overload worse. Pick one place. We turn the SDK's retries off (max_retries=0) and own the policy in the gateway, because that's where we also do fallbacks, logging and the circuit breaker. If you don't need those, leave the SDK's defaults alone and skip this lesson's loop.
The gateway
"""One door to the model. Every call goes through here, so retries, timeouts, logging, fallbacks and usage counting
exist in exactly one place."""
import logging
import random
import threading
import time
from dataclasses import dataclass, field
import anthropic
log = logging.getLogger("gateway")
class GatewayError(Exception):
"""Base class. `retryable` says whether the CALLER might try again later."""
retryable = False
class Unavailable(GatewayError):
retryable = True
class SpendLimit(GatewayError):
"""The account's spend cap was reached. Retrying will not help until the cap is lifted or the month rolls over."""
class BadRequest(GatewayError):
pass
class Refused(GatewayError):
def __init__(self, details=None):
super().__init__("The model declined this request.")
self.details = details
class Truncated(GatewayError):
pass
class CircuitOpen(Unavailable):
pass
@dataclass
class Reply:
text: str
model: str
request_id: str | None
input_tokens: int
output_tokens: int
cache_read_tokens: int = 0
cache_write_tokens: int = 0
stop_reason: str = ""
attempts: int = 1
used_fallback: bool = False
latency_s: float = 0.0
@dataclass
class Breaker:
"""After `threshold` failures in a row, stop calling for `cooldown` seconds so a struggling API isn't hammered."""
threshold: int = 5
cooldown: float = 30.0
clock: callable = time.monotonic
failures: int = 0
opened_at: float | None = None
_lock: threading.Lock = field(default_factory=threading.Lock)
def allow(self) -> bool:
with self._lock:
if self.opened_at is None:
return True
if self.clock() - self.opened_at >= self.cooldown:
return True # half-open: let one attempt through
return False
def success(self) -> None:
with self._lock:
self.failures, self.opened_at = 0, None
def failure(self) -> None:
with self._lock:
self.failures += 1
if self.failures >= self.threshold:
self.opened_at = self.clock()
RETRYABLE = (anthropic.APIConnectionError, anthropic.APITimeoutError, anthropic.RateLimitError, anthropic.InternalServerError)
def classify(e: Exception) -> tuple[str, float | None]:
"""Return (kind, retry_after_seconds). kinds: retry | spend | permanent."""
if isinstance(e, anthropic.EnforcedSpendLimitReachedError):
return "spend", None
if isinstance(e, anthropic.APIStatusError):
retry_after = None
try:
retry_after = float(e.response.headers.get("retry-after"))
except (TypeError, ValueError):
pass
if e.status_code in (429, 500, 502, 503, 504, 529) or isinstance(e, anthropic.OverloadedError):
return "retry", retry_after
return "permanent", None
if isinstance(e, RETRYABLE):
return "retry", None
return "permanent", None
class Gateway:
def __init__(self, client: anthropic.Anthropic, model: str, fallback_model: str | None = None, max_attempts: int = 3,
max_tokens: int = 800, breaker: Breaker | None = None, sleep=time.sleep, rand=random.random, on_event=None):
self.client, self.model, self.fallback = client, model, fallback_model
self.max_attempts, self.max_tokens = max_attempts, max_tokens
self.breaker = breaker or Breaker()
self.sleep, self.rand = sleep, rand
self.on_event = on_event or (lambda **kw: None) # hook for metrics and logs (lesson 8.7)
def ask(self, prompt: str, *, system: str | None = None, model: str | None = None, max_tokens: int | None = None,
extra: dict | None = None) -> Reply:
if not self.breaker.allow():
self.on_event(kind="circuit_open")
raise CircuitOpen("The model service is temporarily paused after repeated failures.")
use_model = model or self.model
started = time.monotonic()
used_fallback = False
attempt = 0
while True:
attempt += 1
try:
reply = self._once(prompt, system, use_model, max_tokens or self.max_tokens, extra or {})
except Exception as e: # noqa: BLE001
kind, retry_after = classify(e)
self.on_event(kind="error", error=type(e).__name__, attempt=attempt, model=use_model, classified=kind)
if kind == "spend":
raise SpendLimit("The API spend limit has been reached.") from None
if kind == "permanent":
if isinstance(e, anthropic.APIStatusError):
raise BadRequest(f"The request was rejected ({e.status_code}).") from None
raise
# retryable
overloaded = isinstance(e, anthropic.OverloadedError) or getattr(e, "status_code", None) == 529
if overloaded and self.fallback and use_model != self.fallback and attempt >= 2:
use_model, used_fallback = self.fallback, True # a smaller model may have capacity
if attempt >= self.max_attempts:
self.breaker.failure()
raise Unavailable("The model service is not responding. Try again shortly.") from None
delay = retry_after if retry_after is not None else min(0.5 * 2 ** (attempt - 1), 8.0) * (0.5 + self.rand() / 2)
self.sleep(delay)
continue
self.breaker.success()
reply.attempts, reply.used_fallback = attempt, used_fallback
reply.latency_s = time.monotonic() - started
self.on_event(kind="ok", model=reply.model, request_id=reply.request_id, input_tokens=reply.input_tokens,
output_tokens=reply.output_tokens, cache_read=reply.cache_read_tokens, attempts=attempt, latency_s=reply.latency_s,
used_fallback=used_fallback)
return reply
def _once(self, prompt, system, model, max_tokens, extra) -> Reply:
kwargs = {"model": model, "max_tokens": max_tokens, "messages": [{"role": "user", "content": prompt}], **extra}
if system:
kwargs["system"] = system
msg = self.client.messages.create(**kwargs)
reason = msg.stop_reason or ""
if reason == "refusal":
raise Refused(getattr(msg, "stop_details", None))
text = "".join(b.text for b in msg.content if b.type == "text")
if reason in ("max_tokens", "model_context_window_exceeded"):
raise Truncated(f"The reply was cut off ({reason}).")
u = msg.usage
return Reply(text=text, model=msg.model, request_id=getattr(msg, "_request_id", None),
input_tokens=u.input_tokens, output_tokens=u.output_tokens,
cache_read_tokens=getattr(u, "cache_read_input_tokens", 0) or 0,
cache_write_tokens=getattr(u, "cache_creation_input_tokens", 0) or 0, stop_reason=reason)
What each part does, and how we tested it:
- Classification.
classify sorts an exception into retry, spend or permanent. A spend-limit error raises SpendLimit straight away. A 400 or 401 raises BadRequest with no retry and a message that doesn't echo the server's text. Tests: a 400 makes one call and no sleeps; a spend limit makes one call.
- Backoff with jitter. Delays double (0.5s, 1s, 2s, up to 8s) and are multiplied by a random factor, so a thousand clients that failed together don't all retry together. When the server sends
retry-after, we wait exactly that. Tests: a 429 with retry-after: 3 sleeps 3 seconds, and three 500s sleep 0.5 and 1.0 then give up, with no sleep after the last attempt.
- Fallback. After two failed attempts on an overload, the gateway switches to a smaller fallback model that may have capacity, and marks the reply
used_fallback so the metrics see it. Test: the third call goes to the fallback.
- Circuit breaker. After five failed requests in a row (each one having used up its attempts), the breaker opens and calls fail immediately for thirty seconds without touching the API, so a struggling service isn't hammered and your users get an instant "temporarily paused" instead of a long wait. After the cool-down one trial request is let through; success closes the breaker. Test: two failures open it, a third call makes no request, and after the clock moves on a trial succeeds.
- Refusals and truncation. A
refusal becomes Refused (carrying the stop_details) and a max_tokens stop becomes Truncated. They aren't errors from the network's point of view but they're not answers either.
- Events. Each attempt emits an event for metrics and logs, without the prompt.
We also ran the gateway through the real Python SDK against a local mock that returns a chosen number of 529 responses first. It saw two failures, switched to the fallback model on the third attempt and succeeded, with the request ID from the mock. A 401 from the mock was treated as permanent and not retried.
Timeouts and long requests
Set a timeout on the client (ours comes from AI_TIMEOUT_SECONDS). For long outputs, the documentation recommends streaming or the Batches API rather than a very large max_tokens on a plain request, because networks can drop idle connections. The SDK validates that non-streaming requests aren't expected to exceed a 10-minute timeout. A stream can also fail after a 200 status, so mid-stream errors need their own handling.
What users see
Map internal failures to calm, honest messages. Our service returns a 503 with Retry-After: 30 and "The assistant is temporarily unavailable. A person will follow up.", never an exception message or status text from upstream, which a test checks. For a reply feature, the best degraded mode is often "queue it for a person", which is what needs_human already means.
Idempotency
Retries are only safe if repeating the work is harmless. Drafting a reply is. Sending an email or moving money isn't, unless it's guarded with an idempotency key or a "did we already do this" check, as in lesson 6.8. Never retry a side effect blindly.
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.
During a busy afternoon the API returns 529s for ten minutes. The gateway retries with jittered backoff, switches to the smaller model after the second failure, and most requests succeed with a slightly simpler draft. A few fail all three attempts and return the calm 503, which the front end turns into "we'll email you". After five consecutive failures the breaker opens, so for thirty seconds new requests fail instantly rather than each waiting through three attempts. The fallback rate and error rate alerts fire, and the on-call person sees the cause is upstream instead of searching their own code.
Mistakes to avoid
- Retrying every error, including 400s and spend limits.
- Stacking retry layers.
- Retrying immediately with no delay or jitter.
- Showing raw upstream error messages to users.
- Retrying actions that have side effects.
- No timeouts.
Security notes
Error messages can leak internals: hostnames, headers, parts of requests. Log the error class and your own request ID, and give users a generic message. A flood of failing requests can also be a sign of abuse, so keep per-user limits in place even when the upstream is down.
Cost and speed
Failed requests that return an error aren't the issue; retries of successful-but-slow requests can double your cost, so keep the timeout generous enough for real answers. The breaker saves both money and user patience during an outage. The documentation notes that requests which error out in a batch aren't billed, but check the pricing and billing terms for regular requests rather than assuming.
Key takeaways
- Retry timeouts, 429 rate limits, 500s and 529s; don't retry 4xx errors or spend caps.
- Back off with jitter and respect
retry-after. Keep exactly one retry layer.
- A fallback model and a circuit breaker turn an outage into a mild degradation.
- Treat refusals and truncation as outcomes your code handles.
- Show users calm messages; send the details to your logs.
Lesson recap: retry the retryable, once, and degrade gracefully when it still fails.
Quick quiz
- Which 429 should you never retry?
- Why add jitter to backoff?
- What problem does a circuit breaker solve?
- Why did we set the SDK's
max_retries to zero?
- When is retrying unsafe?
Answers and explanations
- The tier spend cap (
enforced_spend_limit_reached). It has no retry-after header and fails until access resumes, so retrying wastes time.
- So many clients that failed together don't all retry at the same instant and cause another spike.
- It stops sending requests to a service that is failing repeatedly, protecting it and giving users a fast failure instead of a long wait.
- To keep one layer of retries, so attempts aren't multiplied, and so the gateway can add fallback, logging and the breaker.
- When the action has side effects, such as sending a message or moving money, unless it is protected by an idempotency key or a check that it already happened.
Official references and further reading
Related tutorials