← All posts

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 with stop_reason=None, and no exception.

What can go wrong, and what to do about it

FailureSignalRetry?How
Rate limited429 rate_limit_error, often with retry-afterYesWait at least retry-after, with jitter; same growth as for errors, with a higher cap
Overloaded529 overloaded_error, 503YesThrottling backoff; reduce concurrency, as in the previous post
Server error500 api_errorIf x-should-retry is not falseShorter backoff
Timed out before the responseConnect or read timeout, 504Yes, within the deadlineStream long requests so the connection is never idle for long
Stream stalls or dropsNo bytes for a while; a transport error mid-bodyYesAn idle timeout per read; catch the transport's own exceptions
Error inside a streamAn error event after the 200, such as overloaded_errorIf its type is retryableClassify by the event's type; the status code is still 200
Stream ends earlyNo message_stop; stop_reason is NoneYesCheck stop_reason before trusting the message
Bad request400, 401, 403, 404, 413NeverFail at once; it will fail the same way every time
Spend cap reached429 rate_limit_error with enforced_spend_limit_reached, no retry-afterNeverFail at once; it lasts until the cap resets
Answer truncated by max_tokensstop_reason is max_tokensNot as isRaise 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:

A workflow retries an activity, which retries a step, which retries an LLM call against an overloaded provider: with three attempts at each layer, one request becomes up to 3, 9 and finally 27 calls Workflow retries the activity Activity retries the step LLM client retries the call Provider overloaded up to 3 calls up to 9 calls up to 27 calls 27 calls for one request Three attempts at each of three layers. With four, it is 64: the example in Google's SRE book.
Figure 1. Retries at every layer 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.

Two panels of bars. 95th-percentile finish in the burst: no jitter 24.6 seconds, the SDK default 15.1, full jitter with an 8 second cap 11.0, with a 30 second cap 12.3, decorrelated 10.6, retry-after alone 8.7, retry-after with a jitter floor 11.5. Calls per client in the storm: 8.9, 9.0, 12.8, 7.9, 8.2, 79.7 and 7.9 Seven retry strategies, 200 clients, a provider allowing 20 requests per second (simulated) 95th-percentile finish, burst (s) calls per client, minute-long storm no jitter, cap 8 s 24.6 8.9 SDK default, cap 8 s 15.1 9.0 full jitter, cap 8 s 11.0 12.8 full jitter, cap 30 s 12.3 7.9 decorrelated, cap 30 s 10.6 8.2 retry-after only 8.7 79.7 retry-after, jitter floor 11.5 7.9 Not shown: retrying at once without backoff took 717 calls per client in the burst and 7,224 in the storm.
Figure 2. No strategy wins everywhere; jitter shortens the tail, and the cap trades load against tail.
StrategyBurst: calls per clientBurst: last client doneStorm: calls per clientStorm: 95th percentile
Retry at once, no backoff716.99.2 s7,22462.7 s
Exponential, no jitter, cap 8 s4.232.7 s8.980.6 s
SDK default: cap 8 s, minus up to 25%3.915.7 s9.064.9 s
Full jitter, cap 8 s4.313.8 s12.865.0 s
Full jitter, cap 30 s4.322.8 s7.976.8 s
Decorrelated jitter, cap 30 s3.215.0 s8.280.6 s
retry-after only, +10%73.09.2 s79.762.3 s
retry-after as a floor, full jitter 30 s4.318.2 s7.977.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.
Two lines of calls per 100 ms over 34 seconds. Without jitter, calls arrive in tall periodic spikes; with full jitter, they are spread evenly Calls reaching the provider per 100 ms, burst of 200 clients (simulated, one seed) 0 10 20 0 s 10 s 20 s 30 s no jitter: synchronised waves full jitter: spread out Peaks above 25 are clipped. The first second, when all clients arrive, dominates both.
Figure 3. Without jitter, rejected clients come back together.

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 timeline from start to deadline with a safety margin at the end: attempt one, a backoff, attempt two, a backoff, and a third attempt shortened to end before the margin start deadline margin attempt 1 attempt 2 attempt 3 (shortened) backoff backoff Each attempt gets min(attempt timeout, time left minus margin); a retry whose wait cannot fit is not made.
Figure 4. Each attempt gets the time that is actually left.

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.

