Skip to content

Route model traffic through a platform boundary

11 min reading

A gateway design with provider continuity, budgets, cache validity and policy scope

Page details

System Design · Optional AI architectures

11 min reading · 26 min with practice

Sources

Published · Last edited:

Prerequisite: Evaluate and observe changing AI systems. For basics, use the independent System Design foundations.

More
20px

Hypothetical scenario. Several Northwind teams use model endpoints. Dev adds a shared gateway with automatic fallback. Priya places restricted documents in a request and asks whether the backup route is permitted to receive them under the same task contract.

Dev: “The alternative endpoint can accept the request.”

Maya: “Compatibility and permission are separate conditions. Which evidence establishes both?”

Define the gateway’s identity, routing, reservation, reuse and provider-continuity responsibilities. Keep application evidence and business-action approval outside claims the gateway cannot establish. Shared infrastructure concentrates enforcement, but also makes the scope of a mistaken rule important.

Background for this lesson

Your outcome is a model gateway contract covering identity, routing compatibility, reservations, reuse and provider continuity. Prerequisites are optional serving, assistant, agent and evaluation pages; review the GenAI gateway chapter if model-specific request and response differences are unfamiliar. The gateway does not replace the application’s evidence or action authority. It owns the checks it can actually enforce at the request boundary.

Which task and data scope may this route serve?

A gateway request carries authenticated tenant and application identity, task class, approved data scope, deadline and relevant execution limits. The route selects only deployments permitted for that class. Provider credentials remain inside the controlled boundary rather than being distributed across every application worker.

Separate user-supplied labels from authenticated policy. A caller cannot obtain a privileged route by changing a request field that claims to be an administrator. Resolve route permission from a trusted identity and current configuration. Record which policy version and deployment actually handled the request.

A unified API shape can reduce integration effort without making model behaviors equivalent. Tokenization, context limits, structured outputs, tool formats and safety behavior can differ. An adapter should expose unsupported semantics explicitly rather than silently dropping constraints that the application relies on.

Fallback is a new execution choice

Maintain an approved fallback set for each task class and data scope. A reachable backup is not enough: it needs compatible capability, authorized data handling and relevant evaluation evidence. If those conditions are absent, return a declared unavailable outcome instead of sending sensitive context to an arbitrary endpoint.

Use one shared retry and deadline budget across gateway, SDK and application. Otherwise nested retries can multiply requests while the user sees a single attempt. A timeout may also leave generated work running or billed upstream. Preserve provider request identity where available and account for uncertain usage according to the reservation contract.

Streaming makes fallback more visible. Once partial output reaches a user or downstream parser, stitching another model’s continuation onto it can create an incoherent result. Choose an explicit restart, failure or resumable protocol with supported semantics. A gateway cannot pretend that an interrupted tool proposal is a confirmed action.

Only compatible authorized routes enter the fallback setIdentity, scope and budget constrain the approved provider route set. Fallback shares the deadline and retry budget. Outcome and usage records identify the actual deployment without granting business-action authority.Tenant + task classData scope + deadlineBudget reservationApproved route setProvider capabilityShared retry budgetVersioned outcomeUsage settlementNo hidden action authority
Only compatible authorized routes enter the fallback set

Reserve shared exposure before provider dispatch

Hypothetical scenario. A gateway admits request K only after identity, route eligibility and budget reservation succeed. The reservation belongs to one operation and its bounded provider attempts. Two gateway replicas must not both spend the same remaining global allowance after independent reads.

Reserve shared exposure before provider dispatch — selected design evidence
Ledger recordFieldsTransition
ReservationK, scope, maximum exposureAtomic admit / reject
Provider attemptK, route, attempt ID, usage stateDispatch under reservation
Settlementknown usage or unknown obligationRelease only resolved allowance
Policy generationeligible routes, validityValidated serving input
The reservation exists before external exposure and remains accountable if the provider reply is lost.The reservation exists before external exposure and remains accountable if the provider reply is lost. Gateway replica to Budget authority: 1 · reserve exposure for K; Budget authority to Gateway replica: 2 · grant or reject; Gateway replica to Provider: 3 · eligible attempt; Provider to Budget authority: 4 · settle known / unknown usage.Gateway replicaBudget authorityProvider1 · reserve exposure for K2 · grant or reject3 · eligible attempt4 · settle known / unknown usage
The reservation exists before external exposure and remains accountable if the provider reply is lost. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

A provider timeout can leave usage unknown. Keep the reservation pending or settle conservatively under the declared exposure rule; immediately refunding it and issuing fallback can authorize more spending than the ledger represents. A fallback also needs an eligible destination, compatible task semantics and permission to receive the selected data.

Control-plane configuration chooses allowed routes; the serving data plane uses a validated generation with explicit expiry behavior. A configuration outage need not stop all work if a valid retained policy is permitted. Conversely, the gateway must not invent permission when policy freshness expires. Cache equivalence includes tenant, request semantics, model settings and relevant evidence; equivalent strings alone are insufficient.

Reserve before dispatch and settle after evidence

Hypothetical worked example. Select one hundred admitted requests. Reserve at most two thousand input tokens and five hundred output tokens per request. Per-request allowance is 2,000 + 500 = 2,500 tokens. Aggregate initial reservation is 100 × 2,500 = 250,000 tokens. These are selected budget units, not current provider prices or a prediction of actual billing.

