Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
What you will learn
- Set timeout and max_retries on the Anthropic client and override them per request with with_options
- Predict which failures the SDK retries by itself and which reach your code at once
- Write a retry policy that reads the error type: honour retry-after, back off then fall back on overloaded, never retry a 400, stream a long job that timed out
- Page through a list endpoint with a plain for loop or page by page
Before you start
- Claude client SDKs wrap one REST API
- Python try/except
A SupportDesk night job talks to Claude all day. Think of it as phoning the same supplier, over and over. Four things decide how that goes: how long you stay on hold (the timeout), how many times you redial (max retries), calling many suppliers at once (the async client), and a catalogue that comes one page at a time (pagination).
The SDK client already has all four. The first half of this article uses each one and shows what the caller really gets back. The second half takes a retry wrapper somebody wrote, which treats every failure the same, and repairs it so each error class gets its own move.
Both projects run the real Anthropic SDK against a stand-in API (an httpx mock transport) that sends scripted replies and scripted errors. Replies start with test model reply; the request ids, the retry-after values and the long-job size are made-up demo values.
Set it once, override it per request
On the client you set timeout and max_retries once, and every request uses them. The defaults are ten minutes and two retries. For one call, with_options changes them, and that value wins for that call only.
The SDK retries by itself, with a short backoff, on connection errors, timeouts, 408, 409, 429 and anything 500 or higher. Everything else raises at once: a bad key or a bad request won't get better if you send it again.
"""The sync client: set the options once, then handle every failure by its type."""
import anthropic
from stand_in import MODEL, make_client
client = make_client(timeout=20.0, max_retries=3)
def ask(ticket, **options):
"""One call. Per-request options go through with_options."""
msgs = [{"role": "user", "content": ticket["text"]}]
try:
r = client.with_options(**options).messages.create(
model=MODEL, max_tokens=256, messages=msgs)
return "ok: " + r.content[0].text
except anthropic.APITimeoutError:
return "APITimeoutError: queue it for later"
except anthropic.APIConnectionError:
return "APIConnectionError: check the network"
except anthropic.RateLimitError:
return "RateLimitError: slow down"
except anthropic.AuthenticationError:
return "AuthenticationError: fix the key"
except anthropic.BadRequestError:
return "BadRequestError: fix the request"
except anthropic.APIStatusError as err:
return f"APIStatusError {err.status_code}: log and alert"
The order of the except lines matters. APITimeoutError comes first because a timeout is also a connection error. RateLimitError here means a 429 that is still there after the SDK's retries. APIStatusError at the end catches any other status.
What the caller sees
The stand-in scripts each ticket: T-202 gets one 429 with retry-after: 1 and then works, T-203 never answers in time (sent with a 5-second timeout and one retry), T-204 has a bad key, T-205 is a malformed request, T-206 is rate limited every time (sent with one retry).
default client timeout 600s | max_retries 2
tuned client timeout 20.0s | max_retries 3
sync client
T-201 ok: test model reply: T-201 answered. | attempts 1
T-202 ok: test model reply: T-202 answered. | attempts 2
T-203 APITimeoutError: queue it for later | attempts 2
T-203 per-request timeout on the wire: 5.0s
T-204 AuthenticationError: fix the key | attempts 1
T-205 BadRequestError: fix the request | attempts 1
T-206 RateLimitError: slow down | attempts 2
- T-202: two attempts, and the caller saw
ok. A 429 that clears never reaches your code. - T-203: one retry means two attempts, then a timeout error. The 5-second override really went on the wire.
- T-204 and T-205: one attempt each. A 401 or 400 is never retried.
- T-206: after its one retry, the rate limit error reaches your code.
The async client and pagination
AsyncAnthropic takes the same two options, you await the same call, and the error classes are the same. APIError is the base class, so one except line catches them all. gather runs the tickets together.
"""The async client: same options, same errors, many tickets at once."""
import asyncio
import anthropic
from stand_in import MODEL, make_async_client
client = make_async_client(timeout=20.0, max_retries=3)
async def ask(ticket):
msgs = [{"role": "user", "content": ticket["text"]}]
try:
r = await client.messages.create(
model=MODEL, max_tokens=256, messages=msgs)
return "ok: " + r.content[0].text
except anthropic.APIError as err:
return type(err).__name__
async def ask_all(tickets):
return await asyncio.gather(*(ask(t) for t in tickets))
List endpoints, such as the list of message batches, come back a page at a time. A plain for loop walks every page; the SDK fetches the next page when the loop needs it. Or you hold one page and ask for the next yourself.
"""Pagination: let the SDK fetch the pages, or hold one page at a time."""
PAGE = 2
def every_batch(client):
"""Auto-pagination: a plain for loop walks all pages."""
return [b.id for b in client.messages.batches.list(limit=PAGE)]
def by_page(client):
"""Manual paging: one page, then ask for the next one."""
page = client.messages.batches.list(limit=PAGE)
pages = [[b.id for b in page.data]]
while page.has_next_page():
page = page.get_next_page()
pages.append([b.id for b in page.data])
return pages
async def every_batch_async(client):
return [b.id async for b in client.messages.batches.list(limit=PAGE)]
async client
T-201 ok: test model reply: T-201 answered. | attempts 1
T-202 ok: test model reply: T-202 answered. | attempts 2
T-207 ok: test model reply: T-207 answered. | attempts 1
list batches
auto: 5 batches, 3 requests
page 1: msgbatch_01, msgbatch_02
page 2: msgbatch_03, msgbatch_04
page 3: msgbatch_05
async: 5 batches, 3 requests
Five batches, two per page, three requests. The first request has no cursor; the next ones start after the last id seen. The cursor moves for you.
In TypeScript the names change a little: timeout is in milliseconds, maxRetries is camel case, per-request options are the second argument to create, errors are checked with instanceof (a timeout is Anthropic.APIConnectionTimeoutError), and for await pages a list for you.
const client = new Anthropic({
apiKey: "test-key",
timeout: 20 * 1000,
maxRetries: 3,
fetch: mockFetch,
});
One loop for four failures
Now a different slice of SupportDesk, RetryGuard. Five tickets go through it and four of them hit an error:
- T-301 gets a 429, a rate limit, with
retry-after: 3. - T-302 gets a 529: the primary model is overloaded.
- T-303 gets a 400: the request ends with a prefilled assistant message, which the model doesn't accept.
- T-304, a long report with
max_tokens=16000, gets a timeout when it isn't streamed.
The wrapper we found treats them all alike: any error, wait one second, send the same request again, three times.
"""The wrapper we found: any error, wait a second, send it again."""
import time
import anthropic
from errors import error_type
from stand_in import MODEL
def handle(ticket, client, sleep=time.sleep):
req = dict(max_tokens=ticket["max_tokens"],
messages=ticket["messages"])
kind = "ok"
for attempt in range(3):
try:
client.messages.create(model=MODEL, **req)
return {"class": kind, "action": "delivered"}
except anthropic.APIStatusError as err:
kind = error_type(err)
sleep(1)
return {"class": kind, "action": "gave up"}
Four defects: every error gets the same move, the wait is a fixed second whatever retry-after said, the same model and request go out on every try, and no request id is kept when it gives up.
A courier at four doors
Picture a courier. A sign says back in a while: he comes back when the sign says (rate limit: honour retry-after). The shop is too busy: he tries again later, then tries another shop (overloaded: back off, then a fallback model). The form is filled in wrong: sending it again won't help (invalid request: never retry). The parcel is too big for the van: it goes in pieces (timeout: stream the job, or send it as a batch).
Three more facts shape the policy. A 429 tells you how long to wait in its retry-after header. The SDK already retries (twice by default, honouring retry-after too), so if you stack your own retries on top, the tries multiply: RetryGuard sets max_retries=0 so one layer owns every decision. And every response carries a request id: log it, and send it to support.
retry_policy.py: one move per class
The error type comes from the response body, never from the message text:
"""Read the error type from the response body. Every API error carries one."""
def error_type(err):
body = err.body if isinstance(err.body, dict) else {}
return body.get("error", {}).get("type", body.get("type", "unknown"))
The repaired wrapper:
"""The repaired wrapper: every error class gets its own move."""
import time
import anthropic
from errors import error_type
from stand_in import MODEL, FALLBACK
MAX_TRIES = 4
def send(client, ticket, model, stream):
args = dict(model=model, max_tokens=ticket["max_tokens"],
messages=ticket["messages"])
if stream:
with client.messages.stream(**args) as s:
return s.get_final_message()
return client.messages.create(**args)
def retry_after(err):
return float(err.response.headers.get("retry-after", 2))
def handle(ticket, client, sleep=time.sleep):
model, stream, kind, trail = MODEL, False, "ok", []
for attempt in range(1, MAX_TRIES + 1):
try:
send(client, ticket, model, stream)
done = ", ".join(trail + ["delivered"])
return {"class": kind, "action": done}
except anthropic.APIStatusError as err:
kind = error_type(err)
if kind == "invalid_request_error":
note = f"no retry, fix it | {err.request_id}"
return {"class": kind, "action": note}
if kind == "rate_limit_error":
wait = retry_after(err)
trail.append(f"wait {wait:g}s (retry-after)")
elif kind == "timeout_error":
wait, stream = 0, True
trail.append("retried as a stream")
else:
wait = 2 ** attempt
trail.append(f"wait {wait}s")
if attempt >= 2:
model = FALLBACK
trail.append("fallback model")
sleep(wait)
return {"class": kind, "action": f"gave up | {err.request_id}"}
A timeout is retried as a stream, and get_final_message() still gives the whole message at the end. Overloaded waits longer each time and, after two tries, switches to the fallback model (claude-haiku-5-5 in the project).
Both wrappers, five tickets
The waits move a virtual clock, so nothing really sleeps. After both runs, the script fixes T-303 (drops the prefilled assistant message) and sends it again.
naive wrapper
T-301 rate_limit_error calls 3 | gave up
T-302 overloaded_error calls 3 | gave up
T-303 invalid_request_error calls 3 | gave up
T-304 timeout_error calls 3 | gave up
T-305 ok calls 1 | delivered
policy wrapper
T-301 rate_limit_error calls 2 | wait 3s (retry-after), delivered
T-302 overloaded_error calls 3 | wait 2s, wait 4s, fallback model, delivered
T-303 invalid_request_error calls 1 | no retry, fix it | req_test_0006
T-304 timeout_error calls 2 | retried as a stream, delivered
T-305 ok calls 1 | delivered
T-303 fixed request: delivered
calls: naive 13 | policy 9
delivered: naive 1 | policy 4
The old wrapper sent the bad request three times, stayed on the busy model, and waited one second when the header asked for three. Thirteen calls, one ticket delivered. The policy wrapper made nine calls and delivered four, and the fifth was stopped on purpose with its request id. Once fixed, T-303 is delivered too. The repair isn't more retries. It is the right move for each error.
Common mistakes
- Writing your own retry loop around every call while the SDK also retries. The tries multiply. Keep one owner: either the SDK's
max_retries, or your policy withmax_retries=0. - Raising
max_retriesto fix a 401 or 400. Those are never retried, and sending them again can't succeed. - A fixed sleep after a 429. Read
retry-after. - Staying on an overloaded model forever, or sending everything to the fallback. Back off first, then fall back; and never use a fallback to hide a request that needs fixing.
- Matching on the error message text. Read the
typefrom the body, or catch the SDK's typed exception. - Catching
APIConnectionErrorbeforeAPITimeoutError. The timeout is a connection error, so the specific class must come first. - Dropping the request id. Keep it with every failure you report.
- Fetching list pages by hand when a
forloop pages for you.
For the wider picture of failures, including replies that come back 200 but unusable, see Debugging a Claude app: three error types. The generic backoff pattern with tenacity is in Streaming and error handling for LLM calls.
Quick recap
| Setting or class | What to do |
|---|---|
timeout | 10 minutes by default; seconds in Python, milliseconds in TypeScript |
max_retries | 2 by default; retries connection errors, timeouts, 408, 409, 429, 5xx |
with_options | Override timeout or retries for one call |
| Async | AsyncAnthropic, same options and errors, gather |
| Pagination | A plain for (or async for) loop |
| 429 | Wait for retry-after, then retry |
| 529 | Back off, then a fallback model (your policy) |
| 400 | Never retry; fix the request, keep the request id |
| Timeout | Stream the long job, or batch it |
Try it yourself
In the RetryGuard project, change make_client() to leave the SDK's default max_retries in place and run both wrappers again. Count the calls the stand-in logs for T-302. How many tries did the two layers make together?
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
Read one streamed Claude reply event by event, relay its text deltas to a browser over a WebSocket, then fix four stream handlers from their event logs: the terminal event, tool arguments, stop reasons and the real token count.