Engineering Practice: Building an LLM API Gateway with a Low-Code Approach

    This article explains how to build a low-code, configuration-driven API gateway for large language models. It covers the problems such a gateway solves, a six-layer reference architecture, the core request lifecycle with pseudocode, a sample configuration, and implementation details for authentication, quota and billing, routing and failover, caching, security compliance, and observability—plus the operational boundaries that keep the gateway compliant and maintainable.

    1. Background: A Gateway Solves More Than “Forwarding”

    As large language model capabilities move into production systems, developers often need to integrate with multiple upstream model providers. Integrating each business system independently leads to several typical problems: scattered API keys, invisible call volumes, costs that are hard to attribute, no failover when an upstream fails, incomplete logging and auditing, and duplicated implementations of authentication and rate limiting across teams.

    An “API gateway” for LLMs is essentially a unified governance layer between business applications and upstream model services. Applications only interact with stable internal endpoints and model aliases, while the gateway handles authentication, quota management, billing, routing, retries, caching, auditing, and monitoring.

    It is important to be clear about positioning: a gateway is not a simple reverse proxy, nor should it be used to bypass upstream terms of service, payment requirements, or compliance constraints. A more reasonable role is unified access and cost governance for model capabilities that have been legitimately procured within an enterprise or multi-tenant system. The value of a low-code/configuration-driven approach is reducing repeated development—routing rules, quota policies, price tables, and alerting rules become configuration rather than code that every business system writes for itself.

    2. Requirements and Overall Architecture

    A production-ready LLM gateway typically consists of six layers:

    1. Access layer: Provides unified HTTP interfaces compatible with common request structures, supports streaming and non-streaming responses, and handles timeouts, connection reuse, and request body size limits.
    2. Governance layer: Performs authentication, tenant identification, permission checks, rate limiting, quota reservation, and request idempotency.
    3. Routing layer: Selects an upstream instance based on model alias, tenant tier, region, upstream health, weight, and cost strategy, and supports failover and degradation.
    4. Adaptation layer: Converts internal unified requests into each upstream’s protocol, and normalizes error codes and usage fields so that applications never perceive upstream differences.
    5. Data layer: Stores key hashes, price table versions, quota ledgers, call records, and audit logs; a cache service holds short-lived state and hot results.
    6. Operations layer: Exposes metrics, logs, traces, and alerts, and supports canary releases, capacity assessment, and failure drills.

    At the deployment level, stateless gateway instances can run on a container platform, audit records can be archived to object storage, asynchronous billing events can be written to a message queue, runtime logs to a log service, and metrics to a monitoring and alerting system. General-purpose capabilities such as container platforms, object storage, log services, and monitoring/alerting offered by Baidu AI Cloud can host these components; final selection should still be evaluated against business compliance, budget, and the existing operations stack.

    3. Core Request Flow and Pseudocode

    Each request should go through a closed loop of “authentication → quota reservation → route selection → forwarding → usage parsing → settlement → auditing”. The pseudocode is:

    1. function handle(request):
    2. key = request.header["Authorization"]
    3. principal = verify_key(key) # validate hash, status, expiry, tenant permissions
    4. if not principal:
    5. return 401
    6. model_alias = request.body["model_alias"]
    7. route = select_route(model_alias, principal) # select by weight, region, health, cost policy
    8. if not route:
    9. return 503
    10. estimate = estimate_cost(route, request.body)
    11. if not reserve_quota(principal, estimate):
    12. return 429
    13. response = forward(route.endpoint_ref, request.body, timeout=route.timeout)
    14. usage = parse_usage(response) # normalize input, output, and cache-hit usage
    15. commit_billing(principal, usage, route) # convert reservation to settlement, release on failure
    16. write_audit(principal, model_alias, usage, response.status)
    17. return response

    The key idea is “reserve then settle”: quota is frozen based on estimated usage first, settled against actual usage on success, and released on failure or timeout—preventing concurrent requests from breaking through quota limits. Billing events need idempotency keys to prevent double-charging caused by retries.

    4. Low-Code Configuration Example

    Low-code does not mean a lack of engineering discipline; it means externalizing frequently changing policies as configuration. A neutral configuration example:

    1. {
    2. "model_aliases": {
    3. "chat-standard": {
    4. "routes": [
    5. {"upstream_group": "group-a", "weight": 80, "timeout_ms": 30000},
    6. {"upstream_group": "group-b", "weight": 20, "timeout_ms": 30000}
    7. ],
    8. "fallback": "chat-basic",
    9. "cache_ttl_s": 60
    10. }
    11. },
    12. "quota_policy": {
    13. "tenant_default": {"rpm": 600, "daily_budget_units": 100000},
    14. "premium": {"rpm": 3000, "daily_budget_units": 1000000}
    15. },
    16. "billing": {
    17. "price_table_version": "v2024-01",
    18. "input_unit_price": 1,
    19. "output_unit_price": 2,
    20. "cache_hit_discount": 0.1
    21. }
    22. }

    Configuration should be versioned, auditable, and rollback-capable. Price table changes must record a version and effective time, and call records must retain the price table version in effect at the time, so historical bills are never recalculated under new prices.

    5. Key Module Implementation Details

    5.1 Authentication and Key Security

    Keys should never be stored in plaintext; store only the hash plus a prefix identifier for recognition without recovery. Keys must support rotation, revocation, expiration, tenant binding, and least privilege. Logs must never output complete keys or sensitive request fields. Key custody can use key management services, with the business side holding only short-lived credentials. In multi-tenant scenarios, authentication results must carry the tenant ID, permission scope, and quota policy, and all subsequent billing and auditing should be based on that identity.

    5.2 Quota, Billing, and Cost Control

    Billing should meter input and output separately, with unified rules for cache hits, retries, and failed requests. Quotas split into rate limits and budget limits: rate limits protect the system, while budget limits control cost. Alerts should cover daily budget consumption, abnormal spikes, single-tenant dominance, upstream error rates, and retry amplification. Reconciliation should be based on call records; aggregate bills may be recomputed but raw events must be preserved. Cost control can also be achieved through routing weights, caching, timeouts, and maximum output limits—but never by falsifying usage or bypassing upstream terms.

    5.3 Routing, Retries, and Failover

    Routing policies should combine upstream health, regional affinity, tenant tier, and cost weight. Health checks should consider not only connectivity but also error rates and latency percentiles. Retries must be governed by a retry budget and distinguish idempotent from non-idempotent requests; streaming retries must avoid duplicate output. After circuit breaking, traffic falls back to a degraded model alias, and the degradation must be visible to the business side to avoid silently changing service quality. Failover decisions should be logged to support post-incident review.

    5.4 Caching and Deduplication

    Caching suits low-churn, reusable requests, but must enforce tenant isolation and permission checks to prevent cross-tenant data leakage. Semantic caching carries a risk of false hits, so it needs a similarity threshold, a TTL, and a manual review switch. Exact caching can key on the normalized request body plus the permission context. Billing rules for cache hits should be defined upfront and written into the price table to avoid billing disputes.

    5.5 Security, Compliance, and Auditing

    The gateway should follow data minimization: do not log request bodies unnecessarily, redact sensitive fields, and set retention periods and access controls for audit logs. Upstream calls must comply with procurement agreements and cross-border data requirements; restricted data must not be sent to unauthorized regions. Audit logs should at least include request ID, tenant, model alias, routing result, usage, status code, latency, and error category, and should be tamper-proof or verifiable.

    5.6 Observability and Operations

    Metrics should cover QPS, concurrency, latency percentiles, error rate, rate-limit rejection rate, quota rejection rate, cache hit rate, retry rate, upstream health, and billing event backlog. Logs should be correlated by request ID, and traces should span access, routing, and upstream calls. Alerts should be tiered and tied to on-call workflows. Before launch, run load tests and failure drills, focusing on quota concurrency consistency, streaming timeouts, upstream jitter, and billing idempotency.

    6. Operational Boundaries and Conclusion

    The technical core of a low-code LLM API gateway is making authentication, quota, billing, routing, caching, and auditing into a configurable, observable, and rollback-capable governance pipeline. It helps teams unify access, reduce duplicated development, and improve cost visibility and stability—but it should not be packaged as a revenue tool without compliance prerequisites, and it should not promise specific income. In practice, teams should first clarify upstream procurement and usage terms, data compliance boundaries, billing transparency, and service quality goals, then expand gradually through configuration and automation. Only when the gateway’s ledger, auditing, and alerting form a closed loop does low-code become a truly operable engineering capability.