Building a Unified Gateway for Multi-Model LLM Calls: Architecture and Practices
This article explains how to build a unified model invocation gateway that abstracts away backend LLM differences behind a stable contract. It covers the five-layer architecture, the intermediate representation (IR) for request normalization, multi-signal routing strategies, failover and degradation design, caching and cost optimization, heterogeneous accelerator adaptation, observability and metering, and a standardized onboarding flow for new models. The goal is to turn model capabilities into governed infrastructure while keeping business code decoupled from specific providers.
1. The Problem: The Cost of Calling Multiple Models
As large models evolve quickly, enterprises rarely stay locked to a single model provider for long. Different tasks call for different strengths: reasoning workloads prioritize low latency, long-context workloads need larger context windows, and batch offline jobs care about cost per unit. Engineering teams face a different set of problems: every provider has its own authentication scheme, request fields, streaming protocol, and error-code semantics, which forces business code to couple tightly with a specific vendor.
The typical pain points fall into four categories:
- Fragmented interfaces: request and response structures vary widely across providers, making switching expensive.
- Stability risk: single points of failure, rate limiting, and regional instability directly affect availability.
- Uncontrolled cost: without unified metering and observability, it is hard to trace where spend comes from.
- Difficult heterogeneous compute adaptation: domestic accelerators and general-purpose GPUs differ in operator support and memory management.
A unified model invocation gateway (discussed here from a general architecture perspective, not tied to any specific vendor product) is the layer of infrastructure designed to consolidate these problems.
2. Goals and Non-Goals
Defining boundaries is the first step in the design.
Goals:
- Hide backend differences behind a single stable external contract.
- Provide cross-cutting capabilities such as routing, failover, rate limiting, and metering.
- Make onboarding a new model or provider approach a configuration task.
- Keep external behavior consistent across heterogeneous compute.
Non-goals:
- Owning the full model training and fine-tuning lifecycle.
- Replacing the business side’s prompt management and evaluation systems.
- Ranking specific model capabilities subjectively.
3. Layered Architecture
A gateway that can actually ship is usually split into five layers:
- Access layer: protocol termination, authentication, tenant identification, quota checks.
- Abstraction layer: a unified request/response model (IR) that hides field differences.
- Decision layer: routing policy, canary, weights, and regional affinity.
- Execution layer: adapters that call backends and handle streaming and timeouts.
- Observability layer: logs, metrics, tracing, and metering.
The core of the abstraction layer is the intermediate representation. Business code programs only against the IR, and adapters handle bidirectional translation:
Business request (unified IR) -> routing decision -> provider adapter -> backend modelBusiness response (unified IR) <- normalized parsing <- streaming/batch response
A sketch of a unified request structure (pseudocode):
@dataclassclass ChatRequest:model_alias: str # logical model name, not a specific backend modelmessages: list[Message]temperature: float | None = Nonemax_tokens: int | None = Nonestream: bool = Falseextra: dict = field(default_factory=dict) # pass-through for provider-specific params
Collecting provider-specific parameters into extra preserves extensibility while avoiding pollution of the main contract.
4. Intelligent Routing: From Rules to Policy
Routing is not simple random or round-robin selection; it should decide based on multiple signals:
- Capability: context length, multimodal support, function-calling support.
- Cost: unit price per backend and cache-hit conditions.
- Performance: real-time latency percentiles, throughput, error rate.
- Stability: circuit-breaker state, remaining quota, regional health.
A recommended approach is a two-stage “weighted scoring plus constraint filtering”: first filter the candidate set by hard constraints (capability, compliance, region), then score by weight within the candidates. Weights can be a static baseline combined with dynamic feedback:
score = w1 * (1 / p95_latency)+ w2 * (1 / unit_cost)+ w3 * cache_hit_rate- w4 * error_rate
Canary and experiments should also live in this layer: split by tenant, by traffic percentage, or by request characteristics, so a new model can be rolled back quickly after launch.
5. Failover and Degradation Design
High availability relies on three layers of protection:
- Retry: retry only idempotent errors judged to be transient, using exponential backoff with jitter to avoid retry storms.
- Circuit breaking: triggered by error rate and timeout rate over a sliding window, with a half-open state probing for recovery.
- Degradation: in priority order, switch across providers with the same capability, switch across regions, fall back to a smaller model, or return a cached result or an explicit degradation flag.
It is important to stress that degradation must carry an observable flag in the response, so the business side does not treat a fallback result as a normal one.
{"data": { "...": "response in unified structure" },"meta": {"served_by": "adapter_a","degraded": true,"reason": "circuit_open_fallback"}}
6. Caching and Cost Optimization
Cost optimization cannot rely on price negotiation alone; engineering measures matter just as much:
- Semantic caching: reuse results for high-frequency, low-timeliness requests, with a similarity threshold and expiration policy.
- Prefix reuse: for requests sharing a system prompt, use backend prefix caching to cut repeated computation.
- Batching and off-peak scheduling: merge offline batches and avoid peak hours.
- Resource virtualization: improve per-card concurrency density through memory sharing and virtualization, raising compute utilization.
Cache hit rate should be monitored as a first-class metric; an abnormal drop often signals a prompt template change or a shift in traffic structure.
7. Heterogeneous Compute Adaptation
Differences between domestic accelerators and general-purpose GPUs show up mainly in operator coverage, compilation toolchains, memory management, and communication libraries. Engineering recommendations:
- Build a unified operator capability matrix, marking each model’s support on each hardware.
- Abstract a device-agnostic runtime interface, pushing differences down into backend plugins.
- Build a compatibility regression test set covering precision alignment and performance baselines.
- Provide a degradation path or graph-level replacement for unsupported operators.
A sketch of a capability declaration:
model: chat-largerequirements:min_context: 32768features: [function_call, stream]hardware_matrix:accelerator_family_a: {status: supported, precision: bf16}accelerator_family_b: {status: partial, note: "no paged_attention"}
8. Observability and Metering
Much of a unified gateway’s value shows up in being able to “see” what is happening:
- Metrics: QPS, P95/P99 latency, error rate, circuit-breaker trips, cache hit rate, per-request token metering.
- Logs: structured records of the routing decision chain, making it easy to review “why this backend was chosen.”
- Tracing: a call chain spanning the access layer to the adapter, to locate cross-system bottlenecks.
- Metering: aggregated by tenant, model alias, and feature tag, supporting cost allocation and quota policy.
9. Fast Onboarding for New Models
Models iterate quickly, so the onboarding flow must be standardized to achieve “ready on release”:
- Research: track architecture changes (attention implementation, positional encoding, vocabulary changes).
- Adapt: implement or reuse an adapter, filling in streaming and error-code mapping.
- Validate: precision alignment, load-test baseline, long-run stability testing.
- Canary: validate with small traffic, then ramp up gradually.
- Open: expose only the logical model alias externally, so business keeps the existing endpoint and credentials to switch.
The key design here is decoupling the “logical model name” from the “backend version,” so business needs no code change, only an alias switch.
10. Security and Compliance
- Centralized credential custody; the business side never touches real keys.
- Tenant-level quota and rate limits to prevent resource abuse.
- Sensitive-data masking and audit trails.
- Content-safety filtering up front, blocking violating requests before they reach the model.
11. Implementation Checklist
- Unify the contract first, optimize later: if the abstraction layer is weak, every later capability is discounted.
- Make routing policy configurable: avoid hardcoding that forces a release for every adjustment.
- Make degradation flags explicit: observable degradation is a prerequisite for correct operations.
- Metering before cost work: no metering means no optimization.
- Make the compatibility matrix a first-class artifact: heterogeneous adaptation relies on the matrix and regression, not ad hoc patches.
In short, the essence of a unified model invocation gateway is turning “model capability” into “governed infrastructure services.” When abstraction, routing, failover, caching, and adaptation are all solid, enterprises can keep business stable and costs controlled amid rapid model iteration.