Two timelines of chunks arriving and then silence. With only a whole-request timeout, the stall is noticed at the end of the budget; with an idle timeout per read, it is noticed one idle interval later whole-request timeout only chunks arrive, then the connection goes silent noticed at the end of the budget idle timeout per read chunks arrive, then the connection goes silent noticed one idle interval later
Figure 5. Silence should cost an idle interval, not a whole budget.

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.

Flow of one retry decision. An attempt produces an outcome. A bad request or spend cap raises at once, and a reply with stop_reason set is returned. Anything else waits for the larger of full-jitter backoff and retry-after. If the next attempt fits before the deadline minus a margin it sleeps and tries again, otherwise it raises DeadlineExceeded Attempt timeout = min(idle, time left) Outcome reply, API error, transport error Never retry: raise 400, 401, 403, 404, 413 spend cap, x-should-retry false Success: return stop_reason is set anything else: retry wait = max(backoff, retry-after) full jitter, cap 30 s if 429, 503, 529, else 8 s; retry-after plus up to 10% Does the next attempt fit? 10 s of attempt after the wait, 5 s margin No: DeadlineExceeded names the attempts made and the wait that did not fit Yes: sleep, then retry next attempt
Figure 6. One pass through the retry loop in the client below.
"""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:

ScenarioRequests sentTimeOutcome
429 with retry-after: 1, then success21.2 sCorrect reply
529 twice, then success30.8 sCorrect reply
400 invalid request10.0 sBadRequestError, not retried
500 with x-should-retry: false10.0 sInternalServerError, not retried
Headers and one event, then 30 s of silence (idle timeout 2 s, deadline 60 s)944.6 sDeadlineExceeded: the next 4.9 s wait would not fit
529 on every attempt (deadline 20 s)54.9 sDeadlineExceeded: the next 4.8 s wait would not fit
Stream closed after its first event, then success20.2 sCorrect reply
An overloaded_error event after the stream's 200, then success20.2 sCorrect reply
One small delta a second for 40 s (idle timeout 2 s, deadline 25 s)120.1 sDeadlineExceeded while still streaming, at the deadline minus the margin
429 for a reached spend cap, on every attempt10.0 sEnforcedSpendLimitReachedError, not retried
The same stall, with the SDK's defaults130.0 sAn 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's APITimeoutError. 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 and stop_reason=None. Code that reads content[0] crashes, and code that iterates over the content treats an empty answer as a real one. The client now raises IncompleteStream and 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_error event inside a stream reached the client as an APIStatusError with 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.

BehaviourSDK defaultsThis client
Request timeout10 minutes, connect 5 sTime left before the deadline, minus a margin; connect 5 s
Stream silenceWaits up to the 10-minute timeoutIdle timeout per read, 60 s by default
Attempts2 retries, then raiseAs many as fit before the deadline
Backoffmin(0.5 × 2^n, 8) s, minus up to 25 per centFull jitter; cap 30 s for 429, 503 and 529, 8 s otherwise
Statuses retried408, 409, 429 and every status of 500 or more408, 409, 429, 500, 502, 503, 504, 529; never a spend-cap 429
x-should-retryObeyed, true or falseObeyed, true or false
retry-afterretry-after-ms, seconds or HTTP-date; waited exactly, no jitterSeconds only; a floor under the backoff, plus up to 10 per cent
Errors once the stream has startedNot retried; a cut stream returns an empty messageRetried: stalls, drops, error events, missing message_stop
Caller's deadlineNoneBounds 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-id header." 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-after as 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_reason before 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