Sub topic 10
Retries and fallback across providers
This chapter assumes you have read the earlier chapters of this tutorial. You should know the neutral ChatRequest and ChatResponse types, the ChatProvider protocol, and how adapters raise a normalized ProviderError with a retryable flag. You should also be comfortable with Python exceptions and basic HTTP status codes.
Two different recovery tools
Retry and fallback solve different problems, and mixing them up causes most reliability bugs in multi-provider code.
- Retry repeats the same request against the same provider. It helps when the failure is brief: a rate limit, a momentary overload, a dropped connection.
- Fallback sends the request to a different provider. It helps when one provider stays unavailable for longer than you can wait.
The usual order is to retry a few times with short delays, then fall back. Each provider gets a small retry budget, and fallback only starts once that budget is spent.
Deciding what to do with each error
Both tools depend on the error normalization from the previous chapter. The calling code should never inspect provider-specific exception types. It should only read retryable and, when present, retry_after.
| Normalized failure | Typical source | Retry same provider? | Fall back? |
|---|---|---|---|
| Rate limited | HTTP 429 | Yes, after the wait the provider requests | Yes, if the wait is long |
| Overloaded or server error | HTTP 500, 502, 503, 529 | Yes, with backoff | Yes |
| Timeout or connection reset | Network | Yes, with caution (see below) | Yes |
| Invalid request | HTTP 400, 422 | No | No. Every provider would reject it |
| Authentication failed | HTTP 401, 403 | No | Usually no. It is a configuration bug |
| Context too long | HTTP 400 with a specific code | No | Only if the fallback model has a larger window |
The last two rows are policy decisions, not facts. Falling back on an authentication error keeps traffic flowing, but it also hides a broken API key until someone notices the bill from the backup provider. If you choose to fall back there, log it loudly.
Retry with exponential backoff and jitter
Backoff means waiting longer after each failure: for example 0.5 s, then 1 s, then 2 s. Jitter means picking the actual wait at random up to that limit. Without jitter, many clients that failed at the same moment all retry at the same moment and overload the provider again. This version uses "full jitter", where the delay is a random value between zero and the current backoff limit.
When a provider sends a Retry-After value, trust it over your own schedule. If that wait is longer than you are willing to sleep, do not retry early. Raise the error so the fallback layer can take over.
The block below is complete and runnable. The types at the top repeat the earlier chapters so the file stands alone, and ProviderError gains an optional retry_after field.
import random
import time
from dataclasses import dataclass, replace
from typing import Callable, Protocol
@dataclass
class Message:
role: str
content: str
@dataclass
class ChatRequest:
model: str
messages: list[Message]
max_tokens: int = 512
temperature: float | None = None
@dataclass
class ChatResponse:
text: str
model: str
input_tokens: int | None = None
output_tokens: int | None = None
class ChatProvider(Protocol):
def complete(self, request: ChatRequest) -> ChatResponse: ...
class ProviderError(Exception):
def __init__(self, message: str, retryable: bool, retry_after: float | None = None):
super().__init__(message)
self.retryable = retryable
self.retry_after = retry_after
def call_with_retry(
provider: ChatProvider,
request: ChatRequest,
max_attempts: int = 3,
base_delay: float = 0.5,
max_delay: float = 8.0,
sleep: Callable[[float], None] = time.sleep,
) -> ChatResponse:
attempt = 1
while True:
try:
return provider.complete(request)
except ProviderError as err:
if not err.retryable or attempt >= max_attempts:
raise
if err.retry_after is not None:
if err.retry_after > max_delay:
raise # waiting is too long; let fallback handle it
delay = err.retry_after
else:
ceiling = min(max_delay, base_delay * 2 ** (attempt - 1))
delay = random.uniform(0, ceiling)
sleep(delay)
attempt += 1The sleep parameter is there for testing. A test can pass a function that records delays instead of actually waiting.
Fallback across providers
Fallback needs one detail that is easy to miss: model names are provider-specific. If the primary target is gpt-4o on one provider, you cannot send that name to another provider. So a fallback list holds pairs of a provider and the model to use on it, and the code rewrites request.model for each attempt.
@dataclass
class Target:
provider: ChatProvider
model: str
def complete_with_fallback(
targets: list[Target], request: ChatRequest, **retry_options
) -> ChatResponse:
last_error: ProviderError | None = None
for target in targets:
attempt_request = replace(request, model=target.model)
try:
return call_with_retry(target.provider, attempt_request, **retry_options)
except ProviderError as err:
if not err.retryable:
raise
last_error = err
if last_error is None:
raise ValueError("no targets configured")
raise last_errorThis extends the simple fallback loop from earlier in the tutorial in two ways. Each target gets its own retry budget, and the model name changes per target. Non-retryable errors still stop everything immediately.
Testing the rules
Because sleep is injectable and providers are plain objects, you can test every branch without a network. A FlakyProvider fails a set number of times and then succeeds. This continues the fake-provider approach from the testing chapter.
class FlakyProvider:
def __init__(self, failures: int, error: ProviderError):
self.failures = failures
self.error = error
self.calls = 0
def complete(self, request: ChatRequest) -> ChatResponse:
self.calls += 1
if self.calls <= self.failures:
raise self.error
return ChatResponse(text="ok", model=request.model)
request = ChatRequest(model="unused", messages=[Message("user", "hi")])
delays: list[float] = []
# 1. Transient failures are retried on the same provider.
flaky = FlakyProvider(2, ProviderError("overloaded", retryable=True))
response = call_with_retry(flaky, request, sleep=delays.append)
assert flaky.calls == 3 and len(delays) == 2
# 2. An exhausted provider triggers fallback, with the model renamed.
down = FlakyProvider(99, ProviderError("down", retryable=True))
backup = FlakyProvider(0, ProviderError("unused", retryable=True))
targets = [Target(down, "model-a"), Target(backup, "model-b")]
response = complete_with_fallback(targets, request, sleep=delays.append)
assert down.calls == 3
assert response.model == "model-b"
# 3. A non-retryable error stops everything and never reaches the backup.
bad = FlakyProvider(99, ProviderError("invalid request", retryable=False))
untouched = FlakyProvider(0, ProviderError("unused", retryable=True))
try:
complete_with_fallback(
[Target(bad, "model-a"), Target(untouched, "model-b")],
request,
sleep=delays.append,
)
raise AssertionError("expected ProviderError")
except ProviderError as err:
assert not err.retryable
assert bad.calls == 1 and untouched.calls == 0
# 4. A Retry-After longer than max_delay skips retries and raises at once.
slow = FlakyProvider(99, ProviderError("rate limited", retryable=True, retry_after=60))
try:
call_with_retry(slow, request, sleep=delays.append)
raise AssertionError("expected ProviderError")
except ProviderError:
assert slow.calls == 1Edge cases that bite in production
Timeouts and duplicate work
A timeout does not mean the provider did nothing. The request may have reached the model and may still be billed. Retrying a timed-out request can therefore cost twice. For chat completions this is usually acceptable, since the call has no side effects on your data. It matters when the call triggers tool execution on the provider's side, or when you pay per token on long outputs. Keep timeouts generous enough that normal slow responses are not cut off.
Streaming
Once a stream has delivered tokens to the user, you cannot silently restart on another provider, because the user has already seen partial text and the second provider would produce a different continuation. The safe rule is to retry or fall back only before the first chunk arrives. After that, surface the error, or restart and discard the partial output if your interface allows it.
Total time budget
Three attempts across three providers, each with backoff, can add up to a long wait. Give the whole operation a deadline. Pass a remaining-time value into each attempt and stop when it is spent. A user waiting on a chat reply will give up long before a nine-attempt chain finishes.
Retry storms
If every request retries three times during an outage, your traffic to the struggling provider triples. A circuit breaker limits this. After a run of consecutive failures, it marks the provider as open for a cooling-off period and skips it entirely, so requests go straight to the next target. Add one when you see sustained outages, not before.
Fallback changes behavior
The backup model is not the same model. It may format output differently, follow instructions differently, and have a different context window or price. Fallback keeps the application running, but answers may change in quality or style. Record which target served each response (the model field in ChatResponse helps) so you can see how often fallback happens and what it costs.
Choosing limits
Reasonable starting values are two or three attempts per provider, a base delay near half a second, and a maximum delay of several seconds. Keep the list of fallback targets short, usually one or two. Longer lists add latency and make behavior hard to predict. Tune from observed data: how often retries succeed, and how often fallback fires.
Exercise
Your fallback list is [OpenAI target, Anthropic target]. A request fails on OpenAI with an invalid-request error (HTTP 400, normalized as retryable=False). What does completewithfallback do, and why is that the right behavior?
Show answer
It re-raises the error immediately without retrying and without calling the Anthropic target. A malformed request is the caller's fault, so another provider would reject it too. Trying it would waste time and send the prompt to an extra provider for nothing.
Exercise
A provider returns a rate-limit error with retryafter=45, and your maxdelay is 8 seconds. What should callwithretry do, and what happens next in completewithfallback?
Show answer
callwithretry re-raises the error without sleeping, because retrying earlier than 45 seconds would fail again and sleeping 45 seconds is too long. completewithfallback sees a retryable error, records it, and moves on to the next target with that target's own model name.
Exercise
Why is it unsafe to fall back to a second provider after a streaming response has already sent some tokens to the user?
Show answer
The user has already seen partial text. A different provider would generate a different continuation, so the combined output would be inconsistent or contradictory. Retry or fall back only before the first chunk, or discard the partial output and restart if the interface supports that.