Sub topic 10
Retries and fallback across providers
This chapter assumes you have the neutral ChatRequest and ChatResponse types, the ChatProvider protocol, and the ProviderError class with its retryable flag from earlier chapters. It also assumes you are comfortable with Python exceptions and loops.
Two different recovery tools
A retry sends the same request to the same provider again. A fallback sends it to a different provider. They solve different problems.
- A retry helps when the failure is brief. Examples are a rate limit that clears in a few seconds or a dropped connection.
- A fallback helps when the provider stays unavailable. Examples are an outage or a quota that is used up for the hour.
Both depend on one rule: the code must know whether trying again can help. Your adapters already answer that by setting retryable on every ProviderError. The recovery code reads that flag. It never inspects provider-specific status codes.
Deciding when to switch
Switch only when another attempt could succeed. Some errors will fail the same way everywhere.
| Error | Retryable | Reason |
|---|---|---|
| Rate limit (429) | Yes | The limit clears, or another provider has capacity |
| Server error (5xx) | Yes | The provider is having a problem |
| Timeout or connection error | Yes | The network or provider may recover |
| Invalid request (400) | No | Every provider will reject it |
| Bad API key (401) | No | Fix the configuration. Switching hides the bug |
Fallback across providers
The loop below tries each provider in order. It moves on only for retryable errors and re-raises everything else immediately.
def complete_with_fallback(
providers: list[ChatProvider], request: ChatRequest
) -> ChatResponse:
last_error: ProviderError | None = None
for provider in providers:
try:
return provider.complete(request)
except ProviderError as err:
if not err.retryable:
raise
last_error = err
raise last_error or ValueError("no providers configured")If every provider fails with a retryable error, the function raises the last one. If the list is empty, it raises ValueError, which signals a configuration mistake.
Adding retries with backoff
Backoff means waiting longer after each failed attempt. It stops your code from hammering a provider that is already struggling. Adding random jitter, a small random extra delay, keeps many clients from retrying at the same moment.
import random
import time
def complete_with_retry(
provider: ChatProvider,
request: ChatRequest,
max_attempts: int = 3,
base_delay: float = 0.5,
) -> ChatResponse:
for attempt in range(1, max_attempts + 1):
try:
return provider.complete(request)
except ProviderError as err:
if not err.retryable or attempt == max_attempts:
raise
delay = base_delay * (2 ** (attempt - 1))
time.sleep(delay + random.uniform(0, delay / 2))
raise AssertionError("unreachable")With the defaults, the waits are about 0.5 and 1 second, each plus jitter. The final raise AssertionError exists only to satisfy type checkers, because the loop always returns or raises first.
Combining both
Wrap each provider in its own retry loop, then fall back. This keeps retries local and short, and it moves on once a provider has used its attempts.
class RetryingProvider:
def __init__(self, inner: ChatProvider, max_attempts: int = 3):
self.inner = inner
self.max_attempts = max_attempts
def complete(self, request: ChatRequest) -> ChatResponse:
return complete_with_retry(self.inner, request, self.max_attempts)
def build_chain(providers: list[ChatProvider]) -> list[ChatProvider]:
return [RetryingProvider(p) for p in providers]
# chain = build_chain([primary, secondary])
# response = complete_with_fallback(chain, request)RetryingProvider satisfies ChatProvider, so the fallback function does not know it is there. This is the same interface idea you have used all chapter.
Common mistakes
- Retrying non-retryable errors. This wastes time and can burn quota on requests that will never succeed.
- Unbounded retries. Always cap attempts. Also cap total time if your caller has a deadline.
- Ignoring model differences. A fallback model may format answers differently or follow instructions differently. Test prompts against each provider in the chain.
- Silent fallback. Log which provider answered. Otherwise a quiet outage looks like a quality drop.
Exercise
Exercise
Your primary provider returns a 400 error because the request contains an unsupported parameter. The adapter marks it retryable=False. What does complete_with_fallback do, and why is that the right behavior?
Show answer
It re-raises the error immediately without trying the secondary provider. A 400 means the request itself is wrong, so other providers are likely to reject it too. Raising at once surfaces the bug quickly and avoids wasted calls.
Exercise
With max_attempts=3 and base_delay=0.5, how many times is provider.complete called if every call fails with a retryable error, and what is the approximate total base wait, ignoring jitter?
Show answer
Three calls. Waits happen only between attempts, so there are two waits of 0.5 s and 1 s, about 1.5 s in total. After the third failure the error is raised without waiting.