LLM Cost Optimization: A Multi-Channel Routing Practice
This article explains why a lower per-token price does not always translate into a lower bill when calling large language models, and how to build a repeatable cost governance process around it. It covers setting a unified measurement baseline, inserting a channel abstraction layer between business logic and model calls, designing layered routing and fallback policies, and exploiting often-overlooked levers such as prompt caching, batching, and context trimming. A reproducible evaluation method and a practical rollout checklist are included.
1. The Problem: A Cheap Unit Price Is Not a Cheap Bill
When teams first move LLM capabilities into production, the issue they hit is usually not output quality but the bill. The same model capability can be priced several times apart across different supply channels, and, counterintuitively, price level has no stable relationship with channel tier (official direct access, cloud marketplace resale, aggregation gateways, third-party proxies). Recent industry-wide price increases only pushed this long-standing structural gap into plain sight.
Seeing this clearly requires accepting three facts:
- Price dispersion is the norm. Input, output, and cache-hit prices for the same model may be set independently on each channel, so any single channel’s “lowest price” only holds under a specific workload mix.
- Uneven version coverage is the norm. Newly released flagship versions often appear on some channels first, and aggregation channels may only offer the previous generation or a lightweight/specialized variant, which makes a same-version side-by-side comparison impossible in many cases.
- Opaque pricing dimensions are the norm. Cache-hit discounts, batch discounts, tiered long-context pricing, and whether failed retries are billed can affect total cost more than the unit price itself.
So the right starting point for cost governance is not “find the cheapest channel,” but building a reproducible measurement baseline plus a switchable channel abstraction layer.
2. A Unified Measurement Baseline: Making Numbers Comparable
Price comparisons without a shared baseline have no engineering value. Fix the following four items before collecting any data:
- Workload mix: use 30% input tokens and 70% output tokens as the typical weighting for agent and code-generation scenarios; pure retrieval Q&A can shift to 70/30, and long-document summarization is close to 90/10.
- Exchange rate and tax basis: apply one conversion rate and record the capture time so data from different batches is never mixed.
- Pricing unit: normalize everything to “per million tokens” to avoid mixing per-thousand and per-million figures.
- Missing values: when a channel does not list a given version, mark it “not comparable” and never fill the gap with numbers from another version.
The weighted cost can be written as a minimal function that is easy to drop into CI for regression monitoring:
def blended_cost(input_price, output_price, in_ratio=0.3, cache_price=None, cache_hit=0.0):"""input_price/output_price/cache_price: price per million tokensin_ratio: share of input tokenscache_hit: share of input tokens served from cache"""effective_input = input_price * (1 - cache_hit) + (cache_price or input_price) * cache_hitreturn in_ratio * effective_input + (1 - in_ratio) * output_price
With this function, any channel price change can be quantified as “the actual impact percentage on the current workload” instead of staying a visual comparison on a price sheet.
3. A Channel Abstraction Layer: Turning Channel Choice into Configuration
Since price swings are out of your control, do not hardcode channels in the architecture. Insert a unified adapter layer between business code and model calls to hide differences in authentication, protocols, streaming response formats, and error codes.
Business logic↓Unified inference gateway (capability routing / cost accounting / rate limiting and circuit breaking)↓Channel adapters: official direct | cloud marketplace | aggregation gateway | third-party proxy
The adapter layer needs four baseline capabilities:
- Capability declaration: each channel registers the model capability tags it supports (long context, structured output, tool calling, vision input), and routing filters by tag rather than hard-matching names.
- Cost accounting: every request records the channel, token usage, cache hits, and converted cost, forming a bill view that can be aggregated by business line.
- Health checks and circuit breaking: sliding-window statistics on timeout rate, rate-limit hit rate, and error-code distribution automatically down-weight unhealthy channels.
- Hot configuration updates: prices and weights live in a configuration center, so a price change takes effect without a release.
4. Routing and Fallback: Balancing Cost, Stability, and Compliance
Optimizing a single dimension always trades off another, so the practical approach is layered routing:
- Layer 1, cost first: send batch, offline, retryable tasks (log summarization, bulk labeling, regression tests) to the cheapest available channel.
- Layer 2, quality first: pin user-visible critical paths to the most consistent channel rather than sacrificing experience to save a few cents.
- Layer 3, capacity fallback: when the primary channel hits rate limits, switch to backup channels by preset weights and log each switch event so quality fluctuations can be reviewed later.
- Layer 4, data compliance constraints: requests involving sensitive data may only use channels that meet data residency and no-retention requirements; this layer outranks cost.
An example weight configuration that can be put into practice:
routing:default: [ {channel: A, weight: 0.7}, {channel: B, weight: 0.3} ]batch_offline: [ {channel: C, weight: 1.0} ]sensitive_data: [ {channel: A, weight: 1.0} ] # compliance first, excluded from cost competitionfallback_order: [B, C, A]
5. Underrated Cost Levers: Caching, Batching, and Context Governance
Beyond unit price, four levers often move the bill more:
- Prompt caching: make the system prompt, tool definitions, and long document prefixes a stable prefix, and input cost can drop significantly on a cache hit. The prerequisite is a byte-for-byte stable prefix; any timestamp or random ID will break the cache.
- Batching and asynchrony: moving non-real-time work to asynchronous batch endpoints usually buys a better price at the cost of higher latency.
- Context trimming: truncate retrieval results by relevance and roll up conversation history into summaries to cut useless input tokens.
- Output length constraints: structured output plus explicit length caps suppress redundant generation, and output tokens are usually the most expensive part.
# Stable prefix plus variables last, to improve cache hit rateSYSTEM_PROMPT = "You are a coding assistant and follow these rules: ..." # no volatile content such as timestampsdef build_messages(snippet: str, question: str):return [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": f"Code snippet:\n{snippet}\n\nQuestion: {question}"},]
6. A Reproducible Evaluation Method: Verify It Yourself
Any pricing conclusion should be independently verifiable by the reader. Fix a collection process: record capture timestamps, save page snapshots, tag each channel with one of three states (“same version comparable,” “version behind,” “not listed”), and put the collection script on a schedule to build a price trend curve. When the curve shows an abnormal jump, first confirm whether a pricing dimension changed (for example, cache pricing moving from free to paid) before deciding whether to adjust routing weights.
Also establish a quality regression baseline: before switching channels, run a fixed question set to measure structured-output accuracy, tool-call success rate, and average latency, avoiding the hidden loss of “cost went down, rework went up.”
7. Rollout Checklist
- Define the workload mix and conversion basis, and turn the cost formula into code and monitoring metrics.
- Build a unified inference gateway with channels, prices, and weights all configurable.
- Strictly mark missing versions as not comparable; never fill data with approximate versions.
- Exploit caching, batching, and context trimming before considering a channel switch.
- Physically isolate the sensitive-data path from cost-optimization paths; compliance comes first.
- Run a biweekly review of both price and quality, and recompute weights whenever a price changes.
If you are using Baidu AI Cloud capabilities to host the gateway and accounting logic described above, you can combine its general container platform, message queue, logging, and monitoring and alerting capabilities to build a unified dashboard for channel health, token consumption, and converted cost, turning cost optimization from a one-off activity into a continuously running engineering mechanism.
