How to Calculate the Real Cost of LLM Inference: A Practical Guide
Comparing per-million-token list prices between LLM providers almost always leads to the wrong conclusion, because the actual bill depends on cache hit rate, the input-to-output token mix, and which time window requests fall into. This guide abstracts billing rules into a reusable cost model with Python code, explains why cache hit rate is the most fragile assumption, shows how to define peak and off-peak windows, and provides a method for converting subscription plans into an effective per-token price, along with a practical cost management checklist.
1. Why “Price Comparison” Almost Always Reaches the Wrong Conclusion
In LLM application cost assessments, the most common practice is to put two providers’ per-million-token prices side by side and conclude that one is “twice as expensive.” The problem is that the unit price on a price sheet is only one coefficient in the billing formula. What actually determines the bill is three variables: the cache hit rate, the ratio of input to output tokens, and the time window in which requests land.
The example from the original discussion is typical: one platform charges 0.115 CNY per million tokens for cache reads, while another charges 0.05 CNY during its discount window. Looking at that line item alone, the gap is indeed more than double. But once the hit rate and token mix are substituted into the full formula, the conclusion reverses: with 98% hits, 1.5% input, and 0.5% output, the cost per 100 million tokens is roughly 12.57 CNY versus 9.40 CNY; with 95% hits, it becomes 14.92 CNY versus 18.25 CNY. For the same pair of products, a 3-percentage-point change in hit rate completely inverts which one wins.
This shows that cost estimation must return to “effective cost” rather than “list price cost.”
2. Abstracting Billing Rules into a General Model
The billing of most inference services can be abstracted into four token categories:
- Cache read tokens: billed at a very low unit price after hitting a prefix cache;
- Uncached input tokens: billed at the standard input price;
- Output tokens: usually the most expensive, and the main cost source in long-text generation scenarios;
- Add-ons: such as batch async request discounts, long-context tiered pricing, and peak-hour premiums.
The general formula is as follows:
def cost_per_100m(cache_hit, in_ratio, out_ratio,p_cache, p_in, p_out):"""cache_hit: cache hit rate, 0~1in_ratio/out_ratio: share of input and output in total tokensp_*: corresponding unit price (CNY per million tokens)returns: cost per 100 million tokens (CNY)"""assert abs(cache_hit + in_ratio + out_ratio - 1) < 1e-6per_million = cache_hit * p_cache + in_ratio * p_in + out_ratio * p_outreturn per_million * 100
Substituting the two parameter sets above reproduces the reversal:
# Scenario A: high hit rateprint(cost_per_100m(0.98, 0.015, 0.005, 0.115, 4.0, 16.0))# Scenario B: slightly lower hit rateprint(cost_per_100m(0.95, 0.045, 0.005, 0.115, 4.0, 16.0))
The key point is that when the hit rate drops, the cached tokens that are lost do not disappear; they shift onto the standard input price. Cost is therefore highly sensitive to the hit rate, and the effect is amplified non-linearly.
3. Cache Hit Rate: The Most Fragile Assumption in the Cost Model
Hit rate is not a system property but a business property. It depends on three things:
- Prefix stability. Whether the system prompt, tool definitions, and few-shot examples remain byte-for-byte identical. Any timestamp, random ID, or dynamic ordering invalidates the prefix.
- Request arrival pattern. High-concurrency homogeneous requests hit easily; scattered requests with differing contexts produce a low hit rate.
- Cache lifetime and capacity. Caches have a time-to-live and a capacity limit, and burst traffic can evict cold data.
Engineering optimizations include: splitting prompts into a “stable segment + variable segment” with the stable segment placed first; normalizing variable content (field ordering, whitespace removal); replacing full concatenation of conversation history with structured references; and treating hit rate as a first-class metric in load tests rather than reverse-engineering it from the bill after the fact.
It is worth stressing that the gap between 95% and 98% looks small, but when the cache price and the input price differ by several times, it is enough to change the selection decision. Any cost report should therefore give a sensitivity range for the hit rate rather than a single-point number.
4. Time-Window Strategy: Define “Peak” Before Calling Anything Cheap
Discount windows (often called off-peak or night-time discounts in the industry) are the second most easily misread factor. What really needs confirming is not “whether a discount exists” but three things: which hours the discount covers, which time zone and working-day definition it uses, and whether it stacks with the cache discount.
The example in the original material shows that platforms define peak hours very differently: one limits peak to 4 hours per working day, while another’s window is clearly longer. The narrower the window, the more easily a workload “legitimately” falls into the discount zone; the wider the window, the more differently the same code can behave on the bill.
Architecturally, requests should be made deferrable: put batch jobs, offline summarization, code base indexing, and regression evaluation into a queue and consume them in bulk during off-peak windows, while keeping user-facing online interactions available at any time. This kind of change usually delivers more certain savings than switching models.
Online interactive requests ──► real-time inference (any time window)Offline task queue ──► bulk consumption in off-peak windows (async batch API)
5. Converting Subscription Plans to Pay-as-You-Go
Subscription plans (the Coding Plan category) are often described as “half the original price,” but verification requires unit conversion. The method has three steps:
- Take the plan’s stated usable volume (for example, the total tokens consumable per cycle);
- Using the same hit rate and token mix assumptions, calculate the equivalent amount of those tokens under pay-as-you-go;
- Divide the plan price by the equivalent amount to get the discount rate; then divide the plan price by the usable volume to get the “actual unit price per million tokens.”
The three data sets in the original material (118 CNY, 538 CNY, and 1078 CNY for different quotas) convert to 50%~70% of the original API price, meaning the plan is effectively a 30% to 50% discount. This range is meaningful: it means the plan’s discount is limited and quantifiable, and once the actual hit rate falls below the stated assumption or the share of peak-hour traffic rises, the discount is quickly eaten up and may even end up worse than pay-as-you-go.
The decision rule can be written as a simple inequality:
def plan_is_worth(plan_price, quota_tokens, unit_price_per_m,expected_hit, in_ratio, out_ratio,peak_ratio, peak_premium=1.0):base = cost_per_100m(expected_hit, in_ratio, out_ratio,unit_price_per_m * 0.1, unit_price_per_m,unit_price_per_m * 4)effective = base * (quota_tokens / 1e8) * (1 + peak_ratio * (peak_premium - 1))return effective > plan_price, plan_price / (quota_tokens / 1e6)
6. An Actionable Cost Management Checklist
- Build a unified metering layer: log cache-hit tokens, input, output, and time-window labels at the gateway to form aggregatable usage data, and connect it to monitoring, alerting, and logging services for trend and anomaly detection.
- Regress against a fixed baseline set: prepare a fixed set of requests, rerun them after every prompt or model version change, and compare hit rate and per-request cost to avoid “optimizing the prompt but paying more.”
- Run sensitivity analysis: report costs at 90%/95%/98% hit rates, and combined results at 0%/20%/40% peak-hour shares.
- Control output cost: the output unit price is usually the highest, so limiting unnecessary long outputs, adopting structured short outputs, and setting length caps for summarization tasks often pays off more than compressing input.
- Preserve exit flexibility: abstract model calls behind an internal interface with configurable routing and fallback policies, so cost conclusions are not bound to a single vendor’s pricing changes.
7. Conclusion
Real cost = billing unit price × token structure × time-window distribution, and missing any of the three leads to misjudgment. The cache hit rate is the largest variable, the time-window definition is the second, and the plan discount is only a coefficient that holds after those two are settled. Only by hardening the model above into code and dashboards can you produce numbers that withstand scrutiny in selection, scaling, and budget reviews. If you need unified capabilities for usage collection, task scheduling, and monitoring alerts, you can build your own metering and scheduling pipeline on top of Baidu AI Cloud’s object storage, message queue, container platform, and log monitoring products, keeping the estimation basis consistent and the results reproducible.
