Unified LLM Gateway in Practice: Access, Routing, and Failover

    Many enterprises call multiple LLM providers and self-hosted models from the same application. Without a gateway, API integration becomes fragmented, model switching is costly, and provider failures are hard to absorb. This article explains how to design a unified LLM gateway with a layered architecture, an OpenAI-compatible API, intelligent routing, semantic and prefix caching, vGPU virtualization, and failure handling. It also covers routing metrics, circuit-breaker thresholds, cache risks, and heterogeneous accelerator adaptation.

    Why a Unified Model Gateway Is Needed

    Enterprises often consume multiple model services in the same product. Some models are strong at long-context understanding, others are more stable at code generation, and open-weight models deployed in-house can provide lower unit cost. If each business team integrates vendors directly, common problems appear:

    Problem Direct impact What the gateway provides
    Fragmented APIs Request formats, authentication, streaming protocols, and error codes differ; business code is full of adapters Unified API contract and error-code mapping
    High switching cost New models require code changes and regression testing; capability windows are missed Switch by changing only the model name; routing rules can be hot-reloaded
    Single-vendor dependency Rate limits, outages, or price changes leave the business without a fallback Multi-channel redundancy, circuit breakers, and graceful degradation
    Low compute utilization Self-hosted GPU clusters idle at times and queue at peak Virtualization and unified scheduling

    A gateway is the middle layer between business applications and model providers. It presents one stable API upward, connects to multiple vendors or self-hosted compute pools downward, and uses routing, caching, and failover to balance cost, performance, and availability. In practice, it is usually deployed as a component of an intelligent cloud platform, alongside container infrastructure, monitoring, alerting, and log services.

    Core Architecture Layers

    A typical model gateway is organized as follows:

    1. Business applications
    2. |
    3. | Unified API (OpenAI-compatible protocol is the de facto standard)
    4. v
    5. Access layer: authentication / quotas / metering
    6. |
    7. v
    8. Routing layer: intelligent routing / canary releases / circuit breaking / degradation
    9. |
    10. v
    11. Cache layer: semantic cache / prefix cache
    12. |
    13. v
    14. Execution layer: vendor API proxy / self-hosted compute pool
    15. |
    16. v
    17. Chip layer: general-purpose GPUs / domestic AI accelerators

    Each layer has a focused responsibility. The access layer handles identity and quota; the routing layer decides where a request goes; the cache layer reduces repeated computation; the execution layer connects to actual compute; and the chip layer hides hardware differences. Because responsibilities are separated, changes in one layer do not need to be visible to business applications.

    Unified API Abstraction

    The unified API is the front door of the gateway. An OpenAI-compatible /v1/chat/completions endpoint has become the default choice for many gateways. The business only needs to replace the endpoint URL and model name to switch backends:

    1. from openai import OpenAI
    2. client = OpenAI(
    3. api_key="YOUR_GATEWAY_KEY",
    4. base_url="https://gateway.example.com/v1"
    5. )
    6. resp = client.chat.completions.create(
    7. model="target-model-v1", # Change only this model name to switch backends
    8. messages=[{"role": "user", "content": "Generate API test cases"}],
    9. stream=True
    10. )

    With this approach, a new model can be used without changing business code, while the gateway handles model routing and traffic migration behind the scenes. It is important to note that compatibility only standardizes the call form. Model-specific differences in parameter ranges, tool-call formats, and context lengths still need to be normalized inside the gateway and clearly documented.

    Intelligent Routing

    The routing layer chooses a backend for each request based on multiple dimensions:

    • Cost: when quality meets requirements, prefer a lower-priced channel.
    • Performance: use recent latency and throughput data for dynamic weighting.
    • Availability: automatically break the circuit to abnormal nodes and shift traffic to standby channels.
    • Business isolation: split traffic by tenant or business line to avoid interference.

    A scoring formula can be adjusted according to business data. For example:

    • Channel score = 0.5 × quality score + 0.3 × cost score + 0.2 × latency score, where each score is normalized from 0 to 1.
    • Circuit breaker condition: in the last 60 seconds, sample count ≥ 200 and error rate > 5%, or P95 latency > half of the business timeout.
    • After the circuit is broken, the node enters a half-open state that only allows a small number of probe requests. If several consecutive probes succeed, the node recovers.

    Thresholds should be tied to SLOs. For latency-sensitive interactive dialog, tighten the P95 threshold; for batch jobs, the threshold can be more relaxed. Routing rules should be stored as configuration and support hot reload, so tuning them does not require redeploying the gateway.

    Multi-Level Caching

    Most of the cost of LLM calls comes from inference compute. A gateway can cache at two levels.

    1. Semantic caching: return a previous result for semantically similar requests. Hit rate depends on the request distribution. Q&A-heavy and template-heavy workloads usually have higher hit rates, while personalized or strongly time-sensitive workloads have much lower hit rates. Before enabling semantic cache, replay historical logs to measure actual hit rate, false hit rate, and token savings, and only then set thresholds.
    2. Prefix caching (KV cache reuse): when many requests share a long system prompt, reuse the computed KV cache to reduce first-token latency and duplicate work. The benefit depends on the length and share of the common prefix.

    Semantic caching has one clear risk: two queries can look similar but require different answers, especially when dates, account status, or permissions are involved. Those requests should be excluded from caching.

    Compute Virtualization and Heterogeneous Accelerator Adaptation

    vGPU Virtualization for Higher Utilization

    A self-hosted inference cluster often has two opposite problems: idle compute at low traffic and queuing at peak. vGPU virtualization splits a physical GPU into finer units and allocates them to inference instances on demand. The scheduler can then reclaim and reuse compute among tasks.

    When implementing this, three points matter:

    • Isolation: memory partitioning can usually provide hard isolation, while compute time slices are usually soft. If one tenant’s tasks occupy compute units for a long time, other tenants’ latency can be affected.
    • Partition granularity: finer granularity improves packing efficiency, but leaves less memory headroom per instance. Choose partition sizes based on actual model weight and KV-cache usage.
    • Scheduling overhead: virtualization and context switching add performance cost. Benchmark before launch on target models to quantify changes in throughput and latency.

    Improved utilization does not automatically mean lower cost. Whether it becomes a cost advantage depends on whether scheduling overhead is controlled and whether actual load is stable enough. Do not assume a gateway is always cheaper than direct vendor connections. Availability commitments should be based on contract terms and measured availability.

    Heterogeneous Accelerator Compatibility

    In environments with domestic silicon requirements, inference compute cannot depend on a single architecture. A common approach is to build a model adaptation system and work through each chip architecture individually.