Architecture Design and Cost Governance for a Multi-Model LLM Gateway

    With multiple LLMs now the norm in production engineering, teams struggle with heterogeneous APIs, version drift, runaway costs, and compliance risks. This article walks through the architecture of a unified model access gateway—covering a layered design, vendor-agnostic abstractions, capability/cost/quality-aware routing, contract-based rolling upgrades, cost attribution and quotas, observability, and security—so models can be treated as replaceable infrastructure rather than embedded business logic.

    1. Background: Multiple Models Are the Norm, Not the Exception

    In real-world engineering environments, no single model covers every use case. Different models trade off long-context comprehension, structured-output reliability, code generation, multimodal parsing, inference latency, and unit cost. Model versions also iterate on a monthly or even weekly cadence, so capability boundaries keep shifting. Teams typically face four problems:

    1. Heterogeneous interfaces: Providers differ in authentication, message structures, streaming protocols, error codes, and rate-limit semantics, tying business code to a specific SDK.
    2. Version drift: Upstream model upgrades or deprecations change output distributions; without regression evaluation, quality silently degrades.
    3. Cost sprawl: Without metering and quotas per business line or caller, bills can’t be attributed and anomalous calls are hard to trace.
    4. Compliance risk: Prompts and responses may contain sensitive data, with no unified redaction or audit entry point.

    The conclusion is clear: treat models as replaceable infrastructure dependencies, not as part of your business logic.

    2. Design Goals and Principles

    • Unified abstraction: Business code depends only on one stable domain interface, unaware of the underlying model.
    • Pluggability: Adding or removing a model only requires registering an adapter and routing rules—no business code changes.
    • Contract-first: Manage version upgrades through capability descriptions and compatibility contracts, not hardcoded model identifiers.
    • Observability: Record request metadata, token consumption, latency, and quality metrics end to end.
    • Governability: Enforce budgets, quotas, fallbacks, and auditing at the gateway layer.

    3. Layered Architecture

    1. Business Applications
    2. ↓ Unified domain interface
    3. Access Layer (auth / tenant identification / rate limiting)
    4. ↓
    5. Routing Layer (capability matching / cost policy / canary / fallback)
    6. ↓
    7. Adapter Layer (protocol conversion / stream normalization / error-code normalization)
    8. ↓
    9. Model Backends (multiple model services, pluggable)
    10. ↓
    11. Governance & Observability (metering / logging / monitoring & alerting / evaluation)

    The access layer handles identity and quotas; the routing layer makes decisions; the adapter layer does the “translation.” Governance consumes the call-event stream asynchronously (decoupled via a message queue if needed), logs and metrics land in the logging service and monitoring/alerting stack, and evaluation samples and regression baselines are stored in object storage.

    4. The Unified Abstraction Interface

    The key is defining a vendor-agnostic domain model and confining differences inside adapters:

    1. class ModelAdapter(Protocol):
    2. capability: Capability # capability tags: text/multimodal/structured output/long context
    3. def chat(self, req: ChatRequest) -> ChatResponse: ...
    4. def stream(self, req: ChatRequest) -> Iterator[Chunk]: ...
    5. @dataclass
    6. class ChatRequest:
    7. messages: list[Message]
    8. max_output_tokens: int | None = None
    9. temperature: float | None = None
    10. response_schema: dict | None = None # structured output constraints
    11. tenant_id: str = ""
    12. trace_id: str = ""
    13. @dataclass
    14. class ChatResponse:
    15. text: str
    16. usage: Usage # input/output token metering for cost accounting
    17. model_key: str # logical name, not the physical model
    18. finish_reason: str

    The key point: decouple logical model names from physical backends. A business request uses model_key="general-chat", and the routing layer maps it to a concrete backend. Upgrades only change the mapping, not the business code.

    5. Routing Strategies

    Routing is where the most value concentrates. Four strategies combine well:

    • Capability routing: Filter candidates by Capability—e.g., exclude backends without constrained decoding when structured output is required.
    • Cost routing: Within the candidate set, try backends in ascending unit cost and return once a quality threshold is met—cost-efficiency first.
    • Quality routing: Route high-value requests to stronger backends, with priority explicitly set by the business.
    • Fallback and safety net: On timeout or rate limiting, fail over in candidate order; if all fail, return a cached result or an explicit degradation message to prevent cascading failures.
    1. def route(req: ChatRequest) -> list[str]:
    2. cands = [k for k in registry if req.needs in registry[k].capability]
    3. cands.sort(key=lambda k: (cost_table[k], -quality_score[k]))
    4. if req.priority == "high":
    5. cands.sort(key=lambda k: -quality_score[k])
    6. return cands or ["fallback-small"]

    Canary releases and A/B tests are implemented via proportional traffic splitting. Use hash(tenant_id + trace_id) as the split key so the same session consistently hits the same backend, reducing experience jitter.

    6. Rolling Upgrades and Compatibility Contracts

    The requirement that “new versions are automatically incorporated by rule once online” is, in engineering terms, a contract-based upgrade. Maintain a declarative configuration per logical model:

    1. model_key: general-chat
    2. contract:
    3. min_context: 32k
    4. supports_stream: true
    5. supports_schema: true
    6. backends:
    7. - name: backend-a-v1
    8. weight: 70
    9. - name: backend-b-v2
    10. weight: 30
    11. rollout:
    12. strategy: canary
    13. steps: [5, 20, 50, 100]
    14. auto_rollback_on: [error_rate>2%, p95_latency_regression>30%]

    Before a new backend goes live, it must pass a unified evaluation set (covering extraction, summarization, code, multi-turn dialogue, and refusal/safety dimensions); only if metrics don’t regress against the baseline may it enter canary. Rollback conditions trigger automatic weight reduction. This turns “launching a new model” from a manual change into a pipeline.

    7. Cost Governance

    • Metering and attribution: Each call emits an event (tenant, business line, logical model, input/output tokens, latency, status), queued asynchronously and stored, producing drill-down bills.
    • Budgets and quotas: Set daily/monthly token budgets and concurrency caps per tenant; when limits are hit, degrade rather than fail outright.
    • Tiered caching: Apply semantic caching to deterministic requests (with similarity thresholds and TTLs), and prefix reuse for long system prompts—significantly cutting repeated input costs.
    • Batching and truncation: Merge offline tasks into batches; for overly long contexts, compress via retrieval or summarization before sending to the model.

    8. Observability and the Quality Loop

    Metrics should include at least: request volume, error rate, P95/P99 latency, token consumption, fallback rate, cache hit rate, and per-backend quality scores. Distributed tracing spans access to backend; logs are redacted, centrally stored, and given retention policies. On the quality side, run dual tracks—offline evaluation plus online sampling with human/automated review—and feed evaluation results back into routing weight adjustments, closing the loop.

    9. Security and Compliance

    Centrally enforce bidirectional (input and output) content safety checks at the access layer, sensitive-data detection and redaction, prompt-injection protection (isolating external content from instruction zones), centralized key management with rotation, and full audit trails. Configure data-residency policy per tenant; where required, allow only private or dedicated deployment backends to participate in routing.

    10. Rollout Roadmap and Common Pitfalls

    A four-step path is recommended: first build the abstraction interface and adapters (1–2 weeks), then add metering and rate limiting, then evaluation and canary, and finally cost and quality optimization. Common pitfalls include: scattering physical model names throughout business code; doing failover without quality regression checks; caches with no invalidation policy serving stale answers; and quotas that limit only total volume but not concurrency, letting traffic bursts overwhelm backends.

    11. Conclusion

    Multiple models aren’t a burden—they’re a lever for availability and cost optimization, provided you encapsulate the differences, pipeline the upgrades, and make costs attributable. On Baidu AI Cloud, teams can host gateway services on the container platform, store evaluation sets and configurations in object storage, decouple metering events with a message queue, and complete the observability loop with the logging and monitoring services—building a stable, compliant, and scalable unified model access system on general cloud capabilities.