Routing across model providers
hard 7 minA provider gateway chooses an execution path for each request.
Video lesson · Chapter 1 of 4
An invoice almost outlives its deadline
Theory
Read or listen first. About 2 min.
What it is
A provider gateway chooses an execution path for each request. First remove routes that violate hard requirements such as data residency, supported modalities or a required structured-output contract. Then compare feasible routes using a quality estimate, remaining deadline, expected retries and price. A model that is cheap per token can be expensive per accepted invoice.
Why it exists
Keep a record of the decision and the resolved model version. Instrument attempts separately from the business task so retries count toward cost but never count as extra successful tasks. While an unhealthy route recovers, a circuit breaker limits new attempts. If no eligible route remains, the system needs an explicit deferred or human-review outcome.
A slow provider during an invoice rush
Inside this chapter
Chapter sources- Eligibility before optimization
- A router may use a learned predictor of relative model quality or simple task rules. A policy filter placed ahead of that optimization prevents an apparently cheap route from silently moving private data into a prohibited region.
Routing has two very different kinds of rule. Hard constraints (where data may be processed, which modalities a model accepts, whether it supports the required output schema, contract terms) define the set of permitted routes. Soft preferences (quality estimates, price, current latency) rank routes within that set. Applying the filter first means a mis-tuned scoring model can make a poor choice but never a prohibited one.
Example. A US-only route is healthy and inexpensive, but is absent from the candidate set for an EU-only invoice.
Another example. A healthcare chatbot tenant forbids routes without a signed data-processing agreement. A new model with excellent benchmark scores is added to the gateway, but it is absent from that tenant's candidate list until the agreement exists.
Filter first, then rank - 1Invoice requesttenant: EU only, typed amount
- 2Residency filterUS route removed
- 3Capability filterneeds structured output
- 4Two EU routes leftfast and standard
- 5Score by quality, costpick within deadline
The cheap US route never enters the scoring step, so no optimiser can choose it.
- Deadline-aware fallback
- Reserve enough time for the alternative to finish. Propagate cancellation and record whether any user-visible output or external action has already occurred. A retry after partial streaming needs an explicit continuation or replacement policy.
Each request carries an end-to-end deadline. When the first attempt fails, the gateway subtracts elapsed time and compares the remainder with the fallback's typical service time (a high percentile, not the average). If it cannot fit, a fast, honest outcome beats a late one. The first attempt must also be cancelled so it stops consuming capacity, and if any tokens already reached the user the retry needs a rule for continuing or replacing them.
Example. With 450 ms remaining, a fallback whose measured service time is 700 ms would miss the deadline even with an empty queue.
Another example. A live captioning service has 1 second per segment. After a 600 ms stall on the primary model, only fallbacks with a p95 under 400 ms remain eligible; otherwise the segment is shown as "[inaudible]" and the stream moves on.
Can the fallback still finish in time?
Numbers from the example: a 700 ms fallback cannot fit in 450 ms even with an empty queue. - Cost per accepted task
- Divide all attempt costs, including failed attempts, by the count of accepted tasks. Track the denominator by route and request type. A shift toward easy requests can otherwise look like a routing improvement.
Per-token price is an input, not the outcome. A cheap model that often fails validation triggers retries and fallbacks, and those costs belong to the tasks it was trying to complete. Track the numerator and denominator by route and request type, because a router that drifts towards easy requests can look cheaper per task without being any better.
Example. One hundred invoices cost 0.025 per accepted invoice.
Another example. Route X costs a third as much per call as route Y but passes schema validation only half the time, after which route Y is called anyway. Per accepted invoice, X-then-Y ends up more expensive than calling Y first.
Divide by accepted tasks, not attempts
Failed and retried attempts stay in the numerator. Illustrative figures from the example. - Circuit breakers per route
- A circuit breaker tracks recent failures for each provider route. When failures pass a threshold it opens and stops sending new attempts there, then after a cool-down lets a few trial requests through before closing again. This protects deadlines and avoids piling load onto a struggling provider.
Keep breakers per route and ideally per region and model, so one bad deployment does not close everything. Log every state change with the reason, since an open breaker silently shifts traffic and cost to other routes.
Example. During the invoice rush, the fast EU route fails 8 of its last 20 calls. Its breaker opens, so fresh invoices go straight to the standard EU route instead of wasting 900 ms first.
Breaker states for one route
Illustrative thresholds. Count timeouts and schema failures, not just HTTP errors. - Normalised request contract
- Callers send one gateway-level request shape (messages, tools, output schema, deadline, tenant policy). Adapters translate it per provider and translate responses back, including usage and error types, so routing can change without changing application code.
The contract is also where capability differences surface: if a provider cannot honour the output schema natively, the adapter must either validate and retry or mark the route ineligible. Normalising usage and error fields is what makes cross-provider cost and reliability dashboards possible.
Example. The invoice service always asks for
{amount, currency}with a 2-second deadline. Whether provider A or B answers, it receives the same typed object and the same error codes.JSON{ "task_id": "inv-20931", "tenant_policy": {"region": "eu", "requires_schema": true}, "deadline_ms": 2000, "messages": [{"role": "user", "content": "Extract the total from the attached receipt"}], "output_schema": {"amount": "number", "currency": "string"}}Illustrative gateway request. Provider-specific fields live only inside adapters.
How it works
Step through the idea, or press Play.
Policy filter. Two eligible EU routes
Understand it
Worked example
A slow provider during an invoice rush
- 1
Two eligible EU routes
The tenant requires EU processing and a typed amount field. A third provider fails residency and never receives the input.
- 2
Fast route has 900 ms
A fresh request takes the fast route. After a timeout the remaining budget and circuit state determine whether another attempt can still finish.
- 3
Return a typed receipt
The permitted alternative decodes the receipt under its own schema support. The gateway validates value and currency before counting the result.
- 4
Charge attempts to one invoice
Both attempts share one business ID. Record both costs, one completion and the end-to-end latency.
Follow the handoffs
One invoice, two attempts
Outcome ledger for the invoice
| Attempt | Route | Result | Counted as |
|---|---|---|---|
| 1 | Fast EU | timeout | cost only |
| 2 | Standard EU | valid typed receipt | cost and the single completion |
| Total | 1 accepted invoice | end-to-end latency includes both |
Summary
The whole topic in one minute.
A latency target cannot override the policy defining where the data may be processed.
Keep a record of the decision and the resolved model version. Instrument attempts separately from the business task so retries count toward cost but never count as extra successful tasks. While an unhealthy route recovers, a circuit breaker limits new attempts. If no eligible route remains, the system needs an explicit deferred or human-review outcome.