Suppose ninety requests use one attempt and ten use a second full-bound attempt after an uncertain first result. Maximum attempted calls for that cohort are 90 + 10 × 2 = 110. If every attempt reaches the selected allowance, the attempted-token subtotal is 110 × 2,500 = 275,000 tokens. A reservation scheme covering only initial calls is short by 275,000 − 250,000 = 25,000 tokens under this selected worst case.

The system can reserve retry headroom, reduce the allowed attempts or reject additional work. Do not count an uncertain upstream attempt as free merely because its response was lost. Settlement uses actual supported usage evidence when available and a declared pending policy when it is not.

For one request, choose a five-second total deadline. If the first route consumes three seconds and final handling reserves half a second, remaining allowance is 5 − 3 − 0.5 = 1.5 seconds. A backup requiring a selected two-second bound does not fit. The gateway must stop or return the product’s declared limitation rather than restarting a new five-second clock.

Reuse an answer only under compatible meaning and authority

An answer-cache key needs more than a similar question. Model and prompt versions, source evidence, authorization scope, relevant time context and output contract can affect validity. Semantic similarity can propose reuse candidates; it cannot establish that a response belongs to the current reader.

Source withdrawal or permission changes can invalidate reused answers even when the original model response was correct. Enforce eligibility at serving time through the selected revocation contract. A long cache lifetime is not a substitute for current authority, and a tenant identifier alone may be insufficient when users within that tenant have different access.

Prefix caching at the serving layer and answer caching at the application layer have different semantics. One reuses computation for compatible token prefixes; the other reuses an asserted result. Document which mechanism is enabled and what information it retains. Avoid describing both as the same harmless performance optimization.

In the wild: fallbacks have explicit configuration

LiteLLM documents model-group fallbacks and retry behavior. Inspect the configured error paths, ordering and timeouts before relying on them. A configured backup is an execution mechanism; Northwind must still establish that it is permitted and evaluated for the task.

Keep policy-as-configuration changes reviewable. Disabling a provider, changing a route or modifying a cache rule can alter every application using that path. Stage those changes with known request classes and preserve the previous compatible configuration for rollback. A successful connectivity check does not evaluate answer quality or data eligibility.

Availability is restored by crossing the wrong boundary

Hypothetical failure scenario. The primary private endpoint is unavailable. The gateway routes a confidential policy request to a public backup because the fallback list was shared across all tenants. The request succeeds operationally while violating its approved processing scope.

Stop the unauthorized path, preserve request and route evidence under restricted access, and assess the disclosure. Restore only routes authorized for that scope. A generic retry rule must not override residency, confidentiality or capability requirements. The correct immediate product outcome may be a temporary limitation.

Centralization creates an operational dependency

The gateway adds a shared availability and policy boundary. Scale and recover it according to its actual workload, and avoid making a remote configuration service a fragile synchronous dependency without a declared fallback. Cached policy itself needs a validity rule; continuing indefinitely with obsolete permission is not resilient governance.

Applications still validate business effects and supported claims. The gateway cannot determine that a cited passage supports an answer merely by seeing a successful model response. It can provide route, timing and usage evidence to the application’s evaluator. The next page follows one complete enterprise request through all these authorities and tests a changed requirement.

Challenge the proposed mechanism

Unknown usage remains an obligation rather than becoming immediately reusable allowance.Unknown usage remains an obligation rather than becoming immediately reusable allowance. Reserved K to Provider usage unknown: timeout after dispatch; Provider usage unknown to Settled evidence: conclusive usage / declared accounting.Reserved KProvider usageunknownSettled evidencetimeout after dispatchconclusive usage / declared accounting
Unknown usage remains an obligation rather than becoming immediately reusable allowance. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

The provider times out and the budget store partitions. Can the gateway refund locally and try any fallback?

Reveal the design reasoning

No. Use only preauthorized bounded grants and eligible routes, retaining unresolved exposure. Otherwise return unavailable. Preserve K and reconcile provider usage later; local optimism cannot establish a shared budget.

Decision and reconsideration: Bound authorized exposure across timeout and fallback. Separate route configuration availability from budget and disclosure authority.

Check the design against changed conditions

  1. The backup endpoint is healthy. May every failed primary request use it?

    Reason through the consequence

    Only if the backup is authorized for the task’s data scope, supports the required semantics and has relevant evaluation evidence. Reachability alone is insufficient.

  2. One hundred requests reserve 250,000 tokens, but ten need full-bound retries. Is the initial reservation enough?

    Reason through the consequence

    Not under the selected worst case. One hundred ten attempts can require 275,000 token units, so reserve retry headroom or constrain additional work.

  3. The first route consumed three seconds of five. Can the fallback start a fresh five-second deadline?

    Reason through the consequence

    No under the shared deadline contract. With half a second reserved for final handling, only 1.5 seconds remain for the fallback.

The gateway joins serving, evidence and execution without merging their authorities. Page 66 reviews that complete path under a permission change while a request waits for another route.

Northwind decision log

Route only through compatible deployments authorized for the data scope.
Share retry, deadline and reservation budgets across attempts.
Next, defend the integrated platform across every authority boundary.

Go deeper: Routing and operational control