Why LLM Costs Spiral Out of Control: Tokens, Caching, and Routing in Practice
This article breaks down the three forces that drive large language model spending — token billing, prompt caching, and model routing — and shows how to build a cost governance framework around observability, budgets, and continuous optimization, so LLM usage stays sustainable at production scale.
As LLMs move from demos into production, one problem keeps coming back: the monthly spend estimated before launch often multiplies several times over under real traffic. A soaring bill is rarely the result of a single mistake. It is the combined effect of how the billing model works, how the system is used, and how the engineering architecture is designed. To bring cost under control, you first need to see where it comes from, why it grows, and how to manage it. This article follows three main threads — tokens, caching, and routing — to explain the underlying logic of AI cost, and then offers a governance framework you can actually apply.
1. Tokens: The First Principle of AI Cost
LLMs are billed by usage, and the unit is not “per call” or “per second” but the token — the smallest unit into which a model splits text. A single Chinese character, a fragment of an English word, or even a punctuation mark may map to one or more tokens. The implication is that the cost driver is not the number of requests, but the total volume of tokens that actually flow through each request.
1.1 The Asymmetric Pricing of Input and Output
The mainstream billing structure breaks a single call into two parts: input (the prompt — the context and instructions you send to the model) and output (the completion — the content the model generates). The two are priced independently, and the output unit price is typically significantly higher than the input unit price — a consequence of the compute characteristics of the generation process. So if you keep telling the model to “say a bit more,” cost climbs non-linearly.
The table below is illustrative only and exists to explain the calculation method (units: per million tokens; actual prices change continuously as models iterate, so always confirm against the provider’s console before launch):
| Model tier (illustrative) | Input price | Cache hit price | Output price | Typical use cases |
|---|---|---|---|---|
| Flagship reasoning model | High | Medium-low | Highest | Complex reasoning, agents, business-critical workloads |
| Standard balanced model | Medium | Low | Medium | Moderate tasks, summarization, general generation |
| Lightweight model | Low | Very low | Low | Classification, high concurrency, light reasoning |
One point deserves emphasis: models iterate extremely fast, so specific names and unit prices will change, but the analytical framework of “input / output / cache / routing” holds up over the long term. The core takeaway is that output costs more than input, and the hidden cost of long answers is very high.
1.2 The Hidden Accumulation of Context
Multi-turn conversations are a disaster area for cost control. If every request stuffs the entire conversation history back into the context, token consumption balloons with each turn. Assume the system prompt plus user input in a single turn total 2,000 tokens. After 20 turns of conversation, with no trimming at all, cumulative input tokens will approach tens of thousands — and almost every turn pays again for the content that came before.
# Illustration: unlimited context accumulation quickly inflates token consumptiondef naive_chat(history, user_input):history.append(user_input) # history only ever growsmessages = history[:] # resend everything in fullreturn call_model(messages) # every turn is billed for the full history again
Remedies include: a sliding window that keeps only the most recent N turns; summarizing and compressing earlier turns; and returning only the retrieval snippets that are genuinely necessary. The goal is to find the balance point between “conversational coherence” and “token cost.”
2. Caching: Stop Paying Twice for the Same Input
In many applications, a large share of requests carry the same prefix content — system role definitions, tool descriptions, business rules, long documents, and so on. This content is transmitted over and over on every call, which is pure waste. Prompt caching exists precisely to eliminate this repeated cost.
2.1 How Cache Hits Work and What They Save
The basic idea is simple: when the prefix of a request is exactly identical to a previous request, the provider reuses the already-computed intermediate results instead of processing that part of the input again, so tokens that hit the cache enjoy a substantially lower unit price. As the illustrative table shows, the cache hit price is often a fraction of the standard input price, delivering savings on the order of magnitude.
To capture that benefit, the key is to keep the prefix stable and put the volatile parts at the end:
# Illustration: put stable content first and dynamic content last to improve cache hit ratedef build_prompt(system_rules, retrieved_docs, user_query):stable_prefix = system_rules + retrieved_docs # stable prefix, easy to cachevolatile_suffix = user_query # volatile part goes at the endreturn stable_prefix + "\n" + volatile_suffix
2.2 When It Helps and When It Doesn’t
Caching is not a cure-all. It requires an exactly identical prefix that is called repeatedly, so it suits: fixed system prompts, high-frequency shared knowledge-base snippets, and batch workloads that share a long document. Conversely, when request content is highly scattered with almost no repetition, the cache payoff is limited — in that case your effort is better spent on routing and context trimming. In addition, caches usually have a time-to-live window, so you need to make sure it lines up with your business refresh cadence.
3. Routing: Give Each Request the Right Model
Not every task needs the strongest model. Using a flagship model to answer “is this sentence positive or negative” is like delivering a letter with a heavy-duty truck — it works, but the cost is severely wasteful. The core idea of intelligent routing is to grade requests by task complexity and dispatch each one to a model that is “good enough.”
3.1 Model Tiering and Routing Strategies
Models can be grouped into flagship, balanced, and lightweight tiers, and selected dynamically based on input characteristics:
# Illustration: model routing based on task complexitydef route_model(query: str, want_json: bool) -> str:# Lightweight tasks: classification, extraction, formattingif want_json or len(query) < 50:return "model_light"# Complex tasks: multi-step reasoning, code, long-form writingif any(k in query for k in ["推理", "代码", "方案", "分析"]):return "model_flagship"# Default to the balanced tierreturn "model_balanced"
A more advanced approach is to have a small model perform intent classification first, decide which path a request should take, and then hand it off to the corresponding model. This two-stage routing can significantly reduce overall spend.
3.2 Fallback and Gradual Rollout
Production also demands a double safeguard covering both stability and cost: when the flagship model times out or hits rate limits, traffic can fall back automatically to the balanced model to preserve availability; when budget approaches a threshold, non-critical requests can be temporarily switched to a cheaper model. These policies should be controlled through configuration switches rather than hard-coded, so they can be adjusted quickly.
4. Building a Sustainable Cost Governance System
The first three threads answer “how to make a single call cheaper.” What actually keeps the bill under control is an engineering system that spans the entire development, launch, and operations lifecycle.
4.1 Observability: You Can’t Manage What You Can’t See
The starting point of cost governance is data visibility. Record, for every call, the model used, input/output token counts, whether the cache was hit, latency, and cost — and aggregate by business line, scenario, and user dimension. With the general-purpose log service and monitoring/alerting capabilities offered by cloud platforms (such as the logging and monitoring services available on Baidu AI Cloud), you can build a cost dashboard and set anomaly alerts, so that when a given API’s daily spend spikes you step in right away instead of “discovering the problem when the monthly bill arrives.”
4.2 Budgets and Rate Limits
On top of observability, add guardrails: set token or spend caps per business and per tenant; enforce rate limits at the gateway layer to stop abnormal calls or usage abuse; and apply hard truncation to over-long outputs and over-long contexts. These measures turn “after-the-fact remediation” into “pre-emptive blocking.”
4.3 The Continuous Optimization Loop
Cost governance is not a one-off project but an iterative process. It helps to establish a closed loop of “measure — attribute — optimize — re-measure”: first locate the scenario with the largest consumption, determine whether the cause is redundant input, over-long output, or an over-provisioned model tier, then apply targeted measures (trim context, enable caching, step down a model tier), and finally validate the effect with data. Making token cost a core monitored metric, weighed alongside response quality, is what lets you sustain a long-term balance between experience and expense.
Closing
The runaway LLM bill is essentially the result of treating compute resources as free air. Understand the billing nature of tokens, use caching well to eliminate duplication, apply routing to allocate on demand, and then build an engineering line of defense with observability, budgets, and continuous optimization — these four steps interlock into a complete methodology for AI cost governance. Models will keep being replaced and unit prices will keep changing, but as long as you master this framework, you can make every unit of spend produce certain value and turn the LLM into a genuinely sustainable, scalable form of productivity.
