# Rising LLM Costs? How to Control Them Through Token Structure, Caching, and Routing
This article explains why LLM API bills grow faster than expected and how to control them. It covers token structure, prompt caching, model routing, retries, and output length, and it presents a cost analysis framework built around per-request metering, attribution, budgets, degradation, and regression testing.
Rising LLM Costs? How to Control Them Through Token Structure, Caching, and Routing
In the early stage of an LLM application, the bill often looks manageable. Once the application moves into multi-turn conversations, retrieval-augmented generation (RAG), tool calling, batch generation, or high-concurrency traffic, costs can multiply in a short time. Many teams first try switching to a cheaper model. The real problem, however, is usually not the unit price. It is the call structure: whether input context is repeated, whether the cache is hit, whether routing makes sense, whether retries are under control, and whether outputs are too long. Unit price is only one variable in the cost formula. Token structure, caching mechanisms, and routing strategy determine the total bill.
This article does not tie itself to any specific vendor or model. It builds a cost analysis method from a general technical perspective. The prices shown here only illustrate the calculation method and do not represent any platform’s pricing. Before going live, check the actual console and billing documentation. Models evolve and prices change, but the framework of input, output, caching, routing, retries, and attribution stays useful over time.
1. Read the Bill First: Cost Is Not Unit Price Times Call Count
The cost of an LLM request usually consists of input tokens, output tokens, cache-hit tokens, retries and parallel calls, and the cost of routing classifiers. A simplified estimate can be written as:
Cost per request =uncached input tokens × input price+ cache-hit input tokens × cache-hit price+ output tokens × output price+ retry overhead+ parallel or cascaded call overhead+ routing and preprocessing costTotal cost =Σ cost per request+ cache write and storage cost+ observability, gateway, and fixed resource cost
This formula looks simple, but each term is easy to underestimate. Input tokens include more than the user’s question. They also include the system prompt, tool definitions, retrieved passages, conversation history, format constraints, and examples. Output tokens usually carry a higher price, and long answers, structured generation, multi-turn expansion, and code generation all increase output cost. Retries and parallel calls are less obvious. One failed retry can double the cost of a request, and multi-model voting or cascading fallbacks can bill the same request several times.
So the first step in cost governance is not finding the cheapest model. It is building per-request metering. Record the input tokens, cache-hit tokens, output tokens, model tier, routing reason, retry count, and estimated cost for each call. Then aggregate the data by feature, tenant, and session. Without request-level attribution, you can see only the total bill and cannot locate the source of a spike.
2. Token Structure: Context Bloat Is the Most Overlooked Cause
Tokens are the basic billing unit, but bill spikes often come from an imbalance in token structure. Common causes include:
- A system prompt that is too long and repeated on every request
- Oversized tool definitions and JSON Schemas
- Retrieved passages concatenated without trimming
- Conversation history that grows without limit
- Output format requirements that cause the model to generate large amounts of redundant content
- Agent loops that send the full context at every step
You can split the input of a request into a stable prefix and a dynamic suffix. The stable prefix includes the system role, fixed rules, tool definitions, and few-shot examples. The dynamic suffix includes the user’s question, the latest retrieved passages, and the current session state. The stable prefix suits caching, while dynamic content should be placed later and trimmed as much as possible. If volatile content such as timestamps, random IDs, or user nicknames sits in the prefix, the cache hit rate drops significantly.
To govern tokens, start with three metrics: the input-to-output ratio, the context reuse rate, and the output length distribution. A high input-to-output ratio means the context carries too much. A low reuse rate means the stable prefix is not being cached. A long tail in output length suggests the prompt or stop conditions need work. Optimization methods include:
- Compressing the system prompt
- Loading tool definitions on demand
- Reranking and truncating retrieved passages
- Summarizing conversation history
- Limiting the maximum output tokens
- Setting field constraints for structured output
- Setting a maximum number of turns and a context budget for agents
3. Caching: Hits Are Cheap, but the Conditions Are Strict
Caching is an important way to reduce input cost. Common approaches include prefix caching and explicit caching. When several requests share the same prefix, the platform can reuse the already computed context and bill the matching portion at a lower price. But caching does not save money just because it is enabled. It depends on strict prefix matching and a stable cache key.
A cache hit usually requires the same prefix order, content, and model version. If the system prompt includes a dynamic timestamp, a request ID, or retrieved results in random order, the cache will be invalidated frequently. A cache key should include the model tier, the system prompt version, the tool definition version, a tenant isolation identifier, and a content hash. Dynamic content should come after the stable prefix. Cache writes and storage can also add cost, so calculate the net benefit:
Net cache savings =cache-hit tokens × (input price - cache-hit price)- cache write and storage cost- recomputation cost caused by cache invalidation
Do not evaluate caching by hit rate alone. Also look at the share of tokens that hit the cache and the actual dollars saved. A request that hits 1 token and one that hits 10,000 tokens have very different impacts. Record the reason for each cache miss, such as a prefix change, tenant isolation, a model switch, a change in content order, or cache expiration. Caching usually pays off most for long system prompts, fixed tool definitions, and shared knowledge snippets. For highly personalized, short requests, the benefit may be small.
4. Routing: A Cheap Model Is Not Always the Answer, and Routing Mistakes Amplify Cost
Routing selects a model tier based on task complexity. Simple classification, extraction, and customer support Q&A go to a lightweight tier. Summarization and general generation go to a balanced tier. Complex reasoning, critical business tasks, and long-running jobs go to a high-capability tier. Good routing can reduce cost significantly, but routing also introduces new risks.
First, the classifier itself has a cost. If every request calls a model to judge complexity first, the routing cost adds up. Second, misclassification has a cost. A simple task routed to a high-capability tier wastes money. A complex task routed to a lightweight tier may fail to meet quality requirements, and the resulting fallback and retry can cost more than the original call. Third, cascades amplify cost. Retries after a high-capability call fails, parallel voting, and multi-round tool calls can turn one request into several billable calls. Fourth, retry storms occur. If timeouts or rate limits trigger retries without backoff or circuit breaking, the bill can grow quickly.
Routing should be explainable, observable, and reversible. Rule-based routing suits clear scenarios. Classifier-based routing suits tasks with labeled data. Confidence-based fallback suits workflows that require high accuracy. Budget-based routing selects a tier dynamically within a cost ceiling. Whichever method you use, record the routing reason, model tier, number of fallbacks, and final cost. Set a maximum number of retries, a maximum number of parallel calls, a maximum number of agent turns, a per-request budget, and daily or monthly quotas. When a limit is exceeded, degrade the service instead of retrying without limit.
The following is an illustrative price table. It shows the calculation method only, with units in price per million tokens, and does not represent any vendor’s pricing.
| Capability tier | Illustrative input price | Illustrative cache-hit price | Illustrative output price | Suitable scenarios |
|---|---|---|---|---|
| High-capability tier | 5.00 | 0.50 | 30.00 | Complex reasoning, critical business tasks, long-running jobs |
| Balanced tier | 0.75 | 0.075 | 4.50 | Summarization, general generation, moderately complex tasks |
| Lightweight tier | 0.50 | 0.05 | 3.00 | High-concurrency customer support, classification, light reasoning |
Suppose a request has 8,000 input tokens and 2,000 output tokens, with 6,000 input tokens hitting the cache and 2,000 missing it. At the high-capability tier, the estimate is:
- Uncached input: 2,000 × 5 / 1,000,000 = 0.01
- Cache-hit input: 6,000 × 0.5 / 1,000,000 = 0.003
- Output: 2,000 × 30 / 1,000,000 = 0.06
- Total: about 0.073
Without caching, the input cost is 8,000 × 5 / 1,000,000 = 0.04, and the total is about 0.10. Caching saves a clear amount, but output remains the main cost item in this example. Controlling output length is therefore just as important.
5. The Governance Loop: Metering, Attribution, Budgets, Degradation, and Regression
Cost governance is not a one-time optimization. It is an ongoing loop. Implement it in the following steps:
- Request-level metering: Record the request ID, tenant, feature, model tier, input tokens, cache-hit tokens, output tokens, retry count, routing reason, latency, and estimated cost.
- Multi-dimensional attribution: Aggregate costs by feature, tenant, session, prompt version, and model tier to find the dimensions where cost grows fastest.
- Budgets and quotas: Set daily and monthly budgets, tenant quotas, and per-request budgets. Trigger alerts at soft thresholds and degrade or throttle at hard thresholds.
- Degradation strategies: For high-cost scenarios, shorten the context, reduce parallel calls, disable nonessential tool calls, switch to a lightweight tier, or warm up the cache.
- Experiments and regression testing: Run A/B tests for prompt compression, cache key changes, and routing rule changes. Compare quality, latency, and cost to avoid saving money at the expense of output quality.
- Codify the rules: Write effective strategies into the gateway or the calling layer as defaults, including maximum output length, maximum turns, retry backoff, circuit breaking, and cost alerts.
Here is a sample implementation:
function estimate_cost(input_tokens, cache_hit_tokens, output_tokens, price):miss = input_tokens - cache_hit_tokensreturn miss * price.input+ cache_hit_tokens * price.cache+ output_tokens * price.outputfunction route(request, budget):if request.task_type in ["classification", "extraction"]:return "lightweight tier"if request.complexity_score < 0.4 and budget.remaining > 0:return "balanced tier"if request.is_critical:return "high-capability tier"return "balanced tier" // Default tier. On failure, fall back according to the rules.
Several common mistakes are worth avoiding. These include looking only at unit price and ignoring the output ratio, relying on a high cache hit rate without checking how many tokens actually hit, optimizing routing for accuracy without considering total cost, retrying without a limit, letting context grow without bound, and running multiple models in parallel without budget controls. The goal of cost governance is not to push spending as low as possible. It is to make every dollar spent explainable, controllable, and testable, while maintaining acceptable quality and latency. A monitoring and governance system built on token, cache, and routing data is what lets you explain why a bill spiked and make the next increase predictable.
