How to Implement Model Fallback Without Infinite Retries
Build a bounded LLM fallback chain with per-model attempt limits, exponential backoff, fail-fast client errors and an overall production deadline.
HeFu · Published 2026-11-26 · Updated 2026-11-263 min read
Model fallback improves resilience only when it has strict limits. Without attempt caps, deadlines and error classification, one malformed request or upstream outage can turn into a long sequence of slow, billable calls.
The HeFu API Examples repository contains a runnable Python fallback example using the same OpenAI-compatible endpoint and API key.
Every retry and every fallback can create another billable request. Test the chain deliberately with a small budget; do not use it as an unattended traffic generator.
1. Classify Errors Before Choosing an Action
| Failure | Appropriate action | Reason |
|---|---|---|
429 rate or quota limit | Bounded retry with backoff, then fallback | The condition may be temporary |
5xx server error | Limited retry, then fallback | The selected upstream route may be unhealthy |
| Timeout or connection error | Bounded retry, then fallback | Network and upstream causes need a recovery path |
400, 401, 403, 404 and other non-429 client errors | Stop and fix the request or credentials | Repeating the same invalid input across models wastes calls |
The important rule is never turn a client error into a tour of the entire model catalog. An invalid model ID, missing credential or malformed message needs correction, not fallback.
2. Set Four Independent Limits
A production fallback policy should define:
- Attempts per model: the example uses
MAX_RETRIES_PER_MODEL = 2, including the first attempt. - Per-request timeout: the example passes a 30-second timeout to each SDK call.
- Overall deadline: bound the complete operation, including backoff and every model. This is an additional production requirement, not a claim that the minimal example implements it.
- Maximum chain length: list only models that have passed the same task-specific acceptance test.
Backoff should increase exponentially and include jitter so many clients do not retry together. Cancellation and the overall deadline must also cover time spent sleeping between attempts.
3. Run the Bounded Example
Clone the repository and configure one protected key:
git clone https://github.com/hefu-hk/hefu-api-examples.git
cd hefu-api-examples
pip install openai
export HEFU_API_KEY="sk-hefu-..."
python examples/fallback.py
The example's ordered chain is:
deepseek-v4-flash → gemini-4-carbon → kimi-k3
These IDs were checked against the live catalog on 2026-11-21 and are examples, not permanent availability guarantees. Before running, compare the chain with the live model catalog and edit FALLBACK_CHAIN to contain currently listed chat models suitable for your task.
The example returns the answer, the model that produced it and the total attempt count. If every model exhausts its allowed attempts, it raises an error instead of continuing forever.
4. Preserve Quality and Cost Controls
Fallback changes more than infrastructure routing. A different model may have different context limits, tool support, output style and rates.
For each intended chain:
- Run the same sanitized acceptance fixture against every model.
- Record which model answered and how many attempts were used.
- Include all attempts—not only the successful one—in usage reconciliation.
- Alert when fallback frequency rises instead of hiding a persistent primary-model failure.
- Define the user-facing behavior when the chain is exhausted.
For user-facing workflows, consider whether a degraded answer should be labeled or held for review. For background jobs, store the selected model with the result so later evaluation remains reproducible.
5. Test Failure Paths Without Creating a Retry Storm
Use mocked SDK errors for routine tests: 401, 400, 429, 500, timeout and success on a later model. Assert the exact number of calls, delay behavior and final error. This verifies policy without spending model tokens or depending on a real outage.
Use a real request only as a separately approved integration check. Inspect the HeFu console's call records and wallet details afterward. For the protocol foundation, start with the Python quickstart; for implementation notes and the complete source, read the repository's fallback guide.
FAQ
Should every failed request switch to another model?
No. Retryable infrastructure failures such as 429, 5xx, timeouts and connection errors can use bounded retry and fallback. Other 4xx errors normally require fixing the credentials, model ID or request rather than calling more models.
Can two fallback models be treated as identical?
No. Evaluate output quality, capabilities, context, latency and current billing for every model in the chain. Record which model produced the answer.
Does the example retry forever?
No. The repository example uses two attempts per model and then stops after the ordered chain is exhausted. Production code should also enforce an overall deadline and cancellation policy.