Sub topic 2
Deciding what to retry and what to surface immediately
This chapter assumes you can write basic Python, know what HTTP status codes and headers mean, and have called an LLM API with an SDK or an HTTP client. It covers one decision: when a call fails, do you try again or report the error? The chapters on backoff, jitter, and retry limits cover how to retry.
Why the decision matters
A retry is only useful if the next attempt can succeed. Some failures are temporary, such as an overloaded server or a dropped connection. The same request will often succeed a moment later. Other failures are permanent. A malformed request or an invalid API key fails the same way every time.
Retrying a permanent error has three costs:
- It adds latency before the user sees the real problem.
- It can burn quota, because many providers count failed requests toward limits.
- It hides bugs in logs behind repeated identical failures.
Failing fast on a temporary error has its own cost. A user sees an error that a half-second wait would have fixed. Good classification avoids both mistakes.
Start with the status code
The HTTP status code is the first signal. Codes in the 4xx range mean the server rejected your request. Codes in the 5xx range mean the server failed while handling it.
| Status | Meaning | Retry? | Why |
|---|---|---|---|
| 400 | Bad request, including context length exceeded | No | The same payload fails again |
| 401 | Missing or invalid API key | No | A retry sends the same key |
| 403 | Key lacks permission, or region or content blocked | No | Permissions do not change between attempts |
| 404 | Unknown endpoint or model name | No | The resource is not there |
| 408 | Request timeout | Yes | The server gave up waiting; a new attempt may be faster |
| 413, 422 | Payload too large, or invalid | No | You must change the request |
| 429 | Too many requests | Usually | Capacity frees up as time passes (see the caveat below) |
| 500 | Internal server error | Yes | Often a transient fault |
| 502, 503, 504 | Bad gateway, unavailable, gateway timeout | Yes | Upstream capacity or routing problems |
The first code example turns this table into a function.
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
def is_retryable_status(status_code: int) -> bool:
"""Return True for statuses that usually indicate a temporary problem."""
return status_code in RETRYABLE_STATUS
for code in (200, 400, 401, 404, 429, 500, 503):
print(code, is_retryable_status(code))Use an allowlist, as above, and not a rule such as "retry anything 5xx". An allowlist makes you choose each code on purpose. An unknown code then defaults to surfacing the error, which is the safer default.
Some providers add their own codes. Anthropic, for example, returns 529 when its service is overloaded. Check your provider's error documentation and add such codes to the set deliberately.
Not every failure has a status code
If the connection drops, the DNS lookup fails, or the read times out, no response arrives, so there is no status code. You classify these by exception type. In httpx, the base class for these failures is httpx.TransportError. It is broader than you want, though. It also includes httpx.UnsupportedProtocol, which means your URL is malformed, and retrying cannot fix that.
A narrower choice is to retry on timeouts, network errors, and the server closing the connection mid-response:
httpx.TimeoutExceptioncovers connect, read, write, and pool timeouts.httpx.NetworkErrorcovers connection failures and resets.httpx.RemoteProtocolErrorcovers a server that sends a broken or truncated response.
Provider SDKs wrap these in their own exception classes. The OpenAI Python SDK, for example, raises APIConnectionError, APITimeoutError, RateLimitError, and InternalServerError, among others. The logic is the same: map each class to retryable or permanent.
Classify 429 by its body, not only its status
A 429 response means "too many requests", and it is the most common retryable error with LLM APIs. It has one trap. Some providers also use 429 for an exhausted account balance or monthly quota. OpenAI, for example, returns 429 with the error code insufficient_quota when your credit runs out. Waiting does not fix that. A person has to add credit.
So the classifier should look at the response body for these cases. This function handles both exceptions and status codes, and it runs as shown:
import httpx
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
PERMANENT_429_CODES = {"insufficient_quota"}
RETRYABLE_EXCEPTIONS = (
httpx.TimeoutException,
httpx.NetworkError,
httpx.RemoteProtocolError,
)
def error_code(response):
"""Return the provider's error code from a JSON error body, or None."""
try:
body = response.json()
except ValueError:
return None
error = body.get("error") if isinstance(body, dict) else None
if isinstance(error, dict):
return error.get("code")
return None
def should_retry(exc):
if isinstance(exc, RETRYABLE_EXCEPTIONS):
return True
if isinstance(exc, httpx.HTTPStatusError):
response = exc.response
if response.status_code == 429 and error_code(response) in PERMANENT_429_CODES:
return False
return response.status_code in RETRYABLE_STATUS
return False # unknown exceptions are surfaced, not retried
def status_error(status, body=None):
request = httpx.Request("POST", "https://api.example.com/v1/chat")
response = httpx.Response(status, json=body or {}, request=request)
return httpx.HTTPStatusError(f"HTTP {status}", request=request, response=response)
cases = [
httpx.ConnectTimeout("timed out"),
httpx.ReadError("connection reset"),
status_error(503),
status_error(400),
status_error(429, {"error": {"code": "rate_limit_exceeded"}}),
status_error(429, {"error": {"code": "insufficient_quota"}}),
ValueError("bug in our own code"),
]
for exc in cases:
print(type(exc).__name__, should_retry(exc))The output is:
ConnectTimeout True
ReadError True
HTTPStatusError True
HTTPStatusError False
HTTPStatusError True
HTTPStatusError False
ValueError FalseThe last case matters. A ValueError from your own code is a bug, and retrying a bug only repeats it.
The decision as a flow
Content errors need separate thought
Some failures arrive with a normal-looking response, or with a 400, and concern the content and not the connection.
- Context length exceeded. This is usually a 400. The prompt is too long, and retrying cannot shorten it. Fix it by trimming or summarizing the input, then send a new request.
- Content filter or refusal. The provider blocked the prompt or output. The same prompt will usually be blocked again. Surface it, or rewrite the request.
- Invalid model output. The call succeeded, but the JSON is broken or fails validation. The model is not deterministic, so a second attempt may work. This is a validation retry. Give it a small separate limit, and never mix it into the network retry loop. Otherwise the two multiply (5 network attempts times 3 validation attempts is 15 calls).
Ambiguous failures: did the request run?
A read timeout is retryable by the table, but it leaves a question. The server may have received your request and be processing it while you gave up waiting. A retry could then run the work twice. For a plain chat completion, the cost is a duplicate charge for tokens. If the call triggers side effects, such as a tool call that sends an email, a duplicate is a real problem. The chapter on idempotency covers this. For now, note that "retryable" means "may succeed on a new attempt", not "harmless to repeat".
Surfacing errors well
When you decide not to retry, surface the error in a way that helps:
- Keep the original status code and provider error message. Do not replace them with a generic "something went wrong".
- Show end users a short message, and log the details with a request ID if the provider returns one.
- Raise a distinct exception for permanent errors, so callers can handle "bad key" differently from "service down".
Exercise
Your client receives HTTP 429 with the body {"error": {"code": "insufficient_quota"}}. Should it retry? What should the application do instead?
Show answer
No. This 429 reports an exhausted account balance or quota, not a short-term rate limit, so waiting will not fix it. The application should surface the error immediately, log it with the provider's message, and alert a person to add credit or raise the quota.
Exercise
A request fails with httpx.UnsupportedProtocol because the URL was written as "api.example.com/v1/chat" with no scheme. Why is catching the broad httpx.TransportError a poor retry rule here?
Show answer
UnsupportedProtocol is a subclass of TransportError, so a broad rule would retry it. The URL is malformed, and every attempt fails the same way. Retrying only adds delay. Listing the specific retryable classes (TimeoutException, NetworkError, RemoteProtocolError) avoids this.
Exercise
A model returns a 200 response, but the JSON inside fails your schema validation. Should this share the network retry limit? Give a reason.
Show answer
No. It is a content failure, not a connection failure. Give it a separate, small retry limit. If the two share a loop, the limits multiply, and one bad prompt can produce many more calls than you intended.