Multi-Provider LLM Routing and API Call Observability in Practice
This article explains how to route large language model (LLM) requests across multiple API providers through a local transparent proxy layer. It covers keyword-based model routing, session continuity when switching models, token-based cost estimation, per-request logging, a systematic method for troubleshooting intermittent errors, and security and rollout considerations.
1. Background: The New Complexity of Connecting to Multiple Providers
LLM capabilities are spread across different providers, and their capability, pricing, and stability vary noticeably. Teams often want to use high-capability models for complex reasoning tasks and low-cost models for mechanical batch edits, which helps control overall spending.
When connecting directly to several providers, problems tend to concentrate in three areas:
- Clients bound to a single address and key: Switching providers usually requires editing a configuration file and restarting the client, which interrupts the current session.
- Differences in protocols and fields: Auth header formats, model naming, streaming event structures, tool-call parameter schema restrictions, and error code meanings can all differ between providers.
- Missing process data: After a request is sent, you only see the final result. You cannot tell where the time was spent, and it is hard to reconstruct the context of intermittent failures.
Intermittent errors usually do not have a single cause. They result from the differences above combining under specific conditions. Therefore, before troubleshooting, you need to make the request process observable as data.
2. Core Approach: Adding a Transparent Proxy Layer Between the Client and Upstream Providers
A transparent proxy sits between the client and the upstream providers. The client always accesses the same local address. The proxy decides which provider receives each request, how the request is rewritten, and what gets recorded.
The proxy layer typically handles three responsibilities:
- Routing: Selects the upstream provider and the actual model based on the model identifier in the request.
- Transformation and fault tolerance: Replaces authentication information, normalizes required request fields, and retries or degrades service on timeouts or rate limits.
- Recording: Stores request metadata, latency metrics, and streaming events for analysis and replay.
The architecture is shown below:
Client ──> Local proxy layer ──> Routing decision ──> Provider A│ Provider B│ Provider C▼Request log and metrics storage
This approach has costs to assess in advance. The proxy adds one network hop, usually a latency of a few milliseconds, but every extra component in the path is another point of failure. The proxy also handles plaintext requests and keys, so you must restrict the listening scope and apply redaction.
3. Model Routing Design
3.1 Keyword Matching on Model Identifiers
The core of a routing rule is mapping the model identifier sent by the client to a specific upstream. A practical approach is keyword matching with rule priorities. Rules are checked in order, and the first matching rule takes effect. Always keep a fallback rule at the end. Otherwise, unmatched requests fail outright.
Example configuration (placeholder names, for illustrating the structure only):
routes:- name: High-capability tiermatch: "large"provider: provider_aupstream_model: model-large-v1- name: Economy tiermatch: "small"provider: provider_bupstream_model: model-small-v1- name: Default fallbackmatch: "*"provider: provider_cupstream_model: model-general-v1
The matching logic can be expressed in pseudocode as follows:
function resolve_route(model_id, routes):normalized = lowercase(model_id)for route in routes (sorted by priority):if route.match == "*" or route.match is contained in normalized:return routeraise RoutingError("no route for model: " + model_id)
When implementing this, keep two points in mind. First, keywords should be as specific as possible to avoid broad matches that cause misrouting. Second, maintain the upstream model name for each rule separately. The name a client sends often differs from the real upstream name, which is a common cause of 404 or “model not found” errors.
3.2 Switching Timing and Session Continuity
Routing is decided again for every incoming request, so a change to the rules takes effect on the next request, and the client does not need to restart. This approach suits adjusting cost and capability during a long session according to the task stage.
Switching also creates continuity problems. Different models have different context window lengths, so after switching from a large window to a smaller one, the conversation history may exceed the limit. Tool-call parameter formats and their support levels also vary. If you switch mid-task, tool-call records generated in earlier turns may not be parsed correctly by the new provider. Therefore, it is safer to switch at task boundaries, or to truncate history and normalize its format at the proxy layer.
3.3 Estimating Costs by Tier
The basic formula for estimating the cost of a single request is:
Cost per request = input tokens × input unit price + output tokens × output unit price
Get unit prices from each provider’s official pricing page, and check them periodically because they change with versions. After the proxy layer records the token count for each request, you can aggregate costs by route, by session, and by day. This shows which tasks justify the high-capability model.
4. Call Observability: Turning Every Request into a Queryable Record
Observability aims to let you reconstruct every request. At minimum, record the following fields:
| Field | Meaning | Purpose |
|---|---|---|
| timestamp | Request start time | Locate failures by time period |
| method / path | Request method and path | Distinguish endpoint types |
| status | Response status code | Track the error distribution |
| route / upstream | Matched route and upstream | Determine whether failures cluster on one provider |
| model | Model name sent by the client and actual upstream model | Troubleshoot model name mapping issues |
| session_id | Session identifier | Reconstruct the full interaction |
| input_tokens / output_tokens | Input and output token counts | Cost accounting |
| latency_ms / ttft_ms | Total latency and time to first token | Determine whether delay is in the network or the generation phase |
An example log record:
{"timestamp": "2026-11-24T16:08:31+08:00","method": "POST","path": "/v1/<endpoint>","status": 200,"route": "Economy tier","upstream": "provider_b","model": "model-small-v1","session_id": "sess-0042","input_tokens": 1820,"output_tokens": 364,"latency_ms": 5230,"ttft_ms": 412}
For streaming responses, recording only the total duration is often not enough. More useful is recording the sequence of event types, such as content delta events, tool-call start and end events, and finish reasons. When an output is suddenly interrupted, the event sequence shows at which stage the interruption occurred: whether generation was cut off, or whether tool-call arguments were incomplete.
Logs must be redacted. Auth headers, keys, and personally identifiable information should be filtered or replaced before they are written. The retention period for session content should also be clearly defined and aligned with your team’s data compliance requirements.
5. Systematic Troubleshooting of Intermittent Errors
Troubleshoot intermittent errors starting from the symptom. Map the symptom to possible causes, then verify with logs. The table below lists common cases:
| Symptom | Common Cause | How to Check |
|---|---|---|
| 401 / 403 | The key has expired, or the key for the target provider was not substituted after the proxy switched routes | Check the auth header and key validity for the target upstream |
| 404 or model not found | Incorrect upstream model name mapping | Compare the model and upstream_model fields in the logs |
| 429 | Rate limiting was triggered or the quota is exhausted | Review request frequency in the same time period, and configure backoff and retry |
| 5xx or timeout | Upstream service instability, or a timeout threshold that is too small | Calculate error rates per upstream, and set reasonable timeouts and failover |
| Streaming output interrupted or parse failure | Buffering in the intermediate layer delays events, or the event format does not match client expectations | Check the response type and chunked transfer settings, and compare event sequences |
| Tool-call parameter error | Providers support different ranges of tool parameter schemas | Compare tool definitions between failed and successful requests |
| Request exceeds context length | Switched to a model with a smaller context window | Count input tokens for the failed requests |
When troubleshooting, you can follow these steps:
- Reproduce: Record the time, route, upstream, and model name of failed requests, and determine whether they cluster on one route or during one time period.
- Compare: Within the same session, find the differences between successful and failed requests, including input length, tool definitions, and event sequences.
- Verify layer by layer: Check the client, the proxy layer, and the upstream in turn to confirm which layer produced the error.
- Minimize the test: Bypass the proxy and send a minimal request directly to the upstream. If the direct request succeeds while the request through the proxy fails, the problem most likely lies in the proxy’s transformation or authentication step.
6. Security and Operations Essentials
- Key management: Inject keys through environment variables or a key management service. Do not store them in plaintext in configuration files, and do not let them appear in logs.
- Network exposure: The proxy should listen only on the local loopback address by default. If LAN access is needed, add access controls.
- Log governance: Define a clear log retention period, clean up expired records regularly, and restrict who can view the logs.
- Fault isolation: Set circuit-breaker thresholds for each upstream. When failures occur consecutively, switch to a backup route automatically and notify the relevant people.
7. Rollout Recommendations
Roll out in phases. In the first phase, enable observation only. Record all requests and establish baselines for error rates and latency without changing routing behavior. In the second phase, introduce routing rules. Validate them on low-
