LLM Inference Cost Calculation: Blended Unit Pricing with Cache Hits
As large language model (LLM) applications transition from demos to production, accurately estimating inference costs is crucial. Estimating expenses using a single "price per million tokens" often leads to significant billing discrepancies because an inference request involves three distinct token categories: cached inputs, uncached inputs, and generated outputs, each billed at a different rate. This article explores how to calculate a "blended unit price" that integrates these proportions and rates for budgeting and quoting. It covers the mathematical derivation, methods for measuring reliable traffic ratios, engineering practices to improve cache hit rates, and broader cost perspectives such as latency and model selection.
LLM Inference Cost Calculation: Blended Unit Pricing with Cache Hits
1. Why We Need a “Blended Unit Price”
As LLM applications move from the demonstration phase to large-scale production, inference costs have become a core issue that technical teams must face directly. The token consumption of a typical LLM inference request is not a monolith; it consists of multiple components, and different parts often correspond to different billing rates. If you still estimate costs using a single metric like “price per million tokens,” the result may deviate from the actual bill by several multiples.
Specifically, the tokens in a single request can generally be divided into three categories:
- Cached Input Tokens: In many LLM service platforms, frequently recurring long prefixes (such as system prompts, historical context in multi-turn conversations, or repeatedly referenced document chunks in Retrieval-Augmented Generation scenarios) can be cached on the server side. Tokens that hit the cache are processed at a significantly lower cost than freshly computed ones, so the industry generally applies a lower “read” price to this portion.
- Uncached Input Tokens: New user inputs, newly retrieved content, etc., in each request must go through the full prefill computation and are billed at the standard “input” price.
- Output Tokens: The response content generated token by token by the model. The decoding process is compute-intensive, usually carries the highest unit price, and is billed at the “output” price.
This leads to the core question of this article: In a real-world workload, cached, uncached, and output tokens each occupy a certain proportion. How do we combine these proportions with their respective prices to obtain a “blended unit price” that can be directly used for budgeting and quoting?
2. Deriving the Blended Unit Price
Suppose that through statistical analysis of business traffic, we obtain the following empirical proportions:
- 80% of token consumption belongs to cache hits;
- 10% belongs to uncached new inputs;
- 10% belongs to model-generated outputs.
The blended unit price is the weighted average of the prices of each part:
Blended Price = 0.8 × Read Price + 0.1 × Input Price + 0.1 × Output Price
The unit follows the original unit in the billing table, typically “currency per million tokens.”
The essence of this formula is the calculation of expected value: treating each token as a random variable, which is billed at the read price with a probability of 0.8, at the input price with a probability of 0.1, and at the output price with a probability of 0.1. The expected cost of a single token is the weighted sum above. When the request volume is large enough, the actual total cost will converge to “Total Tokens × Blended Price,” which is a reflection of the law of large numbers in cost accounting.
Consider a schematic example: Assume a service has a read price of 1 per million tokens, an input price of 5 per million tokens, and an output price of 15 per million tokens (actual prices are subject to the official billing page of the service used). Then:
Blended Price = 0.8 × 1 + 0.1 × 5 + 0.1 × 15 = 0.8 + 0.5 + 1.5 = 2.8 per million tokens
As you can see, the caching mechanism makes the blended price significantly lower than the result of a naive estimate like “half input, half output.” This is the direct economic value brought by prefix caching.
3. How to Obtain Reliable Proportion Coefficients
The formula itself is simple; the difficulty lies in the fact that the proportion coefficients must be measured from real traffic, not guessed. The following steps are recommended:
Step 1: Enable usage detail collection. Mainstream LLM services typically return the token usage details for the current request in their responses, including the number of input tokens, output tokens, and the number of cache hits. On the application side, these fields should be fully recorded into a logging service.
Step 2: Aggregate by business dimension. Cache hit rates vary drastically across different business scenarios: a customer service Q&A with a fixed system prompt may have a very high hit rate, whereas an open-ended creative scenario with entirely different inputs each time may have a hit rate close to zero. You should aggregate statistics separately by business line and session type to avoid masking structural differences with a single average.
Step 3: Dynamic updates via sliding windows. User behavior drifts over time. It is recommended to recalculate the proportions on a daily or weekly window and monitor the trend. If the hit rate drops significantly, it may indicate a change in the prompt structure (e.g., placing mutable content before the prefix), which requires investigation.
A simplified statistical code example is as follows:
class TokenCostTracker:def __init__(self, read_price, input_price, output_price):self.read_price = read_priceself.input_price = input_priceself.output_price = output_priceself.cached = 0self.uncached = 0self.output = 0def record(self, cached_tokens, uncached_tokens, output_tokens):self.cached += cached_tokensself.uncached += uncached_tokensself.output += output_tokensdef blended_price(self):total = self.cached + self.uncached + self.outputif total == 0:return 0.0return (self.cached * self.read_price +self.uncached * self.input_price +self.output * self.output_price) / totaldef total_cost(self):total = self.cached + self.uncached + self.outputreturn total * self.blended_price() / 1_000_000
Directly accumulating actual costs is certainly the most accurate, but the value of the blended unit price lies in “prediction”: before launching a new feature or without historical bills, you can quickly calculate the budget scale using estimated proportions.
4. Engineering Practices to Improve Cache Hit Rates
Since tokens that hit the cache are significantly cheaper, increasing the hit rate becomes the most direct way to reduce costs. Here are several widely recognized effective practices:
- Stable prefix design. Caching usually works by matching prefixes. Therefore, immutable or infrequently changing content (system instructions, role settings, tool definitions, long documents) should be placed at the beginning of the prompt, while highly mutable content (timestamps, user IDs, current questions) should be placed at the end. Any random content inserted in the middle of the prefix will render the subsequent parts unable to hit the cache.
- Avoid meaningless variations. Concatenating timestamps precise to the second or randomly generated identifiers into system prompts will completely destroy the cache. If time information is necessary, consider reducing the precision or moving it into the user message.
- Maintain context continuity in multi-turn conversations. Conversation history naturally forms a continuously extending prefix. Maintaining session continuity allows the historical portion to continuously hit the cache, meaning you only pay for the new input in each turn.
- Centralized batch request processing. For offline batch processing tasks, sending requests that share the same context together can increase the probability of cache reuse.
5. Cost Perspectives Beyond the Blended Price
Finally, it is important to note that the blended unit price model has its boundaries of applicability. First, the proportion coefficients are statistics, and the prediction error for a single small-traffic business may be large; it should be used in conjunction with confidence intervals. Second, beyond token billing, hidden costs such as latency and concurrency limits should also be considered—cache hits not only save money but typically also reduce Time To First Token (TTFT), which is equally important for user experience. Third, when selecting models, you should substitute the blended price into the pricing tables of different models for comparison, rather than just looking at the list price, because the leverage effect of the hit rate on total cost often exceeds the difference in unit prices themselves.
In summary, the concise formula “Blended Price = Cache Hit Ratio × Read Price + Uncached Ratio × Input Price + Output Ratio × Output Price” connects engineering capabilities across three levels: understanding the billing model, statistical analysis of traffic, and prefix cache optimization. Mastering it means mastering the fundamentals of LLM cost governance.
