Getting LLM API retry and fallback right matters more than it looks: every retry is a second request, and on a metered LLM API a second request can be a second billable inference. Most retry advice skips that part, because a retried GET is free and a retried chat completion is not.
This post lays out a retry and fallback pattern for OpenAI-compatible endpoints such as AtmoRouter's https://atmorouter.dev/v1: a wall-clock deadline, an explicit attempt budget, error classification, and a cheaper standby model. It is AtmoRouter-authored. The arithmetic below is illustrative, not a benchmark, and every rate comes from the live catalogue on 2026-11-11.
Why a retry is a second inference
When a request is rejected before any tokens are generated — a 400, a 401, or a rate-limit 429 — you generally pay nothing, and AtmoRouter does not bill failed requests. The costly case is different: the server accepted the request, began generating, and your client gave up first. The timeout fired, you never read the stream, and the tokens were produced anyway. Retrying that means paying twice for one answer.
That reframes the first design decision. It is not "how many retries do I allow" but "how long will I wait before I decide the request is lost". A retry policy with no wall-clock budget just multiplies latency, and in the timeout case it multiplies spend.
Set a deadline first, then an attempt budget
The OpenAI Python SDK already retries some failures for you: two retries by default with a short exponential backoff, covering connection errors, 408, 409, 429 and 5xx responses. max_retries changes it at the client level, with_options(max_retries=...) per call. Streams are not retried automatically once you start consuming them.
The trap is stacking layers. Three SDK attempts wrapped in your own three-attempt loop is nine requests, a 9x latency tail, and up to 9x the spend on a workload that times out. Pick one layer. I set max_retries=0 on the client and let an explicit loop own the budget, so every attempt is visible in my logs and counted against one clock.
pythonimport os, random, time
import openai
client = openai.OpenAI(
base_url="https://atmorouter.dev/v1",
api_key=os.environ["ATMOROUTER_API_KEY"],
max_retries=0, # one retry layer, and this is it
timeout=60.0,
)
CHAIN = ["zai/glm-5.3", "alicn/qwen3.8-flash"] # primary, then cheap standby
def is_retryable(exc):
return isinstance(
exc,
(openai.RateLimitError, openai.InternalServerError,
openai.APIConnectionError, openai.APITimeoutError),
)
def complete(messages, deadline_s=90):
started = time.monotonic()
last = None
for model in CHAIN: # fallback changes the model
for attempt in range(2): # two tries per model, max
try:
resp = client.chat.completions.create(
model=model, messages=messages, max_tokens=800
)
return resp, model
except openai.APIError as exc: # base class of every SDK error
last = exc
if not is_retryable(exc) or time.monotonic() - started > deadline_s:
raise
if getattr(exc, "code", None) == "insufficient_quota":
raise # an empty balance will not fix itself
response = getattr(exc, "response", None)
header = response.headers.get("retry-after") if response is not None else None
try:
wait = float(header) if header else 2 ** attempt
except ValueError: # HTTP-date form; fall back to backoff
wait = 2 ** attempt
time.sleep(wait + random.uniform(0, 0.5)) # jitter
raise RuntimeError("fallback chain exhausted") from lastClassify the error before you retry it
Not every failure deserves another request, and the status code alone is not enough. The SDK maps errors to classes you can branch on, which is more reliable than string-matching a message.
openai.RateLimitError(429): back off only if it is a rate limit. A 429 caused by an exhausted prepaid balance or a quota cap will never succeed on retry, so readerror.codefirst and respectRetry-Afterwhen it is present.openai.InternalServerError(5xx),APIConnectionError,APITimeoutError: retryable, but treat a timeout after generation started as expensive rather than free — prefer fewer retries and a shorter read timeout.BadRequestError,AuthenticationError,PermissionDeniedError,NotFoundError: fail fast. These are your bugs, and retrying them burns wall-clock for nothing.
Fallback is a different axis
A second attempt against an overloaded model usually fails for the same reason the first one did. Fallback changes the variable: same request shape, same protocol, different model. Because an OpenAI-compatible endpoint keeps the payload identical, fallback is a one-line change in most clients — swap the model field.
Keep the standby cheap. These are from-prices per million input/output tokens from the public catalogue on 2026-11-11; rates change, and the model page is the authority.
| Model ID | Context | From (input / output, per M tokens) | |---|---|---| | zai/glm-5.3 | 1M | $0.0035 / $0.011 | | zai/glm-5.3-flash | 1M | $0.000375 / $0.00125 | | alicn/qwen3.8-flash | 1M | $0.000375 / $0.001175 | | mm/MiniMax-M3.1-Flash | 1M | $0.0375 / $0.15 | | cx/gpt-6-luna | 272K | $0.009 / $0.045 | | cx/gpt-6-sol | 272K | $0.1 / $0.5 |
The practical rule: your fallback should be the cheapest model in the same capability class that still handles your prompts, not a second flagship. If your standby costs as much as your primary, you have built a retry with extra steps.
The arithmetic, labelled as arithmetic
Take an illustrative workload of 50,000 requests a day, 8,000 input tokens and 800 output tokens each. All numbers below are arithmetic on catalogue rates, not measured results.
On cx/gpt-6-sol at from $0.1 / $0.5 per million, one request costs about $0.0012, so the day costs roughly $60 and 30 days roughly $1,800. On zai/glm-5.3 at from $0.0035 / $0.011, the same request costs about $0.0000368 and the day about $1.84.
Now the retry layer. If 2% of requests time out after the model has already generated a full answer, and you retry them, you add 2% to the bill: about $36 over 30 days on the flagship, about $1.10 on the cheap model. That is not catastrophic, which is exactly why it goes unnoticed. The problem is the 2% is elastic: a bad afternoon turns it into 30%, and the multiplier sits on your most expensive model.
Retries that were rejected before generation cost nothing extra, which is the other half of the design: make failure cheap by failing early, and keep the timeout tight enough that you are not paying for answers you will never read.
Log the things that make the pattern auditable
A retry layer you cannot audit becomes a mystery latency source three months later. Log one structured line per attempt:
- attempt number and model ID
- error class and HTTP status
Retry-Aftervalue if present- time to first byte, so a slow start is distinguishable from a failure
- whether any token was received, which tells you if the retry was billable
- a request fingerprint, so duplicate work is visible even though chat completions has no built-in idempotency key
A short checklist
- 1.One retry layer, one wall-clock deadline, an explicit attempt cap.
- 2.Backoff with jitter, and honour
Retry-Afterwhen the server sends it. - 3.Branch on the SDK's error classes; never retry a 4xx you caused.
- 4.A cheap standby model on a different family, swapped by changing
model. - 5.A tight read timeout so you stop paying for streams you abandoned.
- 6.Structured logs that show which attempts were billable.
FAQ
How many times should I retry an LLM API call?
For interactive work, two attempts per model and a single fallback model is usually enough. What matters more is the wall-clock deadline: once it passes, fail and surface the error instead of queueing another attempt.
Should I retry a 429 from an LLM API?
Only when it is a rate limit. Respect Retry-After if the server sends it and add jitter. A 429 that means an empty balance or an exhausted quota will not succeed on retry, so check the error code first.
Does the OpenAI SDK retry automatically when I use a different base URL?
Yes. The retry behaviour lives in the client, not the provider, so pointing base_url at https://atmorouter.dev/v1 keeps the default of two retries. Set max_retries=0 if your own loop owns the budget.
Is fallback to another model safe for structured output?
Usually, if both models handle your schema. Test the standby with your real prompts and validate its output before trusting it in production, because a cheaper model can be stricter or looser about JSON formatting.
If you want to see what the standby actually costs for your prompt sizes, check the live rates on the model page, and if your requests repeat a large system prompt the prompt caching guide is the cheaper win. AtmoRouter runs on a prepaid balance with no seat fees and does not bill failed requests, which makes the fail-early half of this pattern free to adopt.