How retries turn one LLM API error into a system-wide outage
A retry budget, circuit breaker and bulkhead, in about 100 lines of plain Python, keep a spend-cap 429 from taking down the client’s CRM API too.
In brief
- Three stacked layers that each allow up to 3 calls multiply into 27 calls to a struggling service, so retry in one place only.
- Never retry a 400 or a 429 caused by a spend cap: the first means the request needs fixing, the second is a signal to open the breaker.
- Give the LLM API and the client’s API separate pools, so that an outage in one cannot use up the other’s resources.
A 429 from the Claude API that comes from hitting a tier’s spend cap carries no retry-after header, according to the API’s error documentation, and it will keep failing until access is restored.
Say a client’s customer support agent starts receiving that error at 9 a.m. The code retries anyway, and each retry ties up another connection.
By 9:05, the client’s own CRM API, which has nothing to do with the LLM, is timing out too. The worker pool is full of LLM requests sitting in backoff. A failure in one dependency has spread through the whole system.
The scenario is hypothetical, but the risk is real for FDEs, who integrate an LLM API and a client’s internal systems at the same time. Either can go down.
This guide builds three layers of protection in about 100 lines of plain Python: a retry budget, a circuit breaker and a bulkhead, with an error classification step in front of all three. You need only Python 3.10+ and no third-party libraries.
The code has been trimmed for readability and is not production-ready.
Why do retries make an incident worse?
Microsoft calls this a retry storm: when a service is busy or unresponsive, a flood of client retries keeps it from recovering and deepens the incident. The AWS Builders’ Library reaches a similar conclusion: retrying while a system is overloaded only makes matters worse.
LLM APIs add a quota trap. OpenAI’s rate limit documentation notes that failed requests still count toward the per-minute limit, so continually resending them solves nothing. Each futile retry burns quota and pushes recovery further away.
The multiplication is what hurts. The official Claude SDK retries 2 times by default, for up to 3 calls in total.
Wrap it in a decorator that also allows up to 3 calls, then put it behind a queue worker that runs up to 3 times, and a single user request can become 3 × 3 × 3 = 27 calls to a struggling service.
That is why AWS recommends retrying at a single point in the stack.
Step 1: classify errors before thinking about retries
Not every error deserves a retry. Microsoft gives the example of 400 Bad Request: once the server has said the request is invalid, resending it unchanged is pointless. With the Claude API, a 429 caused by a spend cap is a hard error rather than a transient one.
def classify(status: int, headers: dict) -> str:
if status < 400:
return "ok"
if status == 400:
return "client_bug" # fix the request, do not retry
if status == 429 and "retry-after" not in headers:
return "hard_stop" # e.g. spend cap: open the breaker
if status == 429 or status >= 500:
return "transient" # may be retried, within limits
return "client_bug"
This is a simplified version. The rule that a 429 without retry-after is a hard error follows the Claude API’s description. For another provider’s API, or the client’s own, read the error documentation and adjust the rule.
Next, write a few unit tests that feed in each error code and check that client_bug and hard_stop never enter the retry loop.
Step 2: pick exactly one layer to retry
Microsoft advises placing retry logic only where there is enough context to understand the failing operation. Lower layers should fail fast, to avoid nested retries that cause long delays. It also points out that retries require idempotent operations.
The Claude SDK lets you set the number of retries through max_retries. If you want to control retries in the application layer, turn off the SDK’s own:
import anthropic
client = anthropic.Anthropic(max_retries=0) # the app layer handles retries
The opposite choice is also valid: keep the SDK’s retries, which use exponential backoff and respect retry-after, and wrap nothing around them. Just never let both layers retry.
To check, grep the codebase for retry, tenacity, max_retries and the queue configuration, then write down the maximum number of calls per request. It should equal the number of calls from exactly one layer.
Step 3: build a retry budget with a token bucket
Microsoft’s checklist against retry storms includes limiting both the number and total duration of retries, using exponential backoff and respecting retry-after. AWS adds another layer: limiting retries on the client itself with a token bucket.
The code below is a pared-down implementation of that idea, not an AWS formula. Each retry costs one token, and each successful request refills a fraction of one. When a dependency stays down for long, the bucket empties and the client stops retrying on its own.
import random, time
class RetryBudget:
def __init__(self, capacity=10, refill=0.1):
self.tokens, self.capacity, self.refill = capacity, capacity, refill
def spend(self) -> bool:
if self.tokens >= 1:
self.tokens -= 1
return True
return False
def on_success(self):
self.tokens = min(self.capacity, self.tokens + self.refill)
def backoff(attempt, base=0.5, cap=20.0):
return random.uniform(0, min(cap, base * 2 ** attempt)) # jitter
The values capacity=10 and refill=0.1 are illustrative; tune them to real traffic. Jitter keeps clients from all retrying at the same moment. If a response includes retry-after, wait for that long instead of the value from backoff.
Step 4: add a three-state circuit breaker
Microsoft defines a circuit breaker as a mechanism that temporarily blocks access to a remote service once failures reach a threshold, rather than continuing to retry an operation that is likely to fail. In the Closed state, the breaker counts failures.
If the number of failures within a time window passes the threshold, the breaker moves to Open and starts a timer. When the timer expires, it moves to Half-Open. In the code below, that state lets exactly one trial request through, so that a recovering service is not swamped.
class CircuitBreaker:
def __init__(self, threshold=5, window=30, open_secs=20):
self.threshold, self.window, self.open_secs = threshold, window, open_secs
self.fails, self.state, self.opened_at = [], "closed", 0.0
def allow(self) -> bool:
now = time.monotonic()
if self.state == "open" and now - self.opened_at >= self.open_secs:
self.state = "half_open"
return True # exactly one trial request
return self.state == "closed"
def record(self, kind: str):
now = time.monotonic()
if kind == "ok":
self.state, self.fails = "closed", []
return
if kind == "hard_stop" or self.state == "half_open":
self.trip(now)
return
self.fails = [t for t in self.fails if now - t < self.window] + [now]
if len(self.fails) >= self.threshold:
self.trip(now)
def trip(self, now):
self.state, self.opened_at = "open", now
Note that hard_stop opens the breaker immediately, without waiting for the threshold, because retrying a spend-cap error achieves nothing. Microsoft also makes clear that retries and breakers serve different purposes: when the breaker indicates that a fault is no longer transient, the retry logic must stop. In the call loop, check breaker.allow() before every attempt, including retries.
Step 5: give each dependency its own bulkhead
The name comes from the partitions in a ship’s hull: divide the application into pools, and when one part fails the rest can keep running. Microsoft’s example is close to an FDE’s daily work. A client that calls several services gets a separate connection pool for each, so a failing service affects only its own pool.
For AI and inference workloads, Microsoft recommends tight bulkheads because quotas and concurrency limits are set per deployment. It advises isolating by workload or by tenant.
import asyncio
POOLS = {"llm": asyncio.Semaphore(8), "customer_crm": asyncio.Semaphore(4)}
async def with_bulkhead(name, coro_fn):
sem = POOLS[name]
if sem.locked():
raise RuntimeError(f"{name} full: return 503 upstream")
async with sem:
return await coro_fn()
When a pool is full, the code fails fast and reports the error upward instead of queuing. This follows the advice in Microsoft’s throttling pattern: when an external dependency fails, reduce the requests you send, and pass the 429 or 503 signal up the stack instead of swallowing it.
Return to the 9 a.m. incident. With two separate semaphores, an LLM API outage can occupy at most 8 slots, leaving the CRM’s 4 slots free.
Step 6: test with a fake dependency
Write a fake function that always returns 503, call it 50 times through the full chain of bulkhead → breaker → classify → retry budget, and count how often it is actually invoked. Work out a baseline first: with no protection and the three retry layers described above, the maximum is 50 × 27 = 1,350 calls.
With every layer in place and the parameters used here, the count should stop at about 5, the breaker’s threshold, plus one trial call each time the breaker moves to Half-Open.
The retry budget is a second safety net: even if the breaker is misconfigured, the bucket allows at most 10 retries. If you count several dozen calls or more, some retry layer is slipping past the breaker.
Then make the fake function return a 429 without retry-after and check that the breaker opens on the very first call.
Three mistakes are common. The first is counting 400s toward the breaker, so that a bug in one client opens the circuit for everyone. The second is sharing one breaker across all tenants, so that one tenant exceeding its quota drags down the others. The third is forgetting that failed requests still count toward the rate limit.
What will the client ask on the day the API goes down?
On a real project, clients rarely ask, “Do you have a circuit breaker?” They ask why their support portal died along with the LLM API on the day it was flaky. A good answer is a diagram: each dependency has its own pool, retries live in exactly one layer, and the breaker opens on hard errors.
When reading FDE job descriptions, look for phrases such as “production reliability” or “integrate with customer systems”. On your résumé, go beyond “implemented a circuit breaker”. Give before-and-after numbers, such as “cut maximum calls per request from 27 to 3”, because an interviewer can dig into those.
The next time a client’s API goes down, your system does not need to try harder. It needs to know when to stop.
Was this article useful?
Thanks for the feedback!
8 sources
- Circuit Breaker Pattern - Azure Architecture Center | Microsoft Learn · 2025-02-05
- Bulkhead Pattern - Azure Architecture Center | Microsoft Learn · 2026-03-19
- Retry Storm Antipattern - Azure Architecture Center | Microsoft Learn · 2025-07-16
- Retry pattern - Azure Architecture Center | Microsoft Learn · 2024-07-18
- Throttling Pattern - Azure Architecture Center | Microsoft Learn · 2026-05-29
- Timeouts, retries and backoff with jitter · 2026-06-12
- Claude API errors
- Rate limits | OpenAI API