How to Calculate the Real Cost of LLM APIs: A Practical Guide
Comparing per-million-token list prices is mathematically valid but practically misleading, because LLM API pricing is a multi-variable, tiered problem. This guide shows how to compare the metric that actually matters—cost per effective token—using a weighted formula built from cache hit price, uncached input price, output price, and cache hit rate. It covers how to turn hit rate from a guess into a measured signal through instrumentation and prefix stability, how peak-hour pricing changes weekly weighted cost, how to convert subscription plans into an effective per-token price, and a checklist of cost-reduction practices. You will get a four-dimension cost model you can calibrate with production telemetry.
1. Why unit price comparisons almost always lead to the wrong conclusion
The most common argument in LLM API selection is that “one vendor charges twice as much as another for cached tokens per million tokens.” That statement is mathematically correct but nearly meaningless in engineering terms, because it compresses a multi-dimensional, tiered pricing problem into a single-point price comparison.
Billing on mainstream platforms is typically determined by four variables together: the unit price of the cached portion, the unit price of the uncached input portion, the unit price of the output portion, and whether different time windows carry different prices. Any approach that compares only one of these will produce a conclusion that can differ from the actual bill by several times. What really needs to be compared is not the unit price but the cost per effective token—the weighted result under a given cache hit rate and input/output mix.
Let the cached unit price be p_c, the uncached input unit price be p_i, the output unit price be p_o, the cache hit rate be h, the input share be a and the output share be b (a + b = 1). Then the cost per million tokens is:
cost = 1e6 * ( h*a*p_c + (1-h)*a*p_i + b*p_o )
This formula explains a counterintuitive phenomenon: when h is high, cost is dominated almost entirely by p_c, and the vendor with the cheaper cache price wins. When h falls below a certain threshold, the uncached input term amplifies quickly, and the vendor with a higher cache price but a lower input price becomes cheaper. The two cost curves must intersect somewhere, and the key to selection is judging which side of that intersection your real hit rate falls on.
2. Bringing the hit rate back from an optimistic assumption to a measurable metric
Most estimation errors come from picking h arbitrarily. In engineering, the hit rate should be treated as an observable metric rather than an estimated parameter:
- Instrumentation: on the caller side, record the prompt prefix fingerprint and the hit flag, then aggregate the real h hourly.
- Layered observation: track hit rates separately for four prefix categories—system prompts, tool definitions, long documents, and multi-turn history. Their magnitudes usually differ substantially.
- Prefix stability governance: move volatile content (timestamps, random IDs, user nicknames) from the head of the prompt to the tail, so a single change does not invalidate the entire cached segment.
Illustrative aggregation logic:
def rolling_hit_rate(events, window=3600):recent = [e for e in events if e.ts > now() - window]hit = sum(1 for e in recent if e.cached_tokens > 0)return hit / max(len(recent), 1)
In practice, single-turn-heavy applications with a stable system prompt and a fixed tool set can achieve a very high hit rate, while retrieval-style applications that concatenate a brand-new long document every turn tend to see a very low one. The former should prioritize the cache unit price; the latter must prioritize the input unit price.
3. The real impact of time-based differentiated pricing
Some platforms charge higher prices during peak hours, and the difference lies in how long the peak window is defined to be. If one option’s peak window is only four hours per weekday while another covers a longer span of the day, their weighted average prices will differ markedly under the same call distribution. When estimating, expand the full 168 hours of a week and convolve the time-window prices with your traffic distribution, instead of using one vague “average price.”
weekly_cost = Σ( tokens_h * price_h ) for h in 168 hours
For offline batch workloads, a queue can shift deferrable requests into off-peak windows. For interactive requests, heavy tasks during peak hours should be downgraded to a smaller model or served from cached results, which flattens the peak.
4. How to convert subscription plans into comparable numbers
Subscription plans (the Coding Plan type) usually state a “monthly fee plus a consumable token allowance.” The conversion is:
effective_price = monthly fee / total tokens available per month
Placing that alongside the weighted pay-as-you-go cost is what reveals the plan’s real discount range. Three things need attention: the allowance is often settled weekly and cannot roll over across weeks; the allowance is consumed faster during peak hours; and the allowance magnitude differs far more between plans than the price does. A fairly stable combination is therefore to move medium- and high-frequency users onto a plan while keeping low-frequency users on pay-as-you-go. Plans also suit interactive coding, where prefixes repeat heavily; batch jobs are better served by pay-as-you-go or reserved throughput.
5. An actionable cost-reduction checklist
- Fix the prefix: keep system prompts, tool descriptions, and examples at the very front and manage them with versioning.
- Trim context: summarize and compress earlier turns to control the volume of uncached input.
- Constrain output: use structured output and length caps to keep b from inflating—output is usually the most expensive part.
- Tier your models: route intent recognition and format conversion to lightweight models, and complex reasoning to larger models.
- Close the observability loop: wire cost metrics into monitoring and alerting, with per-business-line unit cost budgets and thresholds.
- Recalculate regularly: hit rates and traffic distributions drift with each release, so the estimation sheet needs a monthly refresh.
6. Conclusion
The right way to compare real cost is to build a four-dimension tradeoff model covering cache hit rate, input/output mix, time-window distribution, and plan allowance, then continuously calibrate its parameters with production instrumentation. Under the general pay-as-you-go and subscription billing systems offered by platforms such as Baidu AI Cloud, this method applies directly: measure h and the time-window distribution first, then compute the weighted unit price, and finally decide between pay-as-you-go, a plan, or a mix of both.
