Model Routing, Fallbacks and Gateways
Several models can be cheaper and sturdier than one, if the switching is tested.
Routing picks a model for each request. Fallback switches when a call fails. A gateway is a shared service that handles model access, keys, limits, logging and these rules in one place. Start with one model and clear timeouts. Add routing when measurements show a benefit, and evaluate every route and fallback, because each is a different system.
What you will learn: routing strategies, retry and fallback rules, circuit breakers, what gateways do, a LiteLLM pattern, cost routing and how to compare gateways.
Prerequisites: Choosing Models: Reasoning, Open-Weight and Hosted. Basic Python for the code.
Three different ideas
| Idea | Question answered | When it acts |
|---|---|---|
| Routing | Which model should handle this? | Before the call |
| Retry | Is it worth asking the same one again? | After a temporary error |
| Fallback | Who takes over when it cannot? | After retries fail or a model is unavailable |
Routing strategies
| Strategy | How it chooses | Strength | Risk |
|---|---|---|---|
| By step | Each stage of the workflow names its model | Simple and predictable | Cannot adapt to hard cases |
| By rule | Language, size, customer tier, data class | Explainable | Rules grow tangled |
| By classifier | A small model labels difficulty or topic | Handles free text | The classifier can be wrong |
| Cascade | Try cheap first; escalate if a check fails | Saves money when checks are good | Pays twice for hard cases; weak checks pass errors |
| Load balancing | Spread across deployments of the same model | Capacity and resilience | Deployments may differ in version or settings |
Prefer the simplest strategy that your data supports. A rule such as "extraction goes to the small model" is easy to test and to explain.
An example routing table
Writing routes as a table makes them reviewable by people who will never read the code. This one is an illustration for a support agent.
| Request class | Primary | Fallback | If neither works |
|---|---|---|---|
| Label the topic | Small hosted model | Second small model | Send to the general queue |
| Answer an order question | Mid-sized model | Large model | Hand to a person with the details |
| Complaint or exception | Large model drafts | None | Hand to a person |
| Contains restricted data | Approved private deployment | Second approved deployment | Stop and explain; never send elsewhere |
The final column is the most important and the most often missing. Every route needs a defined behavior when no model can serve it. "Hand to a person" only works if somebody is there to receive it, so include opening hours and queue limits in the design.
Testing the router itself
If a classifier decides the route, it has its own error rate. Label a set of requests with the correct route and measure two mistakes separately: easy work sent to the expensive path, which wastes money, and hard work sent to the cheap path, which harms quality. The second is usually worse, so tune the threshold toward caution and measure again. Keep a record of the router's version with each request.
Retry only what can succeed
| Failure | Retry same? | Fall back? |
|---|---|---|
| Network error or timeout | A few times, with growing delay and randomness | Yes |
| Rate limit | After the indicated wait | Yes, if the other has capacity |
| Server error or overload | Briefly | Yes |
| Invalid request | No | No; fix it |
| Authentication failure | No | Alert; do not hide a broken credential |
| Content refusal | No | Generally no; shopping for a model that agrees undermines your policy |
| Input too long | No | Shorten, or use a model approved for longer input |
Set one overall deadline for the task. Retries at several layers multiply: three attempts each at the client, the gateway and the workflow can turn one request into twenty-seven.
A small router with a circuit breaker
A circuit breaker stops sending requests to a model that keeps failing, then tries again after a pause. The providers here are simulated.
"""Route by task, fall back on failure, and stop calling a broken model."""
class ProviderError(Exception):
def __init__(self, message, retryable):
super().__init__(message)
self.retryable = retryable
ROUTES = {"classify": ["small-a", "small-b"],
"analyze": ["large-a", "large-b"]}
class Router:
def __init__(self, call, trip_after=2, cool_down=30):
self.call = call
self.trip_after, self.cool_down = trip_after, cool_down
self.failures, self.blocked_until = {}, {}
def send(self, task, prompt, now):
tried = []
for model in ROUTES[task]:
if self.blocked_until.get(model, 0) > now:
tried.append(f"{model}: skipped (cooling down)")
continue
try:
answer = self.call(model, prompt, now)
except ProviderError as error:
if not error.retryable: # a bad request stays bad
raise
tried.append(f"{model}: {error}")
count = self.failures.get(model, 0) + 1
self.failures[model] = count
if count >= self.trip_after:
self.blocked_until[model] = now + self.cool_down
continue
self.failures[model] = 0
return model, answer, tried
raise ProviderError("no model available: " + "; ".join(tried), False)
def fake_call(model, prompt, now):
if model == "small-a" and now < 25: # an outage that ends
raise ProviderError("timeout", retryable=True)
if "forbidden" in prompt:
raise ProviderError("invalid request", retryable=False)
return "done"
if __name__ == "__main__":
router = Router(fake_call)
for now in (0, 5, 10, 45):
model, _, notes = router.send("classify", "label this", now)
print(f"t={now:>2}s answered by {model} {notes or ''}")
try:
router.send("classify", "forbidden content", 50)
except ProviderError as error:
print("t=50s not retried elsewhere:", error)
Output:
t= 0s answered by small-b ['small-a: timeout']
t= 5s answered by small-b ['small-a: timeout']
t=10s answered by small-b ['small-a: skipped (cooling down)']
t=45s answered by small-a
t=50s not retried elsewhere: invalid request
At the third request the failing model is skipped, so the user does not wait for another timeout. Later it is tried again and has recovered. The invalid request is raised immediately. A production breaker also needs shared state across servers, limited trial requests during recovery and a deadline.
Beware of repeating actions
If a model call fails after your agent has already executed tools, restarting the task on a fallback model may repeat those actions. Save completed steps and results, resume from them and make tools safe to repeat. Streaming adds a case: output may stop half way after part has been shown. Decide whether to restart visibly or report the interruption. See Reliable Tool Execution and Error Recovery.
A fallback is a different system
- Prompts that work on one model may not work on another.
- Tool calling, structured output and context limits differ.
- Conversation history may contain provider-specific blocks.
- Data terms and processing location may differ.
Therefore run the test set against each fallback, with its own prompt if needed, and list which routes each data class may use. If no approved model is available, failing clearly is better than sending data somewhere forbidden.
What a gateway does
| Capability | Why it helps |
|---|---|
| Central credentials | Applications never hold provider keys |
| Per-team budgets and limits | One project cannot consume everything |
| Usage records | Cost can be attributed |
| Model allow-lists | Policy is applied in one place |
| Routing and fallback | Consistent resilience |
| Caching | Saves repeated work, with care about privacy |
Choosing timeouts and attempts
A timeout that is too short cancels work that would have succeeded, and you may still be charged for it. One that is too long leaves users waiting while a healthy fallback sits idle. Base the values on measured response times for each model and request size, with a margin, and review them when models change.
| Setting | Question to ask |
|---|---|
| Connection timeout | How quickly should an unreachable service be given up? |
| Time to first output | When does a silent stream count as stuck? |
| Total call timeout | What is the longest useful wait for this request class? |
| Attempts per model | Do retries fit inside the task deadline? |
| Task deadline | When is a late answer worthless to the user? |
| Breaker threshold and pause | How many failures signal an outage, and how soon should we probe? |
Add randomness to retry delays so that many clients do not return at the same moment. Where a provider's reply tells you how long to wait, respect it. Pass the remaining time down the chain, so a later layer does not start an attempt that cannot finish.
Test these paths on purpose. Inject delays, errors and rate limits in a test environment and confirm that the user sees a sensible result, that the records show which model answered and that spending stays within bounds. A fallback that has never been exercised should be assumed not to work.
A LiteLLM pattern
LiteLLM is an open-source library and proxy server that presents many providers through one interface. Its documentation describes fallbacks for automatic failover, set either on the Python Router or under router_settings, alongside retries and cool-downs. This example uses mock replies, so it needs the library but no key. The first model is made to report a rate limit.
"""LiteLLM Router with a fallback, using mock replies so no key is needed."""
from litellm import Router
router = Router(
model_list=[
{"model_name": "primary", # the name your code uses
"litellm_params": {"model": "openai/model-one", "api_key": "unused",
"mock_response": "litellm.RateLimitError"}},
{"model_name": "backup",
"litellm_params": {"model": "openai/model-two", "api_key": "unused",
"mock_response": "answer from the backup"}},
],
fallbacks=[{"primary": ["backup"]}],
num_retries=0,
)
reply = router.completion(
model="primary",
messages=[{"role": "user", "content": "hello"}],
)
print("asked for: primary")
print("reply: ", reply.choices[0].message.content)
Output from our test run:
asked for: primary
reply: answer from the backup
As a proxy, the same idea is written in configuration. Replace the placeholders with models you are licensed to use.
model_list:
- model_name: primary
litellm_params:
model: PROVIDER/MODEL-ONE
api_key: os.environ/PRIMARY_API_KEY
- model_name: backup
litellm_params:
model: PROVIDER/MODEL-TWO
api_key: os.environ/BACKUP_API_KEY
router_settings:
num_retries: 2
fallbacks: [{"primary": ["backup"]}]
Pin the version you deploy, read release notes before upgrading and treat the gateway as security-critical software, since it holds every provider credential.
Routing for cost
Savings come from sending each request to the least expensive path that handles it well. Measure before and after.
| Technique | Check |
|---|---|
| Small model for easy classes | Quality per class, not only overall |
| Cascade with verification | How often errors pass the verifier |
| Provider prompt caching | Stable prefix; cache hit figures |
| Batch processing for non-urgent work | Completion time acceptable |
| Response cache | Keys include user, permissions and data version |
The cache warning matters: returning one user's cached answer to another is a data leak. Count the router's own cost, and the cost of escalations, in the comparison. Reducing Tokens, Tool Calls and Spend goes further.
What to record for each call
When someone asks why an answer was poor or a bill was high, a small record per call usually answers the question: task identifier, request class, router version, model asked for, model that answered, attempt number, token counts, duration, stop reason and error type. Keep content separate, protected and short-lived, or leave it out. With these fields you can chart cost by route, see which model fails most and reconstruct a single task from start to finish. They also let you check that restricted data classes only ever reached approved destinations, which is a useful automated alert.
Compare gateways
| Type | Examples to investigate | Consider when |
|---|---|---|
| Self-hosted proxy | LiteLLM proxy | You want control of data path and rules and can operate it |
| API management gateway with AI features | Kong AI Gateway and similar | Your organization already runs one |
| Cloud or edge service | Cloudflare AI Gateway, cloud provider offerings | You prefer a managed service |
| Library only | Router in your application | One team, few providers |
These are examples, not recommendations, and features change, so verify against current documentation. Score each on provider coverage, preservation of provider features, added delay, identity and audit, data handling, behavior when it fails and the ease of leaving.
Operate the gateway
- More than one instance, and a plan for gateway failure.
- Short-lived or scoped keys per application, rotated and revocable.
- Logs that record route and model, without storing more content than needed.
- Alerts on error rate, fallback rate, latency and spend.
- Configuration changes reviewed, tested and reversible.
- Regular drills that disable a provider in a test environment.
Watch the fallback rate in particular. A fallback that succeeds quietly can hide an outage for days while quality or cost drifts.
Introducing routing step by step
- Measure the baseline. One model: quality, time, cost and error rate on your test set and in production.
- Add logging. Record task class, model, tokens, duration and outcome for every call.
- Find the opportunity. Identify a large class of requests where a smaller model passes the same cases.
- Shadow it. Send copies to the candidate without showing its output, where data rules allow, and compare.
- Release a share. Route a small percentage, watch quality signals and widen gradually.
- Keep the switch. One configuration change must restore the previous routing.
Run the comparison long enough to see unusual requests, not only the busy common ones. When a provider releases a new model, the same steps apply. Promotion, Feature Flags, Rollback and Drift describes releases in more detail.
Caching without surprises
Two very different features share the word cache. A provider's prompt cache reuses processing of a repeated beginning of a request; the model still generates a fresh reply. A response cache returns a stored reply without calling the model, sometimes matching by similarity of meaning. The second can answer a different question than the one asked, serve facts that are out of date or cross a permission boundary. Use it only where answers are the same for everyone entitled to ask, expire entries when source data changes and exclude anything personal or action-triggering. Measure wrong-hit cases as carefully as the savings.
Frequently asked questions
Do small projects need a gateway?
Usually not. A function that calls the model with a timeout, a retry limit and usage logging is enough until several teams or providers are involved.
Can a model choose its own model?
It can suggest escalation, but limits and the list of permitted models should be set in code.
Does an OpenAI-compatible interface make models interchangeable?
It makes the request shape similar. Behavior and feature support still differ and need testing.
Should the fallback be the same provider?
A second model from the same provider helps with model-specific problems, not with a provider-wide outage. Choose according to the failure you are protecting against.
References and further reading
- LiteLLM documentation: Proxy fallbacks
- LiteLLM documentation: Router and load balancing
- Kong Gateway documentation
- Cloudflare AI Gateway documentation
Next steps
Workflow Versioning, Testing and Resilience
Extend resilience across the whole workflow.
Agent FinOps, Budgets and Chargeback
Budget and attribute model spend.
What to Measure: Metrics, Dashboards and SLOs
See what your routes are doing.