Classify by error code, then status, then phase
A retry policy keyed on status codes alone gets two cases wrong. First, one status covers several causes: OpenAI documents 429 for a request-rate limit, a slow_down ramp limit, a depleted balance (credit_balance_exhausted), and organization or project spend and usage limits.1 Anthropic likewise returns 429 rate_limit_error for a rate limit and for a monthly spend cap, and the spend-cap case carries error.details.error_code of enforced_spend_limit_reached.2 Second, the same status means different things before and after the first token.
So the order of checks is:
- Phase. Did the response start? Before the first token a request can be moved to another target. After it, you are in stream-recovery territory (see the last section).
- Error code or type. Branch on
error.codeorerror.type, never on the message text. Anthropic's page says not to match messages in code, and that new codes and types can appear, so unrecognized ones should fall back to the HTTP status.2 - HTTP status. The fallback when there is no code.
The decision table
| Error | What it usually means | Retry same target | Fail over | Default |
|---|---|---|---|---|
400 invalid_request_error | Malformed or invalid request. Anthropic also returns 400 when an organization or workspace spend limit is reached.2 OpenAI returns 400 for a service tier the project disallows.1 | No | Only if the fallback differs on the rejected parameter | Fail fast |
| 401 | Bad, revoked or expired key; OpenAI also uses 401 for a blocked IP.12 | No | Yes, to a connection with a different credential | Fail fast on that key, alert |
| 408 | Request timeout. The Anthropic SDK retries it.2 | Yes, once or twice with backoff | Yes, if still failing | Retry, then fail over |
| 413 | Request over the size limit; Anthropic's Messages API limit is 128 MB.2 | No | Only to a target with a larger limit | Fail fast |
| 429, rate limit | Too many requests or tokens. OpenAI says to follow Retry-After when present.1 | Yes, if the wait fits your deadline | Yes, if it does not | Retry or fail over |
| 429, spend, usage or balance limit | Enforced limits that keep failing until someone changes them or the period resets.12 | No | Only to a connection with its own limit | Fail fast, alert an owner |
| 500 | Internal error. Anthropic: retry only if x-should-retry is not false.2 | Yes, one or two attempts | Yes | Retry, then fail over |
503 server_is_overloaded | OpenAI: model temporarily overloaded; follow Retry-After, then retry.1 | At most once, if the wait is short | Yes | Fail over quickly |
504 timeout_error | Anthropic also uses this type with other statuses, such as a 500 before the response starts.2 | Once | Yes | Retry once, then fail over |
529 overloaded_error | Anthropic: temporarily overloaded across all users.2 | Once, with backoff | Yes | Fail over quickly |
| 200 with a content-filter stop | Not an error status. Field names differ per provider and I did not confirm them. | No | Only by explicit policy | Fail fast to the caller |
Two rows deserve a note. For 429, the split between "clears in seconds" and "stays until a human acts" is the whole policy: OpenAI states that retrying billing, spend or quota errors will not restore access.1 Anthropic adds that a tier spend-cap 429 has no retry-after header and keeps failing until access resumes.2
For content-filter stops, a refusal is a property of the prompt and the model's policy, not of capacity. Retrying the same target repeats it. Failing over to a different vendor's model can change the outcome, but that decides what content policy your product accepts, so make it an explicit rule rather than a side effect of a generic fallback.
Retry-After rules
Retry-After is defined in RFC 9110 section 10.2.3.3 These rules cover what the headers do in practice:
- Treat the header as a floor. OpenAI says to wait at least as long as it specifies; if it is missing, use exponential backoff with jitter and a retry limit.1
- Compare it with your deadline. If the wait exceeds the time left in the request's budget, do not sleep: fail over now, or return a retryable error to the caller with the wait.
- Cap total attempts, not just each delay. Anthropic's SDK defaults to two retries (three attempts), honors
retry-after, and otherwise backs off from 0.5 to 8 seconds.2 Your own policy needs its own ceiling. - Do not assume the header exists. A 429 without it is not proof of a spend cap. Check the code first, then apply backoff.
- Respect
x-should-retry. Anthropic's SDK follows it when present, true or false, ahead of its status-based defaults.2 - Ramp after
slow_down. OpenAI's rule of thumb: once traffic reaches 1 million input tokens per minute, raise it by no more than 50% every 15 minutes.1 Replaying the backlog at full rate triggers the same error again.
Do not count a rate-limit 429 as a provider outage in health checks. A throttled key is healthy; see the post on circuit breakers for LLM providers.
Idempotency caveats
Chat and message calls are POST requests. RFC 9110 defines idempotent methods in section 9.2.2 and POST in 9.3.3, and POST is not among the idempotent methods.3 None of the pages I read describes an idempotency key for these endpoints, so assume a retry can run the work twice.
That has three consequences:
- A timeout is ambiguous. A 408, 504 or dropped connection does not say whether the provider finished generating. A retry or failover can produce a second completion and a second charge. Budget for it; see whether providers bill failed or cancelled streams.
- Two attempts can disagree. Outputs are not deterministic. If attempt one was partly consumed by a user or written somewhere, do not silently swap in attempt two.
- Tool calls are the dangerous part. Retrying the model call is safe while your code has not yet executed the tool calls it returned. After a tool has run, a replay can repeat the side effect. Give every attempt one request id and every tool call its own idempotency key on your side. See failover mid-agent-run.
Mid-stream errors
An error can arrive after the API has returned 200. Anthropic documents error events inside an SSE stream and says its SDK does not retry an error in a stream.2 That makes the first token a hard boundary.
- Before the first token: retry or fail over freely, within the limits above.
- After the first token: do not fail over invisibly unless you can discard the partial output. Either surface the failure, or restart on a new target and mark the first attempt as abandoned.
- Log both: the partial attempt's tokens were probably billed.
The streaming failure-mode guide covers recovery in more depth.
Putting it into a gateway
A hand-written policy is a small function plus tests. Classify once, then let one layer act on it:
def action(status, code, retry_after, time_left):
if code in {"credit_balance_exhausted", "enforced_spend_limit_reached",
"organization_spend_limit_exceeded",
"project_spend_limit_exceeded",
"organization_usage_limit_exceeded"}:
return "fail_fast_alert"
if status in (400, 413, 422):
return "fail_fast"
if status in (401, 403):
return "failover_other_credential"
if status == 429:
if retry_after is not None and retry_after > time_left:
return "failover"
return "retry_after"
if status in (503, 529):
return "failover"
if status in (408, 500, 504):
return "retry_once_then_failover"
return "fail_fast"INFRO's gateway does a version of this before the first token. Its failover moves a request to the next connection or route target on a provider 5xx, timeout, 429, rejected credential, 404, or even a 400/422, and does not count a provider 429 against connection health.4 That is broader than the table above on purpose, since providers differ on optional parameters, so you may want a failure rule that stops on 400 for requests that must not leave one model. INFRO's own refusals (invalid body, budget, allowlist) return immediately without failover, and a provider-returned 429 surfaces with the code provider_rate_limited.5 Routing rules include failure rules that decide, per failure kind, whether to retry, move on or stop. Whichever layer you choose, keep the policy in one place.
Before rollout, run the table against a failover drill with injected 429, 503 and 529 responses.
