Retries That Don't Make It Worse: LLM Clients
Every LLM call can fail in more ways than an ordinary HTTP request. The provider can throttle you with a 429, declare itself overloaded with a 529, time out before the response starts, or start a stream and then go silent. Retrying is the obvious answer, and a retry policy written in five minutes can turn a provider's bad minute into your own outage.
This post writes that policy carefully. It combines the classic work on backoff and deadlines with what we learned running LLM services in production, and it tests each claim. Simulations of up to 200 clients against a rate-limited provider show how retry strategies behave. A local fake of the Messages API tests a complete client, built on the official Anthropic Python SDK, against throttling, overload, bad requests, a spend cap, error events mid-stream, and streams that go silent, trickle or end early. Four of those tests surprised me, and each changed the client.
In short
- Retry at one layer only. Three layers that each try three times turn one request into 27 calls on a provider that is already struggling.
- Always jitter. Without it, simulated clients retried in synchronised waves and the slowest finished at 33 seconds against 14 with full jitter. A higher backoff cap cut load in a long storm by 38 per cent, at the price of a longer tail.
- Bound every attempt by the caller's deadline and give streams an idle timeout. A silent stream is otherwise noticed only when the whole request budget runs out, and a read timeout alone does not stop a stream that keeps trickling.
- Check
stop_reason. With anthropic 2.16.0, a stream cut off after its first event returned an empty message withstop_reason=None, and no exception.
What can go wrong, and what to do about it
| Failure | Signal | Retry? | How |
|---|---|---|---|
| Rate limited | 429 rate_limit_error, often with retry-after | Yes | Wait at least retry-after, with jitter; same growth as for errors, with a higher cap |
| Overloaded | 529 overloaded_error, 503 | Yes | Throttling backoff; reduce concurrency, as in the previous post |
| Server error | 500 api_error | If x-should-retry is not false | Shorter backoff |
| Timed out before the response | Connect or read timeout, 504 | Yes, within the deadline | Stream long requests so the connection is never idle for long |
| Stream stalls or drops | No bytes for a while; a transport error mid-body | Yes | An idle timeout per read; catch the transport's own exceptions |
| Error inside a stream | An error event after the 200, such as overloaded_error | If its type is retryable | Classify by the event's type; the status code is still 200 |
| Stream ends early | No message_stop; stop_reason is None | Yes | Check stop_reason before trusting the message |
| Bad request | 400, 401, 403, 404, 413 | Never | Fail at once; it will fail the same way every time |
| Spend cap reached | 429 rate_limit_error with enforced_spend_, no retry-after | Never | Fail at once; it lasts until the cap resets |
Answer truncated by max_tokens | stop_reason is max_tokens | Not as is | Raise the budget; adaptive thinking and the answer share it |
Three rows need a word. The 500 row follows Anthropic's documentation: "Don't retry if the response's x-should-retry header is false". The spend cap is a 429 with the same error type as a rate limit, but the rate-limit documentation says it carries no retry-after and that retrying fails. The last row comes from production: on Claude, thinking and the answer share max_tokens, so a structured call with a tight budget and adaptive thinking could spend the budget thinking and end truncated. Retrying that unchanged fails again, so we now add headroom for thinking above the answer's own budget.
Rule one: retry at one layer
A retry looks free to the caller. To an overloaded service it is more load at the worst time, and when several layers each retry, the attempts multiply:
Google's SRE book gives the canonical example in its chapter on cascading failures: "a single user action may create 64 attempts (4^3) on the database". Its chapter on handling overload gives the remedy: "requests should only be retried at the layer immediately above the layer that is rejecting them", otherwise "we'd have a combinatorial explosion". The same chapter limits retries two ways: "a per-request retry budget of up to three attempts", and a per-client budget where "a request will only be retried as long as this ratio is below 10%". gRPC's retry design builds the second idea in as a token bucket that stops retries when too many recent calls have failed.
For LLM calls inside a workflow engine, this decides where retries live. We turned the SDK's retries off and retried in one place, in process, bounded by the activity's deadline. Errors the workflow should see, like a retry-after longer than a minute, go back to it instead of being slept on, so no worker slot sits idle. Deterministic failures, such as an input that can never be mapped, go on a non-retryable list. We once found one missing from it: it was retried up to the attempt cap and failed identically each time.
Rule two: always jitter
Marc Brooker's 2015 post on exponential backoff and jitter is still the reference. It compares backoff without jitter with three jittered variants: full jitter, a random wait between zero and the exponential ceiling; equal jitter, half fixed and half random; and decorrelated jitter, where each wait is random between a base and three times the previous one. Its verdict: "the no-jitter exponential backoff approach is the clear loser"; of the jittered ones, "Equal Jitter" is the loser; and between decorrelated and full jitter, "the Full Jitter approach uses less work, but slightly more time".
To see this with an LLM-shaped workload, I simulated 200 clients, each needing one successful call, arriving within a second at a provider that allows 20 requests per second through a token bucket. A sustained storm was the second scenario: capacity at 2 per second for the first minute. Each number is the mean of five seeds.
| Strategy | Burst: calls per client | Burst: last client done | Storm: calls per client | Storm: 95th percentile |
|---|---|---|---|---|
| Retry at once, no backoff | 716.9 | 9.2 s | 7,224 | 62.7 s |
| Exponential, no jitter, cap 8 s | 4.2 | 32.7 s | 8.9 | 80.6 s |
| SDK default: cap 8 s, minus up to 25% | 3.9 | 15.7 s | 9.0 | 64.9 s |
| Full jitter, cap 8 s | 4.3 | 13.8 s | 12.8 | 65.0 s |
| Full jitter, cap 30 s | 4.3 | 22.8 s | 7.9 | 76.8 s |
| Decorrelated jitter, cap 30 s | 3.2 | 15.0 s | 8.2 | 80.6 s |
retry-after only, +10% | 73.0 | 9.2 s | 79.7 | 62.3 s |
retry-after as a floor, full jitter 30 s | 4.3 | 18.2 s | 7.9 | 77.1 s |
The results support Brooker and add some detail:
- No jitter is worst for the tail. Clients rejected together retried together, in waves the provider rejected again; the last finished at 32.7 seconds against 13.8 with full jitter.
- Decorrelated jitter made the fewest calls (3.2 per client in the burst) and the lowest peaks; full jitter with an 8 second cap had a similar tail.
- The cap is a real trade. In the minute-long storm, full jitter capped at 30 seconds sent 7.9 calls per client against 12.8 with an 8 second cap, 38 per cent less load on a provider that was already overloaded, but its 95th percentile rose from 65 to 77 seconds.
- Retrying at once without backoff finished fast here, because my simulated provider charges nothing for a rejection. It sent 717 calls per client in the burst and 7,224 in the storm. A real provider pays for each one, and the next post's metrics would show it.
Our client's throttling backoff once stopped at 8 seconds and removed at most a quarter of each wait. During a long storm every worker retried every 6 to 8 seconds, and workers throttled together stayed in step. We switched throttling to full jitter with a 30 second cap and kept 8 seconds for server errors. The Anthropic Python SDK's default is the scheme we moved away from: in version 2.16.0 it waits min(0.5 × 2^n, 8) seconds multiplied by 1 - 0.25 × random(), while the comment beside that line says "plus-or-minus half a second". That is reasonable for two retries and not built for long storms.
Rule three: treat retry-after as a floor
HTTP defines Retry-After as "either an HTTP-date or a number of seconds to delay", and Anthropic's rate-limit documentation is careful about what it promises: "Earlier retries might fail. Not every 429 carries it". Honouring it is right, but honouring only it can backfire. In the simulation, rejected clients were told similar short waits; those that obeyed the hint with 10 per cent of spread returned close together and made 73 calls each. Taking the larger of that hint and the jittered backoff brought it down to 4.3 calls per client. The SDK does what the header says: in version 2.16.0 a positive retry-after-ms or retry-after sets the wait exactly, without jitter, and an HTTP-date is parsed too. A hand-written client should at least fall back to backoff when the header is not a number.
Rule four: every attempt fits the deadline
Timeouts are how a client admits it has waited long enough. gRPC's guide puts the principle bluntly: "By default, gRPC does not set a deadline", and you should set one. The SRE book adds propagation: "servers should employ deadline propagation" rather than invent a fresh deadline at each hop.
The SDK's defaults fit this badly. It times a request out after 10 minutes and retries twice, so a request that hangs before its first byte can hold a worker for up to half an hour. Inside a workflow activity with its own deadline, that is worse than useless: when the activity times out, the engine may retry it while the old call is still running and billing.
A deadline-aware client gives each attempt the smaller of its normal timeout and the time left before the caller's deadline, minus a margin, and skips a retry whose wait would not fit. I checked its effect with 20,000 simulated calls from an invented latency distribution, 10 per cent of which hang, against a 90 second deadline. It did not raise the success rate: 95.3 per cent against 96.8 for fixed 60 second attempts, because the reserved margin costs a few late successes. What it removed was orphaned work. In 3.2 per cent of the fixed-timeout runs, a call was still running after the caller's deadline, for 28 seconds on average; the deadline-aware client left none, and it failed with an error that says why.
Rule five: streams need an idle timeout
Anthropic's documentation recommends streaming, or the Batches API, for long requests, partly because "some networks might drop idle connections after a variable period of time". Streaming changes what a timeout means. A whole-request timeout notices a silent stream only when the whole budget runs out. In production we had a half-open connection, sending nothing, that was noticed only after the request's full budget of half an hour. A timeout per read notices silence one idle interval later. It bounds each read, not the attempt, so the client also checks the deadline between events: a stream that keeps trickling must not outlive it either.
Streaming has a second benefit for workers: cancellation. A non-streamed reply sends its headers only when generation is complete, so a cancelled job can leave a thread blocked on the request until it finishes or times out. We stream every call a cancellation can reach, so closing the stream ends the request.
A client that follows the rules
Here is the whole policy in about 80 lines. It uses the SDK for everything except retries, which it owns, so create the client with max_retries=0. The figure shows one pass through the retry loop.
"""One retry layer for Claude calls: classified errors, full jitter, retry-after as a floor, a deadline."""
import random
import time
import anthropic
try: # newer SDKs ship their own fork of httpx; older ones use httpx itself
import httpx2 as http
except ImportError:
import httpx as http
RETRYABLE = {408, 409, 429, 500, 502, 503, 504, 529}
THROTTLED = {429, 503, 529}
STREAM_ERRORS = {"overloaded_error": 529, "api_error": 500} # error events sent after the stream's 200
NEVER = {"enforced_spend_limit_reached"} # a 429 that lasts until the spend cap resets
class IncompleteStream(ConnectionError):
"""The stream ended before message_stop: the SDK returns a message with stop_reason None."""
class DeadlineExceeded(TimeoutError):
"""Raised, by name, when the next attempt could not finish before the caller's deadline."""
def backoff(attempt: int, throttled: bool) -> float:
"""Full jitter: anywhere between 0 and an exponential ceiling, capped higher for throttling."""
cap = 30.0 if throttled else 8.0
return random.uniform(0, min(cap, 0.5 * 2 ** attempt))
def status(e: anthropic.APIStatusError) -> int:
"""The HTTP status; for an error event inside a stream, which arrives after a 200, the status its type means."""
if e.status_code == 200:
return STREAM_ERRORS.get(getattr(e, "type", None), 400)
return e.status_code
def retry_after(response) -> float | None:
try:
value = float(response.headers["retry-after"])
except (KeyError, ValueError): # absent, or an HTTP-date: fall back to backoff
return None
return value if value > 0 else None
def create(client: anthropic.Anthropic, deadline: float, *, idle_timeout: float = 60.0,
margin: float = 5.0, min_attempt: float = 10.0, **params) -> anthropic.types.Message:
"""Stream one request until `deadline` (a time.monotonic() value). The client must have max_retries=0."""
attempt = 0
while True:
left = deadline - time.monotonic() - margin
if left < min_attempt:
raise DeadlineExceeded(f"{attempt} attempts made, {max(left, 0):.1f} s left")
# Each read waits at most idle_timeout, so a silent stream fails fast; the loop below
# checks the deadline between events, so a slow trickle cannot outlive it either.
timeout = anthropic.Timeout(left, connect=5.0, read=min(idle_timeout, left)) # the SDK's own type
try:
with client.messages.stream(**params, timeout=timeout) as stream:
for _ in stream:
if time.monotonic() > deadline - margin:
raise DeadlineExceeded(f"attempt {attempt + 1} still streaming at the deadline")
message = stream.get_final_message()
if message.stop_reason is None: # cut short without an exception
raise IncompleteStream("stream closed before message_stop")
return message
except anthropic.APIStatusError as e:
code, hint = status(e), e.response.headers.get("x-should-retry")
never = hint == "false" or getattr(e, "error_code", None) in NEVER
if never or (hint != "true" and code not in RETRYABLE):
raise # 400, 401, 403, 404, 413, a spend cap: retrying cannot help
wait = backoff(attempt, code in THROTTLED)
ra = retry_after(e.response)
if ra is not None:
wait = max(wait, ra * (1 + 0.1 * random.random())) # the server's floor, spread a little
except (anthropic.APIConnectionError, http.TransportError, IncompleteStream):
# The SDK maps errors before the response starts; a stream that stalls or drops mid-body
# raises the transport's own ReadTimeout or RemoteProtocolError, so catch both.
wait = backoff(attempt, throttled=False)
attempt += 1
if time.monotonic() + wait > deadline - margin - min_attempt:
raise DeadlineExceeded(f"{attempt} attempts made; the next wait of {wait:.1f} s would not fit")
time.sleep(wait)
I ran it against a local fake of the Messages API that scripts each failure and otherwise streams a valid reply:
| Scenario | Requests sent | Time | Outcome |
|---|---|---|---|
429 with retry-after: 1, then success | 2 | 1.2 s | Correct reply |
| 529 twice, then success | 3 | 0.8 s | Correct reply |
| 400 invalid request | 1 | 0.0 s | BadRequestError, not retried |
500 with x-should-retry: false | 1 | 0.0 s | InternalServerError, not retried |
| Headers and one event, then 30 s of silence (idle timeout 2 s, deadline 60 s) | 9 | 44.6 s | DeadlineExceeded: the next 4.9 s wait would not fit |
| 529 on every attempt (deadline 20 s) | 5 | 4.9 s | DeadlineExceeded: the next 4.8 s wait would not fit |
| Stream closed after its first event, then success | 2 | 0.2 s | Correct reply |
An overloaded_error event after the stream's 200, then success | 2 | 0.2 s | Correct reply |
| One small delta a second for 40 s (idle timeout 2 s, deadline 25 s) | 1 | 20.1 s | DeadlineExceeded while still streaming, at the deadline minus the margin |
| 429 for a reached spend cap, on every attempt | 1 | 0.0 s | EnforcedSpendLimit, not retried |
| The same stall, with the SDK's defaults | 1 | 30.0 s | An empty message with stop_reason=None, no exception |
"Would not fit" applies the rule in the code above: a retry goes ahead only if its wait still leaves the 5 s margin and a 10 s minimum attempt before the deadline.
Four results changed the code. The first two showed up in the first test run. The last two came from a later review of the code, and the fake reproduced each before it was fixed.
- A stalled stream raised the wrong exception. When the stream stalled after its first event, the read timeout surfaced as the HTTP library's own
ReadTimeout, not the SDK'sAPITimeoutError. The SDK maps errors that happen before the response starts, and its documentation says "the SDK doesn't retry an error in a stream". A client that catches only SDK exceptions misses the hung stream. - A cut stream raised nothing. A stream the server closed after its first event made
get_final_message()return a message with empty content andstop_reason=None. Code that readscontent[0]crashes, and code that iterates over the content treats an empty answer as a real one. The client now raisesIncompleteStreamand retries. - A slow stream outlived the deadline. One small delta a second, each read well inside the idle timeout, ran 40 seconds against a 25 second deadline. The client now checks the deadline between events and stopped the same stream at 20 seconds, the deadline minus its margin.
- An error event was not retried. An
overloaded_errorevent inside a stream reached the client as anAPIStatusErrorwith status code 200, outside the retryable set, so it was raised. The client now classifies such an event by its type.
The SDK's defaults, side by side
The table lists what anthropic 2.16.0 does with its defaults (from _constants.py and _base_client.py) next to the client above. The stream row for the SDK is the "stall, SDK defaults" run: one request, 30 seconds, an empty message.
| Behaviour | SDK defaults | This client |
|---|---|---|
| Request timeout | 10 minutes, connect 5 s | Time left before the deadline, minus a margin; connect 5 s |
| Stream silence | Waits up to the 10-minute timeout | Idle timeout per read, 60 s by default |
| Attempts | 2 retries, then raise | As many as fit before the deadline |
| Backoff | min(0.5 × 2^n, 8) s, minus up to 25 per cent | Full jitter; cap 30 s for 429, 503 and 529, 8 s otherwise |
| Statuses retried | 408, 409, 429 and every status of 500 or more | 408, 409, 429, 500, 502, 503, 504, 529; never a spend-cap 429 |
x-should-retry | Obeyed, true or false | Obeyed, true or false |
retry-after | retry-after-ms, seconds or HTTP-date; waited exactly, no jitter | Seconds only; a floor under the backoff, plus up to 10 per cent |
| Errors once the stream has started | Not retried; a cut stream returns an empty message | Retried: stalls, drops, error events, missing message_stop |
| Caller's deadline | None | Bounds every attempt and every wait |
The SDK is ahead in one place: it reads retry-after-ms and the HTTP-date form, which the client does not. Adding them is a few lines. For scripts and short requests, where two quick retries are enough, the SDK's defaults are fine.
What else belongs in the toolbox
- Idempotency. A retry is safe only if repeating the call is harmless. LLM generation is, apart from cost; side effects around it may not be. Stripe's API shows the pattern: idempotency keys allow "safely retrying requests without accidentally performing the same operation twice". When a write's answer is lost, treat the outcome as unknown, not as failed.
- Circuit breakers. After enough failures, stop calling for a while: "all further calls to the circuit breaker return with an error, without the protected call being made at all", as Martin Fowler describes. The adaptive concurrency limit from the previous post is a softer version of the same idea.
- Hedged requests. Dean and Barroso's "The Tail at Scale" sends a second request when the first is slower than usual and takes whichever answers first. It works well for cheap reads; for LLM generation it doubles cost on every hedged call, so I would use it only for short, latency-critical requests, if at all.
- Request IDs. "Every API response includes a unique
request-idheader." Log it with every attempt; it is the only way to ask the provider what happened to a specific call.
A checklist
- Choose one retry layer; turn the others off, including the SDK's.
- Classify errors: retry 408, 409, 429, 500, 502, 503, 504 and 529, retryable error events inside streams, and transport errors; never retry other 4xx or a spend-cap 429; obey
x-should-retry. - Use full or decorrelated jitter, with a higher cap for throttling than for errors.
- Treat
retry-afteras a floor, with a little spread. - Derive every attempt's timeout from the caller's deadline, and fail by name when the next wait will not fit.
- Stream long or cancellable calls, with an idle timeout per read.
- Catch transport errors raised mid-stream, check the deadline between events, and check
stop_reasonbefore trusting a message. - Leave room for thinking in
max_tokens; do not retry a truncated answer unchanged. - Log the request ID, the attempt number and the wait for every retry.
Sources
- Marc Brooker, Exponential Backoff And Jitter, AWS Architecture Blog
- Amazon Builders' Library: Timeouts, retries, and backoff with jitter
- Google SRE book: Handling Overload and Addressing Cascading Failures
- gRPC: deadlines and gRFC A6, client retries
- RFC 9110, Retry-After and RFC 6585, 429 Too Many Requests
- Claude API: errors and rate limits
- Anthropic Python SDK (version 2.16.0 tested here)
- Dean and Barroso, The Tail at Scale, Communications of the ACM, 2013
- Martin Fowler: Circuit Breaker
- Stripe API: idempotent requests