Why LLM Bills Spike: Token Costs, Caching, and Intelligent Routing
This article explains why large language model costs can appear negligible during testing but rise sharply in production. It breaks down the billing components behind model calls, then covers model tiering, caching, context governance, retry and tool-call controls, cost observability, unit economics, and a practical implementation order for cost-aware routing.
During early validation of large language model applications, costs often do not seem significant: there are few calls, contexts are short, concurrency is low, and dozens of tests may generate only a small charge. Once a system enters production, however, cost growth is often non-linear. A customer service system may handle tens of thousands of conversation turns per day. Content moderation must continuously process large amounts of text. Knowledge Q&A repeatedly carries the same rules and documents. Intelligent coding tools also read directory structures, code snippets, and historical change records. For agents with autonomous planning capabilities, a single user request may even trigger multiple model calls, tool calls, and failed retries.
Therefore, LLM cost governance cannot be reduced to “choosing the model with the lowest unit price.” A truly effective approach is to build a cost-aware routing system that can identify tasks, estimate risk, allocate models, and continuously feed results back into the system.
1. Understand the Bill First: What Are You Paying for in Model Calls?
LLM costs are usually related to the following factors:
- Number of input tokens;
- Number of output tokens;
- Input tokens that hit the cache;
- Input tokens that miss the cache;
- Billing rules for long contexts or extremely long inputs;
- Internal computation generated by deep reasoning;
- Tool calls, search, retrieval, and multi-turn planning;
- Retries after timeouts or failures;
- Unit price differences across model tiers;
- Resource policies such as concurrency, batching, and call timing.
A token can be understood as the basic unit used when a model processes text. It is not exactly equivalent to a word count, nor to the number of Chinese characters. Chinese, English, numbers, code, and special symbols may be split differently, so costs cannot be estimated solely from character count.
A simple call cost model can be expressed as:
Total cost =uncached input tokens × input unit price+ cached input tokens × cache unit price+ output tokens × output unit price+ tool and additional call costs+ retry costs
If a request contains long system rules, historical conversations, retrieved documents, and tool results, then even if the final answer is only a few hundred words, the input portion may already account for the main cost.
2. Why It Is Cheap in Testing but Quickly Gets Out of Control in Production
2.1 Traffic Volume Changes by Orders of Magnitude
During testing, a system may make dozens of calls per day. In production, it may make hundreds of thousands of calls per day. Even if each call generates only a small charge, the accumulated total can become a significant expense.
Suppose a service handles 100,000 requests per day, with an average of 3,000 input tokens and 500 output tokens per request. The daily token volume would already reach hundreds of millions. At that point, even unit price differences that appear to be only after the decimal point can turn into a considerable monthly bill when multiplied by request volume.
2.2 Production Requests Are Often Longer Than Test Requests
A demo environment usually passes in only a short question, while a production system may attach:
- System instructions;
- User conversation history;
- Permission and business rules;
- Retrieved knowledge snippets;
- Page structure or code context;
- Tool execution results;
- Planning information from the previous turn.
This content can easily be sent repeatedly across multi-turn interactions. Without context trimming and caching mechanisms, input tokens will continue to accumulate.
2.3 Multi-Turn Calls Amplify the True Cost of a Single Request
Agent-based applications usually do not work as simple “question and answer” interactions. Instead, they may follow a flow like:
User request→ intent recognition→ task planning→ data query→ tool call→ evaluate tool results→ generate final answer
If any step uses a high-tier model, one user request may correspond to multiple billed calls. More seriously, some systems automatically retry after tool failures or repeatedly plan when the model is uncertain, causing hidden costs to rise quickly.
2.4 Output Tokens Are Often More Expensive Than Input Tokens
For many models, the output unit price is significantly higher than the input unit price. The reason is that output generation requires step-by-step reasoning and decoding, and the computation process is usually more complex. Therefore, instructions such as “let the model explain more,” “output the full solution by default,” and “do not limit answer length” directly increase costs.
In real systems, controlling output length is often more effective than compressing a small amount of input. Clear output formats, field limits, pagination mechanisms, and maximum generation length should be used to prevent the model from producing lengthy content with little business value.
3. Model Tiering: Do Not Send Every Request to the Highest-Tier Model
The core of cost governance is not to reduce model capability for every request, but to match tasks of different complexity with appropriate models.
A tiered structure can be established as follows:
Tier 1: Rules and Programmatic Logic
For fixed-format validation, keyword matching, permission checks, field conversion, and simple routing, there is no need to call an LLM. Traditional program logic is more stable, and the cost is close to zero.
Tier 2: Lightweight Models for High-Frequency Tasks
This tier is suitable for intent classification, sentiment recognition, summarization, tag generation, simple Q&A, formatted output, and basic rewriting. These tasks usually have very high call volumes, so lower-cost, lower-latency models should be prioritized.
Tier 3: General-Purpose Models for Complex Business Tasks
This tier is suitable for more complex content generation, multi-document summarization, code explanation, structured analysis, and tasks that require a certain level of reasoning capability.
Tier 4: High-Capability Models for Critical Requests
These models should be used only for complex reasoning, assistance with critical business decisions, long-chain tasks, difficult code analysis, and requests where lightweight models have failed multiple times. High-capability models should be a fallback resource, not the default option.
Model routing can make comprehensive judgments based on task type, text length, user tier, risk level, historical success rate, and budget status. For example:
if request is a fixed-rule task:use program logicelse if text is short and task is classification or summarization:use lightweight modelelse if task complexity is medium:use general-purpose modelelse:use high-capability model
Real systems should also include degradation strategies. When a high-capability model reaches a budget threshold, becomes congested, or times out, the system can switch to a general-purpose model. When a lightweight model has insufficient confidence, the request can be escalated to a higher tier.
4. Caching Design: A Key Way to Reduce Repeated Input
Caching is not simply saving final answers. It is important to distinguish different types of repeated content.
4.1 Fixed Prefix Caching
System rules, role descriptions, format requirements, and business glossaries usually remain unchanged for a long time and can serve as stable prefixes. The more stable the request structure, the more likely cache hits become.
4.2 Retrieval Result Caching
For the same question, the same document version, and the same permission scope, retrieval results or intermediate summaries can be cached to avoid regenerating them every time.
4.3 Result Caching
For highly deterministic queries, such as policy explanations, common operation guides, and standard Q&A, final results can be cached. However, the cache must have an expiration time and must be combined with data version and permission checks to prevent old answers or unauthorized content from being reused.
4.4 Semantic Caching
For questions phrased differently but similar in meaning, vector representations or similarity checks can be used to reuse results. However, semantic caching must not be expanded blindly. Questions involving accounts, orders, permissions, legal liability, or real-time data must be revalidated.
Cache design must consider hit rate, data freshness, permission isolation, and error propagation at the same time. An overly aggressive caching strategy may save costs but introduce higher business risk.
5. Context Governance: Long Text Does Not Equal High Quality
Long contexts increase input costs and may also reduce the model’s effective attention. The following methods are recommended:
- Store conversation history in layers and retain only content relevant to the current task;
- Compress older messages into structured summaries;
- Control the number of returned documents and snippet length during retrieval;
- Remove duplicate titles, irrelevant metadata, and redundant formatting;
- Prioritize relevant files and relevant functions for code context;
- Set a maximum input token limit per request;
- Trim and filter fields in tool return results.
Context should serve the task rather than stuffing all available information into the model. More input does not necessarily mean a more accurate answer. It may instead lead to distracted attention, slower responses, and higher costs.
6. Retries and Tool Calls: The Most Easily Overlooked Hidden Costs
Production systems must distinguish between retryable and non-retryable errors. Temporary network interruptions, service rate limiting, and connection timeouts can usually be retried within limits. Parameter errors, insufficient permissions, and business validation failures should not trigger repeated model calls.
Recommended retry settings include:
- Maximum retry count;
- Exponential backoff;
- Total time limit;
- Per-request budget;
- Idempotency identifier;
- Failure reason classification;
- Model degradation strategy after retries.
For tool calls, the maximum number of calls per turn should also be limited, and the input, output, latency, and cost of each call should be recorded. If the model loops repeatedly among multiple tools, the task should be terminated promptly and an explainable failure result should be returned.
7. Build an Observable Cost Metrics System
Without detailed data, effective governance is impossible. At minimum, the following metrics should be recorded:
- Total requests and success rate;
- Input, output, and cache-hit tokens;
- Average cost per request;
- Cost by user, tenant, department, and business line;
- Call share by model;
- Retry rate and degradation rate;
- Number of tool calls;
- Average response latency;
- Maximum cost per request;
- Cache hit rate;
- Number of high-cost abnormal requests.
Cost statistics should not remain at the monthly bill level. They should also support breakdowns by application, API, task type, and user dimension. Real-time alerts should be set for sudden growth, such as abnormal cost per unit time, a sudden increase in output length, a clear rise in retry rate, or a rapid drop in cache hit rate.
8. Use Unit Economics to Evaluate Optimization Results
Looking only at the total bill makes it impossible to determine whether costs remain healthy as the business grows. More reasonable metrics include:
Cost per session = total cost / number of valid sessionsCost per task = total cost / number of successfully completed tasksCost per thousand requests = total cost / number of requests × 1000Cost per unit of revenue = LLM cost / corresponding business revenue
If request volume doubles while cost per task decreases, the system has scalable capability. Conversely, even if total revenue increases, continuously rising unit costs indicate problems with routing, context, or retry strategies.
9. Recommended Implementation Order
Enterprises can advance cost governance in the following order:
Step 1: Establish call details and token statistics to see clearly where the money is being spent.
Step 2: Classify requests into rule-based tasks, lightweight tasks, complex tasks, and high-risk tasks.
Step 3: Control output length, clean up ineffective context, and limit tool loops and retry counts.
Step 4: Design caching mechanisms for fixed prefixes, retrieval results, and deterministic answers.
Step 5: Introduce model tiering and dynamic routing so that low-complexity requests prefer low-cost options.
Step 6: Establish budgets, quotas, alerts, and automatic degradation mechanisms to prevent abnormal traffic from causing runaway bills.
Step 7: Use accuracy, success rate, latency, and cost per task as shared metrics for continuous evaluation of both effectiveness and cost.
Conclusion
LLM cost optimization is not simply about finding the “cheapest model,” nor is it about hastily compressing calls after seeing the bill at the end of the month. A mature governance system should identify tasks at the request entry point, control input during the context stage, apply tiered routing at the model stage, limit output during generation, constrain loops during tool use, and continuously monitor runtime behavior. Caching, degradation, and budget mechanisms should form a closed loop.
For teams using Baidu AI Cloud or other cloud-based LLM capabilities, the ultimate goal is not to make every call low-cost. It is to ensure that, while meeting quality, latency, security, and stability requirements, every token produces measurable business value.
