Architecture and Practice of an LLM Aggregation and Routing Gateway
This article explains how to build a model aggregation and routing layer that decouples business code from individual LLM providers. It covers the engineering challenges of fast-moving model supply, the goals and non-goals of the gateway, a five-layer architecture, multi-dimensional routing strategies, stability patterns such as retries, circuit breaking and fallback chains, cost controls, observability and evaluation loops, security and compliance, and a phased rollout plan.
1. Background: Engineering Challenges from Rapid Model Supply Iteration
Over the past two years, the LLM service market has shown two clear trends. First, consolidation at the capital level has accelerated: larger M&A deals have appeared, and the number and form of service providers keep shifting. Second, capability iteration is extremely fast. The same research lab may ship several versions within weeks, including closed-source flagship models and open-source lightweight variants for low-cost scenarios. In some cases, an anonymous preview model appears first and its ownership is confirmed later.
For developers and enterprises, this is both an opportunity and a burden. The opportunity is more available capabilities and lower unit cost. The burden is that once business code is deeply coupled to one provider, migration cost is high, negotiating leverage is weak, and the failure domain is concentrated. The harder engineering problems include:
- Inconsistent interface protocols: authentication methods, request body structures, and streaming response formats all differ.
- Quotas and rate limits change at any time, so peak traffic easily triggers widespread failures.
- Model quality on the same task varies significantly, and there is no unified evaluation baseline.
- Cost grows linearly with call volume, with no way to schedule by scenario tier.
So the common industry answer is not “pick the single best model” but to build a model aggregation and routing layer that is decoupled from any specific vendor, turning “model selection” from a compile-time decision into a configurable runtime policy.
2. Goals and Non-Goals
Clear boundaries prevent architectural sprawl. The aggregation and routing layer should deliver:
- Protocol normalization: a single interface contract upstream, with adapters for multiple heterogeneous backends downstream.
- Pluggable policies: routing, retries, fallbacks, and rate limiting exist as configuration or plugins, with no business code changes.
- Observability: every call is traceable to a specific backend, its latency, token usage, and estimated cost.
- Smooth migration: adding or retiring a backend is transparent to upstream callers.
Non-goals matter just as much. The layer should not handle model training or fine-tuning pipeline orchestration, nor replace the business side’s quality evaluation and data labeling systems.
3. Layered Architecture
A mature implementation is usually split into five layers:
- Access layer: unified authentication, tenant identification, quota reservation, request body validation.
- Abstraction layer: maps different backends’ requests and responses to a unified internal model (message arrays, tool calls, streaming events).
- Decision layer: route selection, load awareness, canary and experiment traffic splitting.
- Execution layer: connection pooling, timeout control, circuit breaking, retries, and the fallback chain.
- Governance layer: metering and billing, logs and metrics, auditing, key management.
The abstraction layer is the most underestimated part. The unified internal representation should keep only concepts common across the industry: role, content, tool call structures, finish reasons, and usage stats. Any backend-specific fields go into an extensible extra container so the core contract stays clean.
{"request_id": "req-8f2c","model_alias": "general-chat","messages": [{ "role": "system", "content": "You are a rigorous technical assistant" },{ "role": "user", "content": "Explain the purpose of an idempotency key" }],"stream": true,"extra": { "temperature": 0.2 }}
Note that model_alias is the only field business code needs to be aware of; the real backend is resolved by the decision layer. This is the key to decoupling.
4. Routing Strategy Design
Routing should not be simple random or round-robin selection. A four-dimension composite score works better:
- Capability match: task type (long-context understanding, code generation, structured extraction, multimodal) against backend capability tags.
- Cost constraint: pick a tier by token price and scenario budget, sending simple tasks down to lightweight models.
- Health: dynamic weights based on sliding-window success rate, time to first byte, and overall latency.
- Constraint compliance: hard conditions such as data residency region, content safety policy, and whether streaming is allowed are filtered first, then scored.
Pseudocode for the scoring logic:
def choose(candidates, task, ctx):pool = [c for c in candidates if hard_filter(c, ctx)]if not pool:raise NoAvailableBackend()scored = []for c in pool:s = 0.0s += 0.4 * capability_score(c, task)s += 0.3 * health_score(c) # sliding-window success rate and latencys += 0.2 * cost_score(c, ctx.budget)s += 0.1 * affinity_score(c, ctx) # session stickiness, cache hit ratescored.append((s, c))return weighted_pick(scored, temperature=0.05)
Keeping a small amount of randomness (a very low temperature) avoids pinning all traffic on one backend over time and makes it easier to keep collecting comparison samples.
5. Stability: Retries, Circuit Breaking, and Fallback Chains
LLM call failure modes differ from typical RPC: latency is long, results are non-deterministic, and partial failures happen mid-stream. Key design points:
- Idempotency keys: generate a unique key per logical request and reuse it on retries, which helps backend deduplication and your own auditing.
- Retry budget: cap the overall retry share (for example, no more than 10% of total requests) so retries do not amplify load during an incident.
- Distinguish error types: rate limits and timeouts can be retried on another instance in the same family; parameter errors and blocked content are deterministic failures where retrying is pointless and an immediate return is correct.
- Circuit breaking: trigger on error rate and latency percentiles, and let a small amount of traffic through in the half-open state to probe.
- Fallback chain: when the primary model is unavailable, try backup models in the same capability tier, then fall back to a smaller model or a cached result, and mark the degraded state in the response so business code can detect it.
primary route → same-tier backup A → same-tier backup B → lightweight fallback model → semantic cache → explicit error
Streaming needs extra handling for “failure after partial output”: mark the content already sent, and let the business side decide whether to continue, resend, or prompt the user to retry, avoiding garbled concatenation.
6. Cost Control
Cost governance comes down to three levers:
- Semantic caching: cache results for high-frequency, low-freshness requests. The cache key is derived from the normalized semantics plus key parameters, with a TTL and invalidation policy.
- Context compression: trim earlier turns, summarize long documents, and cap tool return size to cut input tokens directly.
- Tier splitting: use lightweight models for deterministic tasks like classification, extraction, and rewriting, and reserve high-capability models for complex reasoning.
For metering, emit data points across four dimensions: tenant × scenario × model tier × backend. That produces an explainable bill and a feedback loop for optimization, rather than only recording totals.
7. Observability and the Evaluation Loop
Metrics should include at minimum: request volume, success rate, time to first byte, end-to-end latency percentiles, input and output tokens, estimated cost, fallback count, and circuit breaker count. Logs should use structured fields with a unified request_id to stitch the full trace together.
On top of that, run a dual track of an offline evaluation set plus small-traffic online experiments: whenever routing weights change or a backend is added, first run a regression on a fixed evaluation set, then canary at 1%–5% traffic, watching core metrics and human-sampled quality, and ramp up gradually once there is no regression. This turns market signals such as “an anonymous model tops the usage charts after launch” into data you can verify yourself, instead of blindly following.
8. Security and Compliance
- Keep keys centrally managed; business code holds only gateway credentials, and backend keys are rotated on a schedule.
- Control outbound traffic with a domain allowlist so a configuration mistake cannot point traffic at an unintended endpoint.
- Mask the full chain: sensitive information in prompts and responses is masked per policy before being written to storage.
- Retain audit records and data retention policies to meet traceability requirements.
9. Suggested Rollout Path
- First unify the interface contract and internal abstraction model, and get a single backend working end to end.
- Add a second backend and validate the completeness of the abstraction layer. This step most easily exposes design flaws.
- Introduce health-based weighting plus circuit breaking and fallback.
- Ship metering, logging, and the evaluation baseline.
- Only then work on cost optimization and productizing the experiment platform.
10. Conclusion
Given how frequently the supply side changes, turning “model selection” into a configurable runtime capability is a more robust engineering strategy than chasing a single leaderboard. If an enterprise wants the same capabilities quickly in a managed environment, it can evaluate cloud providers such as Baidu AI Cloud and their combination of general-purpose products across container platforms, message queues, logging services, and monitoring and alerting, using standard components to carry the layers above instead of building all the infrastructure itself.
