How to Choose and Operate an LLM API Gateway: Routing, Quota, and Cost Governance

    This article explains why teams need a unified LLM access layer and how to build one. It covers a layered architecture that decouples logical model names from backend instances, cost-aware routing beyond simple round robin, token metering and multi-level budget control, retry and circuit-breaking strategies for long-output failures, and the observability metrics needed to close the evaluation loop. It also maps the architecture to generic cloud capabilities without tying it to a specific vendor.

    1. Why You Need a Unified LLM Access Layer

    Over the past two years, the supply side of LLM inference has expanded rapidly. Models keep launching across different vendors, parameter sizes, and context windows, with open-weight models and closed APIs coexisting while pricing and rate-limit policies change frequently. For application teams, integrating with each provider one by one quickly accumulates a pile of adapter code that is hard to maintain.

    A pattern often mentioned in public industry discussions is a newly launched model absorbing an enormous volume of token processing within a short period, with weekly call volume measured in trillions of tokens. Such figures are operational statistics, but the engineering fact they reveal is clear: inference calls have become high-concurrency, heavily metered, cost-sensitive baseline traffic that needs to be governed like databases and message queues.

    A unified access layer, commonly called a model aggregation gateway, addresses four problems:

    • Heterogeneous interfaces: request/response structures, authentication schemes, streaming protocols, and error-code semantics differ across providers.
    • Metering and cost: token billing rules vary, and without unified aggregation there is no way to build budgets or attribute cost.
    • Stability differences: backends differ significantly in rate limiting, timeouts, and tail latency.
    • Evolution speed: model iteration cycles are measured in weeks, so hardcoding leads to frequent releases.

    2. Target Architecture: Layered Decoupling

    A practical layered structure looks like this:

    1. Access layer: unified authentication, tenant identification, request validation, protocol conversion (sync/streaming).
    2. Routing layer: selects a backend by model alias, capability tag, cost policy, region, and remaining quota.
    3. Adapter layer: one Driver per backend, responsible for request mapping, response normalization, and error-code normalization.
    4. Governance layer: rate limiting, circuit breaking, retries, fallback, caching, budget control.
    5. Observability layer: metrics, logs, tracing, and token metering aggregation.

    The key design principle is decoupling the model identifier from the backend instance. Applications depend only on a logical model name (such as chat-general or chat-long-context), while a configuration center decides which backend, which version, and what weight sit behind it.

    1. # Example: mapping logical models to backends with governance policies (vendor-agnostic)
    2. models:
    3. chat-general:
    4. backends:
    5. - driver: openai_compatible # generic compatible-protocol adapter
    6. weight: 70
    7. max_tokens_per_min: 600000
    8. timeout_ms: 20000
    9. - driver: openai_compatible
    10. weight: 30
    11. max_tokens_per_min: 300000
    12. timeout_ms: 30000
    13. fallback: [chat-general-backup]
    14. budget:
    15. daily_token_cap: 800000000
    16. on_exceed: degrade_to_smaller_model

    3. Routing Strategies: From Round Robin to Cost Awareness

    Plain round robin cannot handle tail latency or exhausted quota. A cost-aware weighted selection is recommended, with a scoring function abstracted as:

    1. score = w1 * (1 - normalized_latency)
    2. + w2 * (1 - normalized_price)
    3. + w3 * available_quota_ratio
    4. - w4 * recent_error_rate

    Three practical rules of thumb:

    • Rate limit by token budget, not request count. Request sizes can differ by tens of times, so QPS-based limiting leads to uncontrolled cost.
    • Separate hot and cold traffic. High-frequency short requests go to low-latency backends, while long-context and batch jobs go to more cost-efficient backends, decoupled through queues and asynchronous tasks.
    • Use consistent hashing for session stickiness. Multi-turn conversations should land on the same backend where possible to reuse prefix caches and avoid repeated computation.

    4. Metering, Quotas, and Cost Control

    Token metering must be done uniformly at the gateway rather than relying on each backend’s bill. The recommended approach:

    • Estimate with a tokenizer before the request, then correct with the actual usage returned in the response, recording the difference as an estimation-error metric.
    • Write metering events to a message queue, aggregate them via stream computing into minute-level, tenant-level, and model-level usage, then land them in object storage for offline reconciliation.
    • Combine token bucket + multi-level budgets: tenant daily budget, project monthly budget, and a hard cap per model. On reaching a cap, degrade or queue instead of failing outright.
    1. def charge(tenant, model, usage):
    2. tokens = usage.prompt_tokens + usage.completion_tokens
    3. if not bucket.acquire(tenant, model, tokens):
    4. raise QuotaExceeded(model=model, retry_after=30)
    5. ledger.append({
    6. "tenant": tenant, "model": model,
    7. "prompt": usage.prompt_tokens,
    8. "completion": usage.completion_tokens,
    9. "ts": now_ms(),
    10. })

    5. Stability: Retries, Circuit Breaking, and Fallback

    Failure modes for LLM calls differ from conventional RPC: timeouts concentrate in the long-output phase, and some errors are safe to retry. Recommendations:

    • Retry only idempotent errors (rate limits, connection failures, 5xx) with exponential backoff plus jitter, allowing at most two cross-backend retries.
    • Track circuit breakers per backend + model independently so a single model’s failure does not spread.
    • Fallback chain: primary model unavailable → backup model with the same capability → smaller-parameter model → return a cached result or an explicit structured error.
    • Streaming scenarios must complete the routing decision before the first token arrives; if the first-token timeout is hit, switch immediately to avoid leaving users waiting.

    6. Observability and the Evaluation Loop

    Beyond standard metrics (QPS, P95 latency, error rate), add: first-token latency, output tokens per second, deviation between estimated and actual usage, cache hit rate, and cost per token. Keep the request ID and the routing decision reason in logs so you can trace “why this backend was chosen.”

    Also maintain an offline evaluation set. Whenever routing weights change or a new model is introduced, run a fixed set of cases and track two curves, accuracy and cost, to avoid silently losing quality in the name of cost reduction.

    7. Mapping to Generic Cloud Capabilities

    Implementing this architecture does not require any specific provider and can map to generic cloud capabilities: a container platform hosts stateless gateway instances, load balancing and elastic scaling handle traffic peaks, a message queue carries metering events, object storage holds evaluation sets and audit logs, logging and monitoring with alerting handle metric collection and threshold notifications, and a configuration center manages model mappings and canary weights. Generic capability categories from cloud providers such as Baidu AI Cloud can serve as the underlying platform for this kind of architecture; the actual selection should follow your own compliance and cost requirements.

    8. Conclusion

    Rapid change in model supply is the norm; engineering certainty comes from abstraction and governance. Treat “models” as replaceable backends, “tokens” as a resource that must be accounted for, and “routing” as a policy that evolves through canary releases, and you can keep the system stable and costs under control despite frequent model iteration.