Calculating LLM Token Costs: Hierarchical Routing and Caching Practices
Evaluating LLM costs goes beyond simply checking the price per million tokens. This article breaks down the real factors driving project expenses, including call volume, token consumption, cache hit rates, and billing rules. It provides a practical cost calculation model, explores strategies like hierarchical model routing and context management to reduce input tokens, and offers a checklist for optimizing and monitoring LLM expenditures over time.
1. Why Unit Price Alone Doesn’t Reveal Real Costs
Looking at the price per million tokens is a common first step when comparing LLM services. While unit price is a necessary baseline, it doesn’t directly represent actual project expenditures. Real costs are driven by three factors: API call volume, input and output token consumption per call, and additional billing conditions like cache hits, package quotas, and rate limits. Under different usage patterns, the same unit price can result in monthly bills that differ by multiples.
Therefore, you should normalize quotes to a single unit (e.g., cost per 100 million tokens) and compare them against your specific usage profile. Unit price only becomes a meaningful metric when placed within actual usage scenarios.
2. Understanding the Four Elements of Billing Structure
1. Input and Output Tokens
Input includes system prompts, conversation history, retrieved document chunks, and tool outputs. Output is the model’s generated content. Their unit prices usually differ, with output generally being more expensive. In long-context scenarios, input often accounts for the majority of consumption, so the savings from reducing invalid input typically outweigh those from compressing output.
2. Cache Hits
When a request’s prefix matches a recent one, the server may reuse pre-computed intermediate results, charging a lower unit price for that portion of the input. The hit rate thus becomes a critical cost variable. Placing fixed system prompts at the beginning of the request and dynamic content at the end helps improve hit rates.
3. Monthly Packages vs. Pay-As-You-Go
Packages offer fixed costs, suitable for stable and predictable traffic. Pay-as-you-go offers flexibility for volatile traffic or projects in the validation phase. Packages usually have quota limits; how overages are handled must be confirmed before procurement.
4. Rate Limits and Retries
Even with a sufficient budget, rate limits cap throughput. Batch tasks require queuing and backoff strategies. Retries consume tokens, and if failed requests aren’t identified promptly, retries can silently inflate costs.
3. Building a Cost Estimation Model
When estimating monthly costs, you can use the following formulas:
Cost per call = (Input tokens × Miss ratio × Miss price + Input tokens × Hit ratio × Hit price + Output tokens × Output price) ÷ 1,000,000
Monthly cost = Cost per call × Average daily calls × 30
The following sample code demonstrates the calculation process. All parameters are hypothetical and do not represent real quotes.
def monthly_cost(calls_per_day, input_tokens, output_tokens,hit_ratio, price_miss, price_hit, price_out):"""Unit: $ / Million tokens"""input_cost = input_tokens * ((1 - hit_ratio) * price_miss + hit_ratio * price_hit)output_cost = output_tokens * price_outper_call = (input_cost + output_cost) / 1_000_000return per_call * calls_per_day * 30# Assume: average 2000 calls/day, 20k input tokens, 1500 output tokens per call, 80% cache hit rateprint(round(monthly_cost(2000, 20000, 1500, 0.8, 1.0, 0.2, 4.0), 2))
Under these assumptions, the monthly cost is approximately $792. The hit rate is the most sensitive variable. If the hit rate drops from 80% to 30% while other conditions remain unchanged, the monthly cost rises to about $1272, an increase of over 60%. Therefore, use the actual hit rate from real logs rather than an ideal value during estimation.
4. Hierarchical Routing: Dividing Labor Between Main and Lightweight Models
Not every task requires the most powerful model. Exploratory subtasks like code retrieval, file location, log summarization, and format conversion demand less reasoning depth and can be offloaded to lightweight models. The main model handles task planning, critical decisions, and final generation. This architecture is commonly known in agent systems as hierarchical routing, or the main-agent and sub-agent pattern.
The routing logic can be straightforward:
def route(task_type: str) -> str:light_tasks = {"search", "summarize", "format", "extract"}return "light_model" if task_type in light_tasks else "main_model"
When implementing layering, note three points. First, build a small evaluation set for each type of subtask to ensure the lightweight model’s output quality is acceptable. Second, perform structural validation on the lightweight model’s output (e.g., checking if JSON is valid and fields are complete) to prevent errors from entering the main workflow. Third, log token consumption at each layer to verify whether layering actually reduces total costs.
5. Reducing Input Costs Through Context Management
Input tokens represent the primary expense for most projects, making context management a direct lever for cost reduction.
- Maintain a stable prefix: Do not frequently change fixed content like system prompts and tool definitions, as this prevents cache hits.
- Prune conversation history: For conversations exceeding a certain number of turns, replace older history with a summary, retaining only facts and constraints relevant to the current task.
- Selectively retrieve results: Set limits on the number and length of retrieved document chunks. Sort them by relevance and truncate to avoid injecting a large volume of weakly related content into the context.
- Limit output length: Constrain response length using the maximum output tokens parameter, and prompt the model to answer concisely to reduce unnecessary generation.
These measures typically do not compromise output quality but directly lower the bill. After implementation, track quality metrics to ensure no information is lost.
6. Price Volatility and Supply Elasticity
The pricing and billing rules of LLM services change rapidly. Price adjustments, cache strategy updates, or package modifications can invalidate previous cost estimates. To mitigate these risks, adopt an engineering approach.
First, encapsulate a unified API interface so that business logic depends only on internal interfaces, decoupling it from specific provider request formats. Second, put prompts and evaluation sets under version control to facilitate quick regression testing when switching providers. Third, periodically recalculate costs using real traffic data instead of relying on conclusions from months ago. Fourth, maintain backup solutions for critical services and proactively estimate switching costs, including the workload for evaluation, prompt adjustment, and output format adaptation.
Switching costs are frequently underestimated. Different services vary in instruction following, output formatting, and context length support. Simply swapping an API endpoint rarely guarantees consistent performance. Therefore, price advantages must be evaluated alongside switching costs to reach a reliable conclusion.
7. How to Judge if the Unit Cost is Reasonable
Some practitioners use rough benchmarks like “cost per 100 million tokens” to describe acceptable price ranges, which offers intuitive understanding. However, whether a price is reasonable ultimately depends on the business’s profit margins.
A more practical approach is to calculate the cost per unit of business output—such as the cost per Q&A, per generated report, or per automated code modification—and compare it against the value generated by that output. If an automated process replaces several minutes of manual labor, a higher cost per call might still be justifiable. Conversely, if the feature is merely auxiliary, costs must be strictly controlled.
8. Implementation Checklist
- Collect real input and output token distributions, grouped by task type.
- Measure cache hit rates and log the number of cache hits and misses.
- Segment model layers based on task type, and establish quality evaluation sets for each layer.
- Set monthly budgets and usage alerts, triggering manual review when thresholds are exceeded.
- Conduct periodic reviews of prompts and context structures to remove redundant content.
- Re-test costs and quality quarterly, adjusting routing rules and package choices based on the results.
The core of LLM cost management is considering unit price, call volume, hit rate, and quality together within a unified framework. As long as the estimation methodology is consistent, teams can quickly recalculate and adapt when billing rules change.
