Model Routing, Fallbacks and Gateways

Several models can be cheaper and sturdier than one, if the switching is tested.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner Routing and fallback

Three different ideas

IdeaQuestion answeredWhen it acts
RoutingWhich model should handle this?Before the call
RetryIs it worth asking the same one again?After a temporary error
FallbackWho takes over when it cannot?After retries fail or a model is unavailable
Request
RouterRules and limits
Primary modelTimeout and retry
FallbackOnly if allowed
ResultRecords who answered

Routing strategies

StrategyHow it choosesStrengthRisk
By stepEach stage of the workflow names its modelSimple and predictableCannot adapt to hard cases
By ruleLanguage, size, customer tier, data classExplainableRules grow tangled
By classifierA small model labels difficulty or topicHandles free textThe classifier can be wrong
CascadeTry cheap first; escalate if a check failsSaves money when checks are goodPays twice for hard cases; weak checks pass errors
Load balancingSpread across deployments of the same modelCapacity and resilienceDeployments 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 classPrimaryFallbackIf neither works
Label the topicSmall hosted modelSecond small modelSend to the general queue
Answer an order questionMid-sized modelLarge modelHand to a person with the details
Complaint or exceptionLarge model draftsNoneHand to a person
Contains restricted dataApproved private deploymentSecond approved deploymentStop 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.

Intermediate Reliability rules

Retry only what can succeed

FailureRetry same?Fall back?
Network error or timeoutA few times, with growing delay and randomnessYes
Rate limitAfter the indicated waitYes, if the other has capacity
Server error or overloadBrieflyYes
Invalid requestNoNo; fix it
Authentication failureNoAlert; do not hide a broken credential
Content refusalNoGenerally no; shopping for a model that agrees undermines your policy
Input too longNoShorten, 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

Applications and agentsOne interface, their own gateway keys
Model gatewayIdentity, budgets, rate limits, routing, fallback, logs, redaction
Provider A
Provider B
Self-hosted
CapabilityWhy it helps
Central credentialsApplications never hold provider keys
Per-team budgets and limitsOne project cannot consume everything
Usage recordsCost can be attributed
Model allow-listsPolicy is applied in one place
Routing and fallbackConsistent resilience
CachingSaves 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.

SettingQuestion to ask
Connection timeoutHow quickly should an unreachable service be given up?
Time to first outputWhen does a silent stream count as stuck?
Total call timeoutWhat is the longest useful wait for this request class?
Attempts per modelDo retries fit inside the task deadline?
Task deadlineWhen is a late answer worthless to the user?
Breaker threshold and pauseHow 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.

Expert LiteLLM, cost routing and operating a gateway

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.

TechniqueCheck
Small model for easy classesQuality per class, not only overall
Cascade with verificationHow often errors pass the verifier
Provider prompt cachingStable prefix; cache hit figures
Batch processing for non-urgent workCompletion time acceptable
Response cacheKeys 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

TypeExamples to investigateConsider when
Self-hosted proxyLiteLLM proxyYou want control of data path and rules and can operate it
API management gateway with AI featuresKong AI Gateway and similarYour organization already runs one
Cloud or edge serviceCloudflare AI Gateway, cloud provider offeringsYou prefer a managed service
Library onlyRouter in your applicationOne 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

  1. Measure the baseline. One model: quality, time, cost and error rate on your test set and in production.
  2. Add logging. Record task class, model, tokens, duration and outcome for every call.
  3. Find the opportunity. Identify a large class of requests where a smaller model passes the same cases.
  4. Shadow it. Send copies to the candidate without showing its output, where data rules allow, and compare.
  5. Release a share. Route a small percentage, watch quality signals and widen gradually.
  6. 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

Next steps