A Practical Guide to Calculating the Real Cost of LLM Inference
Comparing per-million-token prices alone almost always leads to wrong conclusions about LLM inference cost. This guide explains why, and shows how to build a reusable cost model based on four variables: tiered pricing, cache hit rate, input-to-output ratio, and off-peak discounts. It includes a sample estimation function, sensitivity analysis showing how a 3-point change in hit rate can reverse which option is cheaper, guidance on converting subscription plans back to an effective per-token price, and a pipeline for turning cost estimation into an ongoing engineering practice.
1. Why Comparing Unit Prices Almost Always Gives the Wrong Answer
When evaluating LLM inference costs, the most common approach is to put the per-million-token price of two options side by side and conclude that one is “twice as cheap.” In real workloads, that conclusion rarely holds, for three reasons:
- There is more than one billing component. Mainstream inference services typically split charges into at least four parts: cache-hit reads, cache-miss input, output generation, and in some cases write or storage fees. Comparing only one of them is like using pocket change to represent the total bill.
- The multipliers between components differ. Cache read prices are usually far below cache-miss input prices, while output prices are typically much higher than input prices. So “cache is twice as cheap” and “total cost is twice as cheap” are two completely different claims.
- Real traffic is a distribution, not a single point. Hit rate fluctuates with session length, how heavily the system prompt is reused, and how often the knowledge base is updated. The input/output mix drifts significantly with the type of workload (long-document summarization vs. code completion).
The right approach is not to compare unit prices, but to build a cost model that takes unit prices, hit rate, mix, and time-of-day into account and computes a weighted result.
2. Building a Reusable Cost Model
Define:
p_cache: cache-hit read price (CNY per million tokens)p_in: cache-miss input pricep_out: output priceh: cache hit rater_in: share of total tokens that are cache-miss inputr_out: share of total tokens that are outputN: total token volume
Total cost is then:
Cost = N * ( h * p_cache + r_in * p_in + r_out * p_out ) / 1_000_000
A sketch of a function that is easy to implement:
def estimate_cost(total_tokens, hit_rate,p_cache, p_in, p_out,in_ratio=0.015, out_ratio=0.005):"""Estimate inference cost (CNY) from tiered unit prices."""parts = {"cache": hit_rate * p_cache,"input": in_ratio * p_in,"output": out_ratio * p_out,}per_million = sum(parts.values())return total_tokens * per_million / 1_000_000, per_million
The single most important point here: per_million is the effective unit price that can actually be compared across options. It normalizes different billing structures onto the same scale. Any vendor, any plan, any discount ultimately has to be converted into this number before a comparison means anything.
3. Variable One: Cache Hit Rate Is the Most Sensitive Lever
Consider an illustrative example. Option A has a cache read price of 0.115 CNY per million tokens, with cache-miss input and output set at common industry multipliers; Option B has a cache read price of 0.05 CNY per million tokens, with its remaining items set from its own price list. In a “high hit rate + very low output share” scenario:
- At a 98% hit rate, 1.5% input, and 0.5% output, the effective unit prices are roughly 12.6 and 9.4 CNY per million tokens, so the option with the lower cache price wins;
- When the hit rate drops to 95%, the effective unit prices are roughly 14.9 and 18.3 CNY per million tokens, and the ranking flips outright.
The same price lists, and a mere 3 percentage points of hit rate reverses the order. This explains a common puzzle: why someone else’s bill is several times lower than yours. Hit rate should be governed as a first-class metric, using measures such as:
- Keep the system prompt, tool definitions, and few-shot examples at the front and byte-for-byte stable, avoiding timestamps, random IDs, or dynamic counters injected into the prefix;
- Place volatile content (user input, retrieved snippets) at the end of the prompt;
- Control the cadence of knowledge base updates so an entire prefix cache is not invalidated frequently;
- Set hit-rate thresholds in the monitoring and alerting system, rather than watching only P99 latency.
4. Variable Two: The Input/Output Mix Determines Cost Structure
The ratio of r_in to r_out almost single-handedly determines the model selection conclusion. Tasks like long-document summarization and code base comprehension are input-heavy, so cache and input prices dominate the bill; generative writing and structured extraction are output-heavy, so the output price dominates. Because the output price is usually several times the input price, a workload that pushes its output share from 0.5% to 5% can see costs rise several-fold, and any advantage from “cheaper cache” is quickly diluted.
The optimization direction is to compress unproductive output: cap the maximum generation length, use structured formats to cut redundant wording, and hand deterministic computation to a rules engine or conventional program so the model only handles semantic judgment.
5. Variable Three: Peak Hours and Off-Peak Discounts
Many inference services offer discounted prices during specific windows, and off-peak unit prices can be significantly lower than peak ones. Two things matter when doing cost estimation:
- Peak-hour definitions differ. Some define an overnight off-peak window by calendar day; others designate a few hours of weekday daytime as peak and treat the rest as discounted. When comparing options, you must first align on the “share of peak hours.”
- Business traffic does not necessarily overlap with discount windows. A coding assistant aimed at daytime office users sees requests concentrated in weekday daytime, which falls exactly in the peak band, so the theoretical discount may never be captured.
The recommendation is to build a weekly traffic profile and compute the effective discount rate after weighting:
effective_price = peak_ratio * p_peak + (1 - peak_ratio) * p_offpeak
6. Variable Four: How to Convert Subscription Plans
Monthly subscription plans (such as those aimed at AI coding tools) are often described as “a certain discount off list API pricing,” but the conversion has to come back to an effective unit price. Taking one class of plan as an example: if a 118 CNY monthly fee corresponds to roughly 317 million tokens per week, 538 CNY to roughly 1.9 billion tokens, and 1078 CNY to roughly 4.433 billion tokens (all official figures under high-hit-rate, non-peak assumptions), the converted effective unit price of the plans lands roughly in the 50%–70% range of pay-as-you-go.
Three decision rules follow:
- A plan’s value depends heavily on whether you can actually consume the full quota. When you cannot, the effective unit price climbs sharply and may end up higher than pay-as-you-go.
- Plans usually bind peak-hour restrictions and a model scope, and revert to pay-as-you-go billing once you exceed the quota, so the probability of overage needs to be estimated.
- When a team shares a plan, pooling the quota significantly improves utilization, but internal quotas and usage dashboards are also needed so a single task does not drain the allowance.
7. Implementation: Turn Estimation into a Pipeline
- Instrument real distributions: log cache hits, input tokens, output tokens, and timestamps for every request.
- Replay offline to do the math: feed the same traffic into different price lists and plan models, and output an effective-unit-price comparison.
- Set governance targets: set improvement targets for hit rate, output share, and peak share, and bring all three into monitoring and alerting.
- Decouple at the architecture level: wrap model calls behind a unified gateway so switching vendors or adjusting routing policy does not require business code changes; general cloud capabilities such as object storage, message queues, container platforms, and logging services can carry the asynchronous and observability requirements.
- When validating on a platform such as Baidu AI Cloud, prefer general-purpose capabilities (monitoring and alerting, logging services, container platforms) to build the load-testing and cost-accounting environment, and make decisions with data rather than unit-price labels.
8. Conclusion
Real cost = tiered unit prices × hit rate × input/output mix × time-of-day discount, and missing any one of the four leads to a misjudgment. Treat the effective unit price as the only comparison basis, treat hit rate and output share as the core governance metrics, and convert plans back to a per-token price before deciding. That is what it takes to make model selection and usage planning decisions that hold up against the actual bill.
