Designing an LLM API Gateway: Multi-Account Scheduling and Context Compression

    This article explores the architectural design of a unified API gateway for large language models (LLMs). It addresses the challenges of integrating multiple upstream model providers, including protocol adaptation, centralized credential management, and failover handling. The core focus is on implementing a robust multi-account scheduling mechanism based on health scores and real-time load, alongside strategies for long-context compression and multi-level caching to optimize cost and performance. The article also covers stream output handling, tool call fidelity, and critical security practices for credential management.

    Why a Unified Model Access Layer Is Necessary

    In real-world projects, teams often use multiple LLM services simultaneously. Different platforms have distinct API endpoint paths, authentication methods, message structures, and streaming protocols. If business code directly integrates with each upstream, three major problems arise:

    • High adaptation cost: Every new tool or SDK integration requires rewriting request and response conversion logic.
    • Scattered credentials: API keys are spread across multiple service configuration files, making rotation and auditing difficult.
    • Poor stability: When a single account hits its rate limit or experiences an outage, the calling service directly receives an error, lacking automatic failover.

    A unified access layer, commonly known as an API gateway or model proxy, consolidates these issues into a single management point. The caller only needs to interface with one stable API, while the gateway handles protocol conversion, account selection, failure recovery, and usage statistics.

    Overall Architecture

    A typical model gateway can be decomposed into the following stages:

    1. Client Request
    2. │
    3. ▼
    4. [Authentication & Rate Limiting] → Validate caller API Key, rate limits
    5. │
    6. ▼
    7. [Protocol Adaptation] → Convert unified format to upstream request structure
    8. │
    9. ▼
    10. [Context Processing] → Length check, history compression, cache hits
    11. │
    12. ▼
    13. [Account Scheduling] → Select upstream credentials by health and concurrency
    14. │
    15. ▼
    16. [Upstream Call] → Send request, handle timeout and retries
    17. │
    18. ▼
    19. [Response Transformation] → Uniform write-back for streaming chunks or non-streaming results

    Each component has a single responsibility, making it easy to test and replace in isolation. When switching upstream providers, only the protocol adaptation layer needs modification. Adjusting the scheduling policy does not impact the client.

    Protocol Compatibility and Format Mapping

    Message Structure Mapping

    Mainstream chat APIs typically use an array of messages with role and content fields, while tool calls are represented through function definitions and call records. The gateway needs to handle the following mappings:

    • System prompt placement: Some APIs treat system as an independent field, while others place it as the first element in the messages array.
    • Tool result role markers: The role or content block type for tool outputs must be correctly backfilled as required by the upstream API.
    • Content block format: Text, images, and tool calls may be structured as arrays, requiring normalization.

    The mapping should preserve all original fields. If an unrecognized field is encountered, it should be logged and safely ignored to avoid failing the entire request.

    Streaming Output

    Streaming responses typically use Server-Sent Events (SSE) or chunked transfer. The gateway must:

    1. Read upstream data chunk by chunk and extract the incremental text.
    2. Re-wrap the data according to the event format expected by the caller.
    3. Send a termination signal on connection interruption and release the account concurrency slot.
    1. async def stream_proxy(upstream_iter, to_client_event):
    2. try:
    3. async for chunk in upstream_iter:
    4. delta = normalize_delta(chunk) # Normalize into incremental text
    5. if delta:
    6. yield to_client_event(delta)
    7. yield to_client_event(None, finished=True)
    8. finally:
    9. release_account_slot() # Always release concurrency count

    The finally block is crucial. If resources are only released on a normal end, client disconnections or exceptions will cause the account’s concurrency count to accumulate indefinitely. This can lead to healthy accounts being misjudged as busy, gradually degrading service capacity.

    Multi-Account Scheduling

    Why an Account Pool Is Needed

    A single upstream account has limited concurrency and rate limits. By pooling multiple accounts, the gateway can distribute requests across them and quickly switch away from any account that encounters issues.

    Health Scores and Concurrency Control

    Scheduling typically combines two key metrics:

    • Health Score: Dynamically calculated based on recent success rate, response latency, and error types. An account with consecutive failures sees its score drop, which gradually recovers after successful requests.
    • Real-time Load: Tracks the number of in-flight requests for each account to prevent overloading a single one.

    A simple yet effective scoring method:

    1. def score(account):
    2. if account.cooldown_until > now():
    3. return float("-inf") # In cooldown, exclude from selection
    4. load_penalty = account.inflight / max(account.max_concurrency, 1)
    5. return account.health * (1 - load_penalty)
    6. def pick_account(pool):
    7. candidates = [a for a in pool if score(a) > 0]
    8. if not candidates:
    9. raise NoAvailableAccount()
    10. return max(candidates, key=score)

    Failure Handling

    Different failure types require specific responses:

    • Authentication failure: Indicates invalid credentials. The account should be immediately quarantined and an administrator notified.
    • Rate limit (429): Place the account into a cooldown period, during which no requests are routed to it.
    • Network timeout or 5xx errors: Lower the health score, allow a limited number of retries, and switch to a different account.

    Retries must consider idempotency. For a streaming response that has already started, transparently switching accounts and resending is generally unsafe, as the client would receive duplicate content. In such cases, return an explicit error to the client and let it decide whether to retry.

    Long-Context Compression and Caching

    Length Detection

    The gateway should estimate the token count of a request before forwarding it. Estimation can be a simple character-based approximation or use a tokenizer consistent with the target model for greater accuracy. When the estimate exceeds a certain threshold (e.g., 80% of the model’s limit), the compression process should be triggered.

    Compression Strategies

    A common approach is layered processing:

    1. Preserve the system prompt and the most recent N conversation turns, as this information is critical for the current response.
    2. Summarize older historical messages with the model and insert the summary as a single message in the context.
    3. If still over the limit after summarization, reduce the number of retained turns or truncate overly long tool outputs.

    Compression inevitably results in some loss of detail. Therefore, record the token counts before and after compression in the logs. This is essential for diagnosing issues like “the model forgot the earlier context.”

    Multi-Level Caching

    For scenarios with many repeated requests, caching can be introduced:

    • In-memory cache: Stores recent request results or summaries for the lowest access latency.
    • Key-value store: Shares summaries across multiple gateway instances.
    • Prefix caching: Leverages the upstream API’s ability to reuse a common prompt prefix to reduce redundant computation.

    The cache key should include the model name, key parameters, and a hash of the message content to avoid cache hits across different requests.

    Tool Calls and Reasoning Content

    Tool calling follows a three-step loop: the model outputs an intent to call a function, the application executes the function, and the result is sent back to the model. The gateway’s responsibility is to ensure the function definitions, call IDs, and result contents remain correctly correlated after format conversion.

    Some models output their reasoning process wrapped in special tags. The gateway can handle this in one of three ways:

    • Pass through as-is and let the caller parse it.
    • Split it into a separate field for easy UI folding.
    • Discard it to reduce the response size.

    Each approach has trade-offs. Products facing end users typically prefer splitting, while batch processing tasks often favor discarding.

    Credential Security and Compliance

    Since a model gateway centralizes a large number of upstream credentials, a breach would have a significant impact. The following principles are recommended:

    • Credential sourcing: Obtain credentials through officially provided methods from the service provider and comply with the relevant terms of service. Avoid extracting tokens from browser sessions or client-side state, as this may violate terms and create account risks.
    • Encrypted storage: Store credentials encrypted, with the master key managed by a dedicated key management service and rotated regularly.
    • Least privilege: Grant the gateway the minimum permissions required for its functions. Issue independent API keys for each caller and support individual revocation.
    • Log sanitization: Request logs should only record the request ID, model name, latency, and status code, without sensitive payload data.