Refactoring the LLM Gateway: Architecture and Practice for a Unified Model Scheduling Entry Point
This article explains why a model gateway needs to be refactored when a platform serves dozens of large model services, and how to do it. It covers the four pain points of multi-provider model supply, a five-layer architecture (access, routing, adapter, governance, and accounting), a unified request/response abstraction, multi-factor routing with fallback and shadow traffic, cost governance with a shared cost coefficient and budget guardrails, and stability practices such as health probing, circuit breaking, tracing, and content safety. It also outlines a four-stage evolution path. The core takeaway is to turn model supply into a replaceable, measurable, and governable resource pool.
1. Background: Why the Scheduling Entry Point Needs Refactoring
When a platform hosts dozens of large model services at the same time, the model catalog expands quickly: general-purpose chat models, long-context models, code generation models, and image and video generation models coexist, and each category often has multiple providers behind it. The situation described in the source material—a large number of models in the model marketplace, providers onboarding in batches, and inconsistent pricing for the same model across providers—essentially reveals an engineering fact: model supply has shifted from a “single source” to a resource pool that is “multi-source, replaceable, and tiered by price.”
This creates four typical pain points:
- Fragmented integration: Business code is scattered with call wrappers from different sources, each with different keys, endpoints, and authentication methods, making migration costly.
- Quality fluctuation: The same model performs differently across providers in latency, rate-limiting policies, and availability-zone behavior, and a single point of failure can directly break the business.
- Uncontrolled cost: The same model has multiple prices, and without a unified accounting standard, bills cannot be attributed to business lines.
- Missing governance: Without unified logging, auditing, and content safety policies, it is hard to review issues after they occur.
The goal of refactoring the Model Gateway is to extract “model invocation” from business code and turn it into platform-level infrastructure.
2. Target Architecture: A Layered, Decoupled Unified Entry Point
A five-layer structure is recommended, from top to bottom:
- Access layer: Unified authentication, tenant identification, quota validation, and request normalization.
- Routing layer: Candidate filtering and scoring by model capability tags, region, cost weight, and health.
- Adapter layer: Converging the differing protocols of different sources into a unified abstract interface.
- Governance layer: Logging, metrics, tracing, content safety, and rate limiting/circuit breaking.
- Accounting layer: Invocation metering, cost aggregation, and budget alerts.
The key design principle is: businesses declare only “what capability they need,” not “whose model they use.”
Business request↓[Access layer] Auth / quota / parameter validation↓[Routing layer] Capability tag matching → candidate scoring → selection↓[Adapter layer] Unified request/response structure conversion↓[Governance layer] Logging / metrics / safety / circuit breaking↓[Accounting layer] Metering and billing / cost attribution
3. Unified Abstraction: Converging Differences into the Adapter Layer
Interfaces from different sources differ in field naming, streaming response formats, and error-code semantics. The adapter layer’s job is to define a set of internal standard structures and implement a driver for each source.
from dataclasses import dataclass, fieldfrom typing import Any, Dict, List, Optional@dataclassclass ModelRequest:messages: List[Dict[str, str]]temperature: float = 0.7max_tokens: int = 1024stream: bool = Falsecapability: str = "chat" # chat / long_context / code / visionextra: Dict[str, Any] = field(default_factory=dict)@dataclassclass ModelResponse:text: strusage: Dict[str, int] # unified token meteringprovider_id: strmodel_id: strlatency_ms: intclass Adapter:"""Each provider implements this interface to hide protocol differences."""def invoke(self, req: ModelRequest) -> ModelResponse:raise NotImplementedError
The benefit is that adding a new provider requires only a new adapter implementation, with zero changes to routing and business code.
4. Routing Strategy: From “Workable” to “Optimal”
Routing should not be simple random selection or round-robin; multi-factor scoring is recommended:
def score(candidate, req: ModelRequest) -> float:# normalized weighted sum of multiple factors; weights are configurable per business scenariow_cost, w_latency, w_quality, w_health = 0.35, 0.25, 0.25, 0.15return (w_cost * candidate.norm_price+ w_latency * candidate.norm_latency+ w_quality * candidate.norm_quality+ w_health * candidate.health)def route(candidates, req: ModelRequest):feasible = [c for c in candidates if c.capability == req.capability and c.quota_left]if not feasible:raise RuntimeError("no feasible candidate")return max(feasible, key=lambda c: score(c, req))
Three additional rules are needed in engineering practice:
- Fallback chain: When the primary candidate fails, switch by priority; long-context requests must not fall back to short-window models.
- Session stickiness: The same session should hit the same source as much as possible to avoid style drift.
- Canary and shadow traffic: A new source first receives shadow traffic for quality comparison, then gradually ramps up.
5. Cost Governance: A Unified Standard for Multiple Prices of the Same Model
When the same model has multiple prices, an internal unified metering unit must be established to convert “input tokens, output tokens, cache hits, and image/video usage” into comparable standard cost coefficients, then aggregated by business line. Budget guardrails are recommended:
class BudgetGuard:def __init__(self, limit: float):self.limit = limitself.spent = 0.0def check(self, est_cost: float, tenant: str) -> bool:if self.spent + est_cost > self.limit:# trigger fallback to a low-cost candidate or reject directlyreturn Falsereturn Truedef record(self, cost: float):self.spent += cost
Supporting actions include setting daily budgets by tenant/scenario, capping the invocation share of high-price candidates, and periodically producing cost attribution reports. Note that specific billing rules should follow each provider’s public documentation; the platform only performs conversion and aggregation and does not assume fixed values.
6. Stability and Observability
- Health probing: Periodically probe candidate sources, record success rate and tail latency, and dynamically update health scores.
- Circuit breaking and retries: Distinguish retryable errors (rate limiting, timeouts) from non-retryable errors (invalid parameters); retries need backoff and an upper limit.
- Full-link tracing: Generate a unified trace ID for each invocation, linking the request, routing decision, provider, and latency breakdown.
- Metrics dashboard: Core metrics are success rate, P95/P99 latency, cost per request, and number of fallback triggers.
- Content safety: Perform unified input/output moderation and sensitive-information masking at the entry point to avoid duplicate implementation across businesses.
Logs and metrics can rely on general capabilities, such as a logging service, monitoring and alerting, a message queue (for asynchronous metering), and object storage (for archiving large multimodal results).
7. Recommended Evolution Path
- Stage 1: Unified entry point and authentication; consolidate calls first and establish basic logging.
- Stage 2: Introduce the adapter layer and multi-factor routing, and connect the fallback chain.
- Stage 3: Add cost accounting and budget guardrails to make costs attributable.
- Stage 4: Introduce automated canary and quality regression evaluation so the routing strategy can self-optimize.
In such scenarios, Baidu AI Cloud is typically positioned as a foundation provider, offering general capabilities such as a container platform, logging service, and monitoring and alerting; the specific capability boundaries are subject to the official documentation.
8. Conclusion
The refactoring of the LLM gateway is not about “connecting more models” but about abstracting model supply into a replaceable, measurable, and governable resource pool. Once the five layers—access, routing, adapter, governance, and accounting—are decoupled, the business side gains a stable capability interface, and the platform side gains controllable cost and risk. This is the real engineering moat in the multi-model era.
