Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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

Four error classes, four moves 429 rate_limit_error 529 overloaded_error 400 invalid_request_error timeout timeout_error wait for retry-after, then retry back off, then a fallback model never retry: fix the request, keep the request id retry as a stream, or send as a batch
Read the type in the error body, then pick the move. The fallback model is our own policy, not an API rule.

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 with max_retries=0.
  • Raising max_retries to 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 type from the body, or catch the SDK's typed exception.
  • Catching APIConnectionError before APITimeoutError. 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 for loop 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 classWhat to do
timeout10 minutes by default; seconds in Python, milliseconds in TypeScript
max_retries2 by default; retries connection errors, timeouts, 408, 409, 429, 5xx
with_optionsOverride timeout or retries for one call
AsyncAsyncAnthropic, same options and errors, gather
PaginationA plain for (or async for) loop
429Wait for retry-after, then retry
529Back off, then a fallback model (your policy)
400Never retry; fix the request, keep the request id
TimeoutStream 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?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 14 of 66

Previous
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Next post
Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay

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.

On this page

  • Set it once, override it per request
  • What the caller sees
  • The async client and pagination
  • One loop for four failures
  • A courier at four doors
  • retry_policy.py: one move per class
  • Both wrappers, five tickets
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.