LLM Gateway in Practice: Multi-Model Routing and Cost Governance

    An LLM gateway turns model selection from a hard-coded dependency into a runtime, configurable policy. This article walks through how to build one: a unified request/response contract that absorbs provider differences, a four-layer routing strategy that moves from static intent routing to cost-quality tradeoffs, cross-provider failover with the reliability details that matter, token metering and cost governance, observability with a quality-evaluation loop, a security and compliance baseline, and a phased rollout plan. It explains the coupling, cost, and availability debt that direct API calls accumulate, and why the durable payoff of an aggregation layer is unified abstraction, policy routing, cost governance, and evaluation—not the subsidies.

    Why business systems need a model access layer

    Capability boundaries among large models are diverging fast. Some excel at long-document understanding and summarization, some are more reliable at code completion and tool calling, some have more complete multimodal input, and some are cheap to run and suited to high-concurrency short tasks. At the same time, a single provider’s pricing, rate-limiting policy, availability zones, and model version cadence all keep changing. The “low-price promotions” and “token subsidies” of the past two years are themselves proof that price is not a stable variable.

    If business code is full of direct calls like client.chat.completions.create(model="xxx"), three kinds of debt accumulate:

    • Coupling debt: switching models means editing business code; canary releases and rollbacks both depend on changing code branches.
    • Cost debt: without a unified token accounting basis, you can’t answer “which business line, which feature, which user segment burned how much budget.”
    • Availability debt: when a single provider rate-limits or has jitter, the business can only degrade wholesale or throw errors, with no cross-provider failover path.

    The role of a model access layer is to demote “the model” from a code dependency to a runtime-configurable policy parameter. This is also where the real technical value of “aggregation” services lies—not the subsidy itself, but the ability to hide differences and orchestrate uniformly.

    Core abstraction: absorbing provider differences with a unified contract

    The foundation of the unified layer is a normalized request/response contract. Every provider adapter implements the same interface, and the business side programs only against the contract.

    1. from dataclasses import dataclass, field
    2. from typing import Protocol, Iterator
    3. @dataclass
    4. class ChatMessage:
    5. role: str # system / user / assistant / tool
    6. content: object # str, or a list of multimodal chunks [{"type": "text", ...}, {"type": "image", ...}]
    7. @dataclass
    8. class ChatRequest:
    9. messages: list[ChatMessage]
    10. intent: str = "general" # Business intent: summary / code / extract / chat, not a specific model
    11. max_output_tokens: int = 1024
    12. temperature: float = 0.7
    13. tools: list[dict] = field(default_factory=list)
    14. response_format: str = "text" # text / json_schema
    15. stream: bool = False
    16. priority: str = "normal" # low / normal / high
    17. trace_id: str = ""
    18. @dataclass
    19. class ChatResponse:
    20. text: str
    21. tool_calls: list[dict]
    22. usage: dict # Unified naming for prompt / completion / cached / reasoning tokens
    23. provider: str
    24. latency: dict # {"ttft_ms": 0, "total_ms": 0}
    25. class LLMAdapter(Protocol):
    26. name: str
    27. capabilities: frozenset # Capability bitmap: tools / json_mode / vision / long_context / reasoning
    28. def chat(self, req: ChatRequest) -> ChatResponse: ...
    29. def stream(self, req: ChatRequest) -> Iterator[dict]: ...

    There are three key design decisions:

    1. Intent, not model ID: the business sends intent="code", and the routing layer decides which model it lands on. Model iteration then requires no code change on the business side.
    2. Capability-bitmap-driven filtering: before routing, use capabilities for hard filtering, so you avoid sending tasks that need structured output to models that don’t support it—turning “capability mismatch” from a runtime error into a configuration-time problem.
    3. Keep an escape hatch: the adapter layer allows passing through vendor-specific parameters (for example reasoning budgets, chain-of-thought toggles, sampler details). Forcing everything down to a “least common denominator” keeps new features unusable for a long time—the most common design trap of an aggregation layer.

    Routing strategy: from static mapping to cost-quality tradeoffs

    The routing layer is the brain of the whole gateway. Build it in four progressive layers.

    Layer 1: Static intent routing. Maintain a config of “intent → candidate model priority list”; the business doesn’t need to know the provider.

    1. routes:
    2. code: [model_a_pro, model_b, model_c_mini]
    3. long_doc: [model_d_long, model_a_pro]
    4. high_volume: [model_c_mini, model_b_mini]
    5. vision: [model_e_vision, model_a_pro]
    6. policies:
    7. default: {timeout_ms: 30000, retries: 2, max_fallback: 2}
    8. high: {timeout_ms: 60000, retries: 1, max_fallback: 1}

    Layer 2: Health- and quota-aware routing. At runtime, maintain each candidate’s sliding-window success rate, P95 latency, and current rate-limit headroom. Temporarily remove candidates that are circuit-broken or out of quota, and probe them with small traffic in a half-open state once they recover.

    Layer 3: Cascaded calls (cascade). First produce a result with a low-cost small model, then use a lightweight verifier (rules, confidence, a second small-model judgment) to decide whether it’s acceptable; if not, escalate to a large model. In practice, a large share of classification, extraction, and rewriting tasks can use cascading to cut cost to a fraction of a single large-model call, at the cost of one extra call’s latency—suitable for offline or near-real-time scenarios.

    Layer 4: Policy-based scheduling. Take latency budget, per-request cost cap, and tenant tier as constraints, and pick the best of multiple objectives:

    1. def choose(req, candidates, state):
    2. need = required_capabilities(req)
    3. pool = [c for c in candidates
    4. if need <= c.capabilities
    5. and not state.circuit_open(c.name)
    6. and state.quota_left(c.name, req.priority)]
    7. if not pool:
    8. return None # Trigger the fallback branch instead of throwing a raw exception
    9. pool.sort(key=lambda c: estimate_cost(c, req) / max(quality(c, req.intent), 0.01))
    10. return pool[0]

    Reliability and fault tolerance: engineering details of cross-provider failover

    The value of a multi-provider setup shows up mainly in resilience, but directly “switching to another model and retrying” brings several hidden problems you must handle in advance:

    • Layered timeouts: set connection timeout, first-token timeout (TTFT), and total timeout separately. In streaming, being stuck before the first token is the real user-experience killer.
    • Retries and idempotency: generate an idempotency key per logical request to avoid duplicate charges and duplicate orders from network jitter. Write-type tool calls especially need the business side to help with deduplication.
    • Mid-stream failures: once an SSE/streaming response has started emitting, a retry makes the user see duplicated content. In practice, either finish all retries before the first token, or do incremental buffering and deduplicated stitching on the gateway side.
    • Circuit breaking and half-open: track separately by provider + error type (rate-limit / 5xx / timeout / content-policy rejection); don’t lump them together. Content-policy errors are pointless to retry and should go straight to a fallback response.
    • Error-code normalization: map each vendor’s rate limits, auth failures, and context-length overflow to a unified error enum, so the business side can write provider-independent handling logic.

    Cost metering and governance: turning tokens into a manageable resource

    The unified layer is naturally in the best position for metering, so build it like a billing system.

    The unified metering basis should at least include: input tokens, output tokens, cache-hit tokens, reasoning tokens, and the extra consumption from retries and fallbacks. Keep the accounting formula generic:

    1. Per-call cost = (input tokens / 1e6) * input unit price
    2. + (output tokens / 1e6) * output unit price
    3. - cache and discount offsets

    Governance levers, in priority order:

    1. Budgets and quota allocation: allocate daily quotas and monthly budgets by tenant / business line / environment; on overflow, queue or degrade by priority rather than blocking everything.
    2. Context slimming: rolling summarization of history, truncation after reranking retrieved results, trimming tool-returned results. Most billing anomalies root-cause to unconstrained context growth.
    3. Prefix caching and semantic caching: keep system prompts and knowledge-base fragments stable to improve prefix cache hit rates; route high-frequency repeated questions through a semantic cache, where a hit skips the model call entirely.
    4. Batching and off-peak shifting: explicitly mark offline batch jobs as low priority and use idle quota to fill valleys.
    5. Cost attribution: tag every log with business line, feature point, and user segment; otherwise you only see the total and can’t locate abnormal growth.

    A reminder: don’t build architecture assumptions on short-term subsidized prices. Getting through a promotion and then losing money at normal prices is the most common way to fail. Before launch, be sure to do a full cost calculation and load estimate against current public pricing.

    Observability and a quality-evaluation loop

    Gateway observability must answer both “where is the cost” and “where is the quality.”

    Metrics: collect QPS, success rate, TTFT, total latency, token consumption, cost per successful request, fallback rate, and retry rate along model / intent / tenant dimensions. Fallback rate is a key leading indicator of health—when it rises, it usually means the primary model is degrading.

    Logs: structurally record the request summary, the routing decision basis (why this model was chosen), each candidate’s latency and errors, and usage details. Desensitize and sample request bodies as needed, to avoid writing user privacy to disk in full.

    Quality: build a gold-standard eval set of 200–1000 cases covering core scenarios, and run regression when models or prompts change; in production, use shadow traffic to dual-run a new model against the old and only shift traffic when metrics don’t degrade. Feed human feedback (thumbs up/down, edit distance, task completion rate) back as an online quality signal to correct the routing quality score.

    Security and compliance baseline

    • Key custody: keep provider keys centrally in a key management service; the gateway issues temporary credentials by least privilege and never pushes keys down to the client; enforce an outbound allowlist to prevent keys from being carried by business code into uncontrolled environments.
    • Data-flow control: clarify which data may leave the region and which must be processed on models kept within the region; make “data residency region” a hard filter condition in routing config.
    • Bidirectional content safety: on the inbound side, do prompt-injection and jailbreak detection plus sensitive-data identification and desensitization; on the outbound side, do compliance review and sensitive-info re-capture checks.
    • Audit and retention: record the caller, model, purpose, and retention period of each call to meet traceability requirements.
    • Supply-chain risk: lock adapter and dependency versions, and roll out provider changes through canary, to avoid upstream silent behavior changes causing abrupt online quality shifts.

    Phased rollout path

    • Phase 1 (1–2 weeks): define the unified contract, integrate 2+ provider adapters, get streaming and tool calling working, and unify log fields.
    • Phase 2 (2–4 weeks): ship static routing + circuit breaking + cross-provider failover to bring down single-point-dependency risk.
    • Phase 3 (3–4 weeks): integrate metering and budget quotas, build a cost dashboard and alerts, and complete one cost review against real pricing.
    • Phase 4 (ongoing): introduce cascaded calls, semantic caching, gold-set regression, and automated routing, turning model selection into data-driven continuous optimization.

    On the engineering side, deploy the gateway containerized to guarantee elastic scaling, pair it with log services and monitoring/alerting to collect metrics and trigger threshold notifications, use a message queue to absorb peaks and take on batch jobs, and manage routing and budget policies through a config center so they take effect without a release. If you use model services from a cloud provider such as Baidu AI Cloud as one of your backends, integrate it into the unified contract through an adapter as well, so you can switch and scale without changing business code—the value of the architecture lies precisely in this replaceability.

    Conclusion

    The short-term hype around aggregation-call products comes from subsidies, but the sustainable technical payoff is these four things: unified abstraction + policy routing + cost governance + an evaluation loop. Subsidies will taper, models will turn over, and prices will reshuffle; only by building this layer in your own hands is model selection an adjustable engineering parameter rather than an operational risk led around by upstreams. The standard for judging whether an access layer is truly mature is simple: when you switch model providers, does the business code need to change; and when an online quality drop happens, can you locate the specific routing decision and complete a rollback within an hour.