Module 4 · Reliability & safety

Retries, timeouts, budgets and circuit breakers

6 min read

A multi-agent system depends on a remote API called dozens of times per run. Statistically, incidents will happen: temporary overload, network drop, rate limit hit. The question isn't whether but how your system reacts. This lesson covers the four resilience mechanisms: retries, timeouts, budgets and circuit breakers.

Classify errors before handling them

First rule: not every error should be retried.

ErrorSDK classRetry?
Rate limit (429)anthropic.RateLimitErrorYes, after a delay
Server error (5xx)anthropic.InternalServerErrorYes
Network drop or timeoutanthropic.APIConnectionError (including APITimeoutError)Yes
Invalid request (400)anthropic.BadRequestErrorNo: fix the request
Model refusalstop_reason == "refusal"Not as-is (see below)
Bug in your codeValueError, KeyError…No

Retrying an invalid request only multiplies failure and cost. Handle errors from most specific to most general, with the SDK's typed classes — never by parsing the error message text:

try:
    text = complete(SYSTEM_WRITER, prompt)
except anthropic.RateLimitError:
    ...  # wait, reduce parallelism
except anthropic.BadRequestError as exc:
    ...  # request bug: log, don't retry
except anthropic.APIStatusError as exc:
    ...  # other HTTP error: exc.status_code
except anthropic.APIConnectionError:
    ...  # network: retryable

Retries: two layers to coordinate

Layer 1: the SDK

The Anthropic client automatically retries transient errors (408, 409, 429, 5xx, connection errors) — twice by default, with increasing delays. Configurable when creating the client:

client = anthropic.Anthropic(max_retries=3, timeout=120.0)   # timeout in seconds

Layer 2: the graph node

LangGraph lets you attach a retry policy to a node — useful when the failure comes from a whole step (an external tool, a validation that fails transiently):

from langgraph.types import RetryPolicy


def retryable(exc: Exception) -> bool:
    return isinstance(exc, (anthropic.RateLimitError, anthropic.InternalServerError, anthropic.APIConnectionError))


builder.add_node(
    "researcher",
    researcher,
    retry_policy=RetryPolicy(max_attempts=3, initial_interval=1.0, backoff_factor=2.0, retry_on=retryable),
)

Tested with a simulated outage: two connection errors followed by a success give three attempts and one result, while a ValueError (a logic error) is attempted only once.

Beware of multiplication

Layers multiply: 3 node attempts × 3 SDK attempts = up to 9 calls for a single step. During a real outage, aggressive retries make the overload worse. Rules: exponential backoff with jitter (enabled by default in RetryPolicy), a single aggressive layer, and a global ceiling (the budget).

Timeouts

A call that never answers is worse than a call that fails: it silently blocks the whole chain.

  • At the client level: timeout= on the Anthropic client (in seconds in Python).
  • At the node level: add_node(..., timeout=...) caps each attempt and raises NodeTimeoutError, which the retry policy can handle.

Important constraint: per-node timeouts only work with async nodes (async def). LangGraph refuses to compile a graph that puts a timeout on a synchronous node, because synchronous Python code can't be cleanly interrupted mid-execution:

async def researcher(task: ResearchTask) -> dict:
    ...


builder.add_node("researcher", researcher, timeout=60)   # async node: timeout applied

For a synchronous node, rely on the HTTP client's timeout.

Refusals and server-side fallback

A model can decline a request (stop_reason == "refusal"), sometimes wrongly on legitimate but sensitive content (cybersecurity, health…). Retrying as-is is pointless. The API offers a server-side fallback: on refusal, the same request is automatically replayed on a suitable fallback model. Atlas enables it in complete():

def _fallback_options(model: str) -> dict:
    # Server-side fallback on refusal: available on Opus / Sonnet / Fable, not on Haiku.
    if model.startswith("claude-haiku"):
        return {}
    return {"betas": ["server-side-fallback-2026-07-01"], "fallbacks": "default"}

If the final response is still a refusal, the whole chain declined: Atlas then raises an explicit RefusalError, to be handled as a business outcome (inform the user), not as an outage.

Budgets and iteration limits

Retries protect against outages; budgets protect against runaways — an agent looping, a critic never satisfied, a question producing 40 sub-questions.

GuardrailWhereProtects against
max_stepsAgent loopReAct agent going in circles
MAX_REVISIONS, MAX_HANDOFFSBusiness logicLoops between agents
recursion_limitLangGraph configGraph runaway (safety net)
Budget (calls, cost)@guarded on each nodeExcessive spend per run

Always prefer a business limit that produces a degraded but useful result ("the note goes to a human after two revisions") over a technical limit that stops abruptly.

The circuit breaker

When a dependency is down for an extended period, continuing to call it wastes time and makes things worse. The circuit breaker cuts calls after a series of failures, then periodically tests for recovery:

import time


class CircuitBreaker:
    def __init__(self, threshold: int = 5, cooldown: float = 60.0):
        self.threshold, self.cooldown = threshold, cooldown
        self.failures, self.opened_at = 0, 0.0

    def call(self, fn, *args, **kwargs):
        if self.failures >= self.threshold:
            if time.monotonic() - self.opened_at < self.cooldown:
                raise RuntimeError("Circuit open: service unavailable, try again later.")
            self.failures = self.threshold - 1           # half-open: one test attempt
        try:
            result = fn(*args, **kwargs)
        except Exception:
            self.failures += 1
            if self.failures >= self.threshold:
                self.opened_at = time.monotonic()
            raise
        self.failures = 0                                 # success: circuit closed again
        return result


search_breaker = CircuitBreaker(threshold=5, cooldown=60)
hits = search_breaker.call(knowledge.search, query, 3)

When the circuit is open, the tool immediately returns an actionable error to the model ("search unavailable, continue with the information you have") rather than making it wait in vain.

Key takeaways

  • Classify errors: only retry transient ones (429, 5xx, network), using the SDK's typed classes.
  • The SDK already retries (twice by default); a per-node retry policy adds to it — watch the multiplication.
  • Timeouts: on the client, and per node only for async nodes.
  • A refusal isn't an outage: server-side fallback, then an explicit business outcome.
  • Budgets and business limits against runaways; circuit breaker against extended outages.

Hands-on

  1. Add a RetryPolicy to Atlas's researcher node and a test simulating two connection errors.
  2. Convert researcher into an async node and give it a 60-second timeout.
  3. Wrap knowledge.search in a CircuitBreaker and check that after 5 failures, the next call fails immediately.

Resources