LLM Gateway Architecture: Reliability, Policy, and Provider Abstraction
Design an LLM gateway that preserves capability contracts, normalizes errors, bounds retries, handles streaming, and records policy-aware routing decisions.
Abhishek Raj · · 8 min read
Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.
An LLM gateway is a policy and protocol boundary between an application and model providers. It can centralize credentials, admission control, routing, and telemetry. Its harder responsibility is preserving meaning when providers expose different capabilities and failure behavior. A request that reaches another endpoint is not necessarily an equivalent request.
This guide develops a hypothetical gateway for a document-review application. The contracts, timings, and operational rules below are proposed designs, not a tested implementation or a claim about any provider's performance.
Separate the control plane from request execution
The control plane defines approved models, deployment locations, caller permissions, budgets, and adapter versions. The execution path evaluates a particular request against a snapshot of that configuration. Keeping these responsibilities distinct makes it possible to explain why a request used a deployment even after routing policy changes.
LiteLLM's documented request lifecycle provides a concrete gateway implementation: authentication and budget checks precede rate limiting and routing, then a translation layer calls the provider. Its router separates retries within a model group from fallbacks to another group. These are implementation-specific mechanics, not proof that all model groups are interchangeable. LiteLLM request architecture.
In the proposed design, each accepted request records a policy revision, adapter revision, resolved model identity, and authorized candidate set. A control-plane update creates a new revision rather than mutating the interpretation of an already admitted request. Emergency denial rules can override that snapshot when continuing would violate access or data-handling policy.
Avoid a single unrestricted administrator endpoint in the data path. A compromised application credential should not be able to change its own routing permissions or replace the provider credentials used by other applications.
Normalize the envelope without erasing capabilities
A common request shape simplifies application code. It should not pretend that every parameter has identical semantics everywhere. Maintain a capability description for each approved deployment: supported input modalities, tool-call behavior, structured-output support, context limits, streaming events, and supported controls.
For this illustrative interface, distinguish three parameter classes:
| Class | Example | Proposed gateway behavior |
|---|---|---|
| Required capability | Validated structured output | Reject candidates that cannot meet the contract |
| Explicit preference | Lower latency within the permitted model set | Optimize only after eligibility checks |
| Provider extension | A provider-specific generation control | Pass through only to an adapter that understands it |
Do not silently discard an unsupported requirement. If the application requires schema-constrained output and a candidate only supports free-form generation, converting the request into a natural-language formatting instruction changes the contract. Return a capability error or require an explicitly evaluated alternative.
Even accepted controls may not produce equivalent distributions across models. A shared field name is an API convenience, not a quality guarantee. Evaluate the application behavior of each permitted combination, using the principles in structured-output validation.
Make normalized errors actionable
HTTP status alone cannot tell an agent whether to correct arguments, wait, stop, or reconcile an uncertain operation. Preserve the original provider status and safe diagnostic identifiers while presenting a stable application error class.
RFC 9457 defines machine-readable problem details for HTTP APIs, including a problem type identifier and occurrence-specific information. Its security discussion cautions against exposing implementation details unnecessarily. A gateway can adopt that format while defining its own documented error types; the RFC does not prescribe LLM retry policy. RFC 9457.
A proposed taxonomy might distinguish invalid_request, capability_unavailable, admission_rejected, provider_unavailable, policy_denied, and stream_incomplete. Attach a retry classification derived from the actual failure, rather than allowing the caller to treat every error as retryable.
Keep policy rejection separate from temporary provider failure. Falling back to bypass a refusal or authorization decision is not ordinary availability recovery. The alternative deployment must remain within the same approved policy boundary, and the product must explicitly define whether that response category permits another attempt.
An error report should also distinguish known usage from estimated or unavailable usage. A timeout may leave billing uncertain. Reporting zero cost simply because no final response arrived understates consumption and can undermine budget enforcement.
Give one layer ownership of retry budgets
Retries can occur in the client SDK, gateway, service proxy, and workflow engine. If every layer independently permits several attempts, the combined behavior can exceed the intended cost and deadline without any layer appearing misconfigured in isolation.
Envoy documents that its outer route timeout includes retries and backoff, while a per-try timeout can limit an individual attempt. That distinction is useful for gateway design even when Envoy is not the chosen proxy. Envoy router documentation.
For the hypothetical document-review service, assign the gateway ownership of model transport retries. The application supplies an absolute deadline and maximum attempt budget. The gateway reserves enough time for response validation and refuses to begin an attempt that cannot fit its remaining allowance. Disable redundant retries elsewhere or account for them explicitly.
Retry eligibility depends on what happened, not just elapsed time. A connection failure before request transmission differs from an interrupted stream after substantial generation. Likewise, provider-side tools or stateful operations can make repetition more consequential than another stateless text-generation call. Define recovery with the relevant endpoint contract. See agent retries and timeouts for the broader workflow implications.
Preserve stream completion as an explicit outcome
An HTTP success response can establish a streaming connection before generation finishes. The application still needs to distinguish partial text, complete content, a tool proposal, a refusal, and an interrupted generation.
Anthropic's streaming documentation describes a sequence of message and content-block events, including a final message-stop event. It also documents error events and content-specific recovery limits. A gateway adapter must interpret that provider protocol rather than equate a closed connection with successful completion. Claude streaming documentation.
In the proposed normalized stream, use events such as response_started, content_delta, tool_proposal_complete, response_completed, and response_failed. These are illustrative names, not a standard. A completed tool proposal means its arguments are available for validation; it does not authorize the application to execute the tool.
Once content has been sent to the user, automatic failover can create incoherent answers: half a response from one model followed by another model's independent continuation. Choose a documented product behavior. For example, mark the attempt incomplete and offer a fresh answer, or buffer a bounded result until validation completes. Do not splice streams invisibly.
Walk through a hypothetical failover decision
Assume a reviewer requests a structured summary of a confidential contract. The application's policy permits two deployments in an approved region. Only one supports the required output contract under the gateway's evaluated adapter configuration.
The gateway authenticates the application, attaches its server-controlled tenant identity, reserves a hypothetical consumption allowance, and records policy revision 12. It selects the eligible deployment. The provider returns a temporary availability error before any response content reaches the caller.
The second deployment is healthy but cannot meet the required structure. The gateway should not choose it merely to improve the availability metric. It returns a documented capability-constrained failure, releases or reconciles the reservation according to known usage, and preserves the trace identifiers needed for investigation.
Now change the example: both deployments meet the required capabilities and policy. A fallback may be allowed if it fits the remaining deadline and attempt budget. Record the fallback reason and actual model used. Whether its summary is acceptable remains an application evaluation question, not something the gateway can infer from a successful transport response. Model-routing decisions covers that separate quality policy.
Observe attempts and outcomes separately
Create one logical request identifier and separate identifiers for provider attempts. Record queue time, routing time, time to first content, total duration, terminal outcome, and usage certainty. Store the routing policy revision and selected adapter so an incident can be reproduced at the configuration level.
Track logical-request success as well as per-attempt errors. A request that succeeds after three failures consumes different capacity from a request that succeeds immediately. Conversely, counting a partial stream as success can make a failing product look healthy.
Apply deliberate data minimization. Operational dashboards usually need outcome categories and identifiers, not complete contract text. Protect diagnostic payloads with separate access controls and retention rules. A centralized gateway concentrates both credentials and sensitive traffic, so its observability system must not become an uncontrolled copy of every application's data.
Validate the abstraction before broad adoption
Build adapter conformance cases for supported message roles, multimodal inputs, tool proposals, structured results, refusals, usage fields, and stream termination. Include unsupported parameters and malformed provider responses. Assert that rejected requirements remain rejected rather than disappearing during translation.
Exercise failures across the entire path: a caller cancels while queued, a policy changes before dispatch, the provider sends partial content then fails, the usage record arrives late, and the gateway restarts during settlement. Inspect both the client-visible outcome and the accounting ledger.
Finally, evaluate each permitted fallback on representative application tasks. A gateway can establish consistent transport and policy behavior while model quality still differs. Treat provider abstraction as an explicitly bounded compatibility contract, with documented differences and an escape hatch for applications that need native capabilities.
Frequently asked questions
Does a shared endpoint eliminate provider lock-in?
It reduces some integration work. Tool semantics, evaluation data, stateful features, and operational procedures can still tie an application to a provider. Keep those dependencies visible rather than treating endpoint compatibility as full portability.
Should the gateway choose the cheapest model automatically?
Only within an approved, evaluated candidate set and a documented routing policy. Price alone cannot establish that a model meets task quality, capability, location, or confidentiality requirements.
Can the gateway validate every generated answer?
It can enforce shared structural and transport contracts. Domain-specific correctness usually needs application evidence, business rules, and task evaluations. Keep that ownership explicit so centralization does not create a false assurance of correctness.
Source reference list
Related reading
- LLM Model Routing: Quality, Cost, and Fallback Decisions
Design LLM routing policies around eligible models, task quality, full cascade costs, calibrated acceptance gates, and bounded operational fallback behavior.
- AI Agent Retries and Timeouts: Deadlines, Jitter, and Retry Budgets
Design AI agent retries around end-to-end deadlines, classified failures, jitter, shared budgets, and cancellation without multiplying unsafe side effects.
- Structured LLM Outputs: JSON Schema and Semantic Validation
Validate structured LLM outputs beyond JSON syntax with evidence checks, domain rules, refusal handling, bounded retries, and explicit action boundaries.