Building a Multi-Model Invocation Gateway: Architecture and Practices
This article explains how a unified model invocation gateway absorbs the structural complexity of calling multiple LLM providers. It covers the layered architecture, a unified request model, routing and scoring strategies, failover and degradation, caching and cost control, heterogeneous compute abstraction, observability and SLAs, release workflows, and common anti-patterns to avoid.
1. The Problem: Structural Complexity in the Multi-Model Era
When an organization moves from calling one model to calling many models at once, complexity does not grow linearly. It expands along three dimensions at the same time: provider API differences, the pace of model version iteration, and differences in compute and deployment form.
API differences show up in authentication methods, request body structures, streaming response formats, error code semantics, and rate limiting policies. Version iteration means that model capability boundaries and parameter conventions keep changing, and a model that was usable yesterday may already be retired today. Compute differences come from the reality that public cloud managed services, self-hosted inference clusters, and heterogeneous accelerator cards coexist.
If every business team wraps its own invocation logic, the end result is a hard-to-maintain web of dependencies: credentials scattered everywhere, inconsistent retry policies, failures that cannot be contained centrally, and bills that cannot be attributed. A unified Model Invocation Gateway exists to converge this horizontal complexity in one place.
2. Goals and Non-Goals
Defining boundaries clearly is the first step of the design.
The goals are: hide provider differences behind a unified interface; route traffic and provide failover across multiple providers; reduce per-call cost through caching and scheduling; provide observability and tenant-level quotas; and hide differences in underlying heterogeneous compute.
The non-goals are: not replacing the business side’s judgment on prompt engineering and quality evaluation; not promising absolute consistency of model output quality; and not carrying business state inside the gateway. Writing the non-goals down prevents the gateway from gradually degrading into a monolith that absorbs everything.
3. Layered Architecture
A mature gateway is usually split into five layers, top to bottom: the access layer, the protocol adaptation layer, the routing decision layer, the execution layer, and the governance layer.
The access layer handles tenant identification, authentication, rate limiting, and quota deduction, and exposes only one stable interface contract externally. The protocol adaptation layer maintains bidirectional mapping between the “unified request model” and each provider’s “native request model”, and is the key place where differences get absorbed. The routing decision layer picks a target backend based on cost, latency, availability, region, and tenant policy. The execution layer handles actual forwarding, stream forwarding, timeouts, and retries. The governance layer collects metrics, logs, traces, and billing data, and drives policy adjustments.
The unified request model can be abstracted as the structure below; field names can be adjusted to follow team conventions:
{"model": "chat-general-purpose","messages": [{"role": "user", "content": "..."}],"parameters": {"temperature": 0.7, "max_tokens": 1024},"stream": true,"routing_hint": {"prefer": "low_cost", "region": "cn-north"}}
The adaptation layer needs to handle three typical mismatches: differences in roles and message structures, differences in the value ranges of sampling parameters, and differences in streaming chunk formats. The engineering recommendation is to maintain a declarative adaptation description for each backend instead of writing the mapping logic as scattered if-else blocks.
4. Routing Strategies
Routing is essentially constrained selection among multiple candidate backends. Common strategies can be combined:
- Weighted routing: distribute traffic by capacity and cost ratio, suitable for canary releases and capacity planning.
- Latency-first: select backends based on tail latency measured over a sliding window, avoiding being misled by averages.
- Cost-first: choose the cheaper channel while quality constraints are satisfied.
- Affinity routing: keep the same backend for sessions with the same prefix, improving cache hit rates.
- Region and compliance routing: ensure data does not leave a specific region, meeting compliance requirements.
The decision logic can be simplified into a scoring function:
score = w1 * availability + w2 * (1 - normalized_latency)+ w3 * (1 - normalized_cost) + w4 * cache_affinitysubject to: compliance_region == tenant_region
Weights should not be hardcoded; they should be delivered as tenant-level configuration and support hot updates. Routing decisions must be explainable: every request should record the candidate set, the final choice, and the reasons candidates were eliminated, otherwise production issues cannot be reconstructed after the fact.
5. Failover and Degradation
Failover needs to distinguish three kinds of failures: connection failures, timeouts, and responses that are semantically unusable. The first two are handled by retries and switching; the third requires content-level validation and fallback.
The recommended retry principle is “limited attempts, with jitter, idempotency-safe”. For non-idempotent generation requests, retries should be paired with a request deduplication key to avoid duplicate billing and duplicate side effects. Circuit breakers should be configured independently per backend so a single point of failure does not spread into a global avalanche. The degradation path should have at least three levels: if the primary channel fails, switch to a backup provider; if all providers are unavailable, switch to a backup model with fewer parameters; if that still fails, return a structured error and preserve the context for the business side to replay.
def invoke(req, candidates):for backend in order_by_score(candidates, req):if breaker.is_open(backend):continuetry:resp = backend.call(req, timeout=backend.timeout)if not validator.usable(resp):raise UnusableResponse()return respexcept (ConnError, Timeout, UnusableResponse) as e:breaker.record_failure(backend, e)metrics.inc("gateway_fallback_total", tags={"backend": backend})return fallback.reply(req)
6. Caching and Cost Control
In the cost structure of generation calls, the share of duplicate and similar requests is often underestimated. Caching should be layered: exact caching keyed on a normalized request fingerprint; semantic caching that matches historical results by vector similarity, which requires a similarity threshold and a manual sampling review mechanism; and prefix caching that reuses the computed common prefix of long prompts, which can significantly reduce repeated input cost.
Cost control also needs three supporting pieces: tenant-level quotas and budget alerts, tag-based billing attribution, and capacity forecasting based on historical calls. It is worth stressing that any cost advantage should come from verifiable engineering means, such as higher compute utilization, less idle spinning, and higher cache hit rates, rather than from claims that cannot be checked.
7. Heterogeneous Compute and Adaptation
When an inference cluster contains several kinds of accelerator cards, the gateway needs a compute abstraction layer on top. The key points are: use a unified device abstraction to hide differences in memory and operators across accelerator cards; improve single-card multi-tenant utilization through virtualization and partitioning; turn model and runtime compatibility into a queryable configuration matrix, avoiding hidden failures where “the model loads but an operator is unsupported”; and include memory requirements, batch size, and card capability as constraints during scheduling.
The adaptation process should be standardized into four steps: architecture research and an operator checklist review, quantization and precision baseline evaluation, load and long-run stability testing, and canary rollout. Fixing the process is what compresses the launch cycle of a new model from weeks to hours or the same day.
8. Observability and SLA
Observability requires three kinds of data working together: metrics for throughput, error rate, per-backend latency distribution, and cache hit rate; logs that retain request fingerprints and routing decisions; and traces that connect the gateway, the adaptation layer, and backend calls with a unified identifier. An SLA should be defined as measurable service objectives, such as the ratio of successful responses and response latency percentiles, backed by error budgets and tiered alerting.
9. Release Process and Consistency
Model version switches should be as transparent to the business as possible: the endpoint and credentials stay stable, and only the model identifier switches the backend; canary switches, dual-run comparison, and one-click rollback should also be provided. Version retirement needs advance notice and a replacement mapping to avoid hard cutovers that interrupt business.
10. Common Anti-Patterns
One is writing adaptation logic into business code, so every model change requires business changes. A second is retries with no limit and no deduplication, which amplifies both failures and bills. A third is using only average latency as the routing basis. A fourth is cache keys that are not normalized, keeping hit rates low over time. A fifth is missing tenant-level quotas, letting one team’s abnormal traffic drag down the whole system. Avoiding these problems costs far less than fixing them afterward.
