How to Calculate the Real Cost of LLM Inference: A Practical Guide
Comparing per-token prices alone almost always leads to the wrong LLM cost decision. This guide shows why real bills depend on three coupled variables—cache hit rate, input-to-output token ratio, and request timing—and provides a code-based cost model to calculate them. You will learn how to find the crossover hit rate where two pricing plans reverse, measure and improve prefix cache hits, factor peak-hour pricing into effective cost, and convert subscription plans into equivalent pay-as-you-go rates. A final checklist covers model setup, P90-based plan selection, off-peak batch scheduling, and monthly cost reviews.
1. Why Per-Token Price Comparisons Almost Always Get It Wrong
When deploying LLM applications, the most common decision-making mistake is comparing just two numbers: the cache-hit price and the standard input price. A real bill is never a linear sum of unit prices. It is the combined result of three variables: the cache hit rate, the input-to-output token ratio, and the time distribution of requests. The observation in the source material that “the same set of prices leads to completely reversed conclusions under different hit rates” is a direct result of these three variables coupling together. In high-hit-rate scenarios, the cache price is amplified by nearly two hundred times in weight and becomes the dominant term. When the hit rate drops by five percentage points, the volume of tokens falling back to the standard input price rises quickly, and the cost structure switches from “cache-dominated” to “input-dominated” almost instantly.
Therefore, any unit-price comparison that ignores your traffic characteristics has no decision-making value. The right approach is to first characterize the statistical properties of your own traffic, then plug them into a unified cost model.
2. The Cost Model: Writing the Bill as a Computable Formula
Let the total token count be N, the cache hit rate be h, the input share be a, and the output share be b (a + b = 1). Let the cache-hit price, standard input price, and output price be p_cache, p_in, and p_out. The cost per token is:
def cost_per_token(h, a, p_cache, p_in, p_out):b = 1.0 - areturn h * p_cache + (1 - h) * a * p_in + b * p_out# Use "per 100 million tokens" as the unit; prices are in CNY per million tokensdef cost_per_100m(h, a, p_cache, p_in, p_out):return cost_per_token(h, a, p_cache, p_in, p_out) * 100
This formula reveals three important conclusions.
First, cost is piecewise linear in the hit rate, with a slope determined by (p_cache − a·p_in). Because the cache price is usually far below the standard input price, this slope is negative: each percentage point increase in hit rate lowers cost roughly linearly.
Second, there exists a “crossover hit rate” h* at which the conclusions of two pricing plans reverse. Setting the two expressions equal gives:
def cross_hit_rate(a, c1, c2):# c = (p_cache, p_in, p_out) for each of the two plansk1 = c1[0] - a * c1[1]k2 = c2[0] - a * c2[1]const1 = a * c1[1] + (1 - a) * c1[2]const2 = a * c2[1] + (1 - a) * c2[2]return (const2 - const1) / (k1 - k2)
Third, the output share b is an “unoptimizable term.” No matter how high the cache hit rate is, output tokens are always billed in full at the output price. In output-intensive scenarios such as long-form generation and code completion, the output price carries far more weight than the cache price.
3. Reproducing the Example: How Hit Rate Reverses the Conclusion
Using an illustrative set of prices (CNY per million tokens), Plan A has a higher cache price and a lower standard input price; Plan B has an extremely low cache price and a higher standard input price. Take an input share of 1.5% and an output share of 0.5% (the typical RAG shape of long context, short output):
- At a 98% hit rate: A is about 12.6 CNY per 100 million tokens, B is about 9.4, so B is better;
- At a 95% hit rate: A is about 14.9 CNY per 100 million tokens, B is about 18.3, so A is better.
A three-percentage-point difference in hit rate produces roughly a 50% cost reversal, with the crossover point near 96%. The engineering implication is clear: the low-cache-price plan is extremely sensitive to hit rate and is a “high-leverage” choice, while the plan with a higher cache price but cheaper standard input is more robust. Before choosing, you must measure whether your pipeline’s hit rate can reliably stay above the crossover point, rather than budgeting on ideal values.
4. Hit Rate Is Not a Constant: How to Measure and Improve It
The hit rate is determined by prefix consistency. Common sources of mismatch include: timestamps, random IDs, or usernames embedded in the system prompt; unstable ordering of few-shot examples; tool results concatenated into the prefix; history rewritten or truncated in multi-turn conversations; and retrieval snippet order changing under concurrency.
Engineering practice should do three things: put stable content first and volatile content last; normalize the prefix and fix the serialization order; and use shadow traffic during load testing to measure the actual hit rate, planning capacity by P50/P90 percentiles rather than the mean.
[fixed system instructions][fixed examples][stable knowledge snippets] | [session ID/timestamp/retrieval results]└──────────── cacheable prefix ────────────┘ └── volatile suffix ──┘
5. Time-of-Day Strategy: Folding “Peak Hours” into Cost
Beyond caching, the time dimension also affects the bill. A common industry practice is to set a few “peak hours” each day, during which standard pricing applies or quotas are reduced, while off-peak periods receive a discount. Factoring time into the model:
def effective_cost(cost, peak_hours_per_day, peak_ratio=1.0):ratio = peak_hours_per_day / 24.0return cost * (ratio * peak_ratio + (1 - ratio))
Four peak hours correspond to a time weight of about 16.7%. This means scheduling batch jobs (offline summarization, log analysis, batch code review, evaluation regression) into off-peak windows can significantly lower the average unit price without sacrificing interactive experience, while user-facing online pipelines should build redundancy outside the peak window.
6. Converting Subscriptions and Pay-as-You-Go to an Equivalent Basis
The way to evaluate a subscription coding plan is to “convert to an equivalent original-price quota”: divide the plan price by the token quota included in that tier to get an implied unit price, then compare it with the pay-as-you-go price to derive the discount range. In practice, low and mid tiers have small quotas, so their implied unit price is around 60–70% of the original price; high tiers offer deeper discounts, but only hold if your real usage can fully consume the quota.
Conversion script:
def plan_value(price, weekly_tokens, unit_price):return price / (weekly_tokens / 1_000_000) / unit_price# A result < 1 means the plan is more cost-effective; the closer to 0, the bigger the discount
Decision rule: first measure the median and peak weekly token usage over two weeks. If the median falls between two tiers, choose the lower tier and send overflow to pay-as-you-go; only if the peak is consistently maxed out and concentrated off-peak does the higher tier become economical.
7. Conclusion and Implementation Checklist
- Build a unified cost model and calculate with code, not spreadsheets;
- Measure the cache hit rate before launch, and compare the P90 value against the crossover hit rate when choosing a plan;
- For output-intensive workloads, look at the output price first—cache optimization yields limited gains;
- Schedule batch jobs off-peak to push the peak-hour weight as low as possible;
- Convert plans to an “equivalent original-price quota” and use real usage percentiles to decide the tier;
- Review prices and hit rates monthly and recompute the crossover point.
In related practice at Baidu AI Cloud, these methods can be implemented alongside general cloud capabilities such as monitoring/alerting and log services: collect token usage, hit rate, and time distribution as first-class metrics to build a cost dashboard that supports continuous review, turning cost optimization from a one-off calculation into ongoing operations.
