How to Calculate the Real Cost of LLM APIs
A practical guide to estimating the true cost of large language model APIs. It explains why comparing per-million-token prices alone leads to wrong conclusions, breaks the bill down into cache-hit input, regular input, output, and peak-hour pricing, and shows how to model each factor, convert subscription plans into an effective unit price, find the break-even cache hit rate, and account for hidden engineering costs. Readers get a repeatable four-step measurement workflow and sample Python snippets for cost modeling and break-even analysis.
1. Why Comparing Unit Prices Almost Always Gives the Wrong Answer
In LLM application cost assessments, the most common mistake is subtracting one vendor’s “price per million tokens” from another’s to decide who is cheaper. This ignores a basic fact: the bill for a single request is not determined by one price, but is a weighted result of several pricing dimensions.
A typical call involves at least four billing items: input tokens that miss the cache, input tokens that hit the cache, output tokens, and the differentiated pricing some platforms apply during peak hours. The unit prices of these four often differ by an order of magnitude, so any unit-price comparison divorced from the call structure reflects only the numbers on the price sheet, not actual spending.
Worse, these variables are not static. Cache hit rate may be very low right after launch, then climb gradually as system prompts and knowledge bases stabilize; traffic distribution differs between day and night, and so does the share that falls into peak windows. The same code can therefore produce completely opposite cost conclusions at different stages.
2. The Cost Model: Breaking the Bill into Four Computable Items
Let total tokens be T, cache hit rate be h, input share be α, output share be β (usually α+β≈1), cached input unit price p_c, regular input unit price p_i, and output unit price p_o. Unit cost can be written as:
def cost_per_1m(total_tokens, hit_rate, in_ratio,p_cache, p_input, p_output):cached = total_tokens * hit_rate * in_ratioplain = total_tokens * (1 - hit_rate) * in_ratiooutput = total_tokens * in_ratio * 0 + total_tokens * (1 - in_ratio)return (cached * p_cache + plain * p_input + output * p_output) / 1e6
This formula reveals three important patterns.
First, although the cached unit price is low, it applies only to “the portion of input that hits,” so its leverage is limited. When the hit rate drops from 98% to 95%, what changes is 3 percentage points of regular input, and those 3 points are billed at several times, or even more than ten times, the cached price. Total cost therefore jumps non-linearly.
Second, output is always a cost amplifier. Output tokens are usually the most expensive part and cannot be optimized by caching, so in summarization and code-completion scenarios with “little input, a lot of output,” even a few percentage points of increase in the output share moves the total noticeably upward.
Third, the cache hit rate has a threshold effect. Plotting hit rate on the horizontal axis and unit cost on the vertical axis gives a curve that is flat in the high-hit-rate region and steep in the low-to-mid region, and two curves with different price sheets cross at some hit rate. The optimal choice on the left of the crossing point is the opposite of the one on the right, which is the mathematical root of why “who is cheaper” has no single answer.
3. Folding Peak-Hour Pricing into the Model
Besides caching, the second frequently overlooked variable is time-of-day pricing. A common industry practice is to split the day into peak and off-peak, with peak prices marked up and off-peak prices marked down, and peak windows vary widely in length: some are set for a few hours a day, others cover the entire daytime of a workday.
The right way to handle this is to introduce the “peak traffic share” γ and use a weighted average instead of a single-point price:
effective unit price = γ × peak price + (1 - γ) × off-peak price
γ is determined by the business traffic curve, not by the calendar. An overnight batch job serving users in other regions may have a γ close to 0; an office-hours coding assistant may have a γ above 0.6. So when choosing a service, first measure the actual time distribution of requests, then plug it into the formula, rather than assuming “off-peak” by default.
4. Converting Subscription Plans and Pay-as-You-Go into Equivalent Terms
The pricing logic of monthly plans is completely different from pay-as-you-go: it converts uncertain token consumption into a fixed monthly payment, and is essentially a capacity reservation contract. To judge whether a plan is worthwhile, convert it into an “effective unit price”:
effective unit price = monthly plan fee / total monthly tokens includeddiscount rate = effective unit price / pay-as-you-go price under the same conditions
With the plan structures common in the industry, and assuming a relatively high cache hit rate, the effective unit price often lands between 50% and 70% of the pay-as-you-go list price, roughly a 40% discount. But this discount is not a constant: it is affected by both the hit rate and the peak share. If the actual hit rate is lower than the assumption the plan calculation relies on, the usable token total shrinks, the effective unit price moves up, and the discount may narrow to 30% or less.
So plan decisions should follow a simple principle: a monthly plan beats pay-as-you-go only when the conservatively estimated monthly consumption is clearly below the plan quota and the peak traffic share is under control; for businesses with volatile traffic or still in validation, pay-as-you-go carries less risk exposure.
5. A Measurement Workflow You Can Actually Apply
It is worth fixing cost assessment into four steps so every discussion does not start from zero:
- Sample: instrument logging to measure the real distribution of input and output tokens and of request timing, covering at least one full business cycle.
- Model: use the formulas above to compute a unit-cost matrix across different hit rates and peak shares.
- Find the crossing point: solve for the hit rate at which two options cost the same, and determine which side the business is on.
- Review: regress the model against the actual bill every month and correct estimation bias in the hit rate and γ.
An illustrative comparison script:
def break_even_hit(p_cache_a, p_input_a, p_out_a,p_cache_b, p_input_b, p_out_b, in_ratio):# If the output term is identical it cancels out; compare the input side onlybase_a = p_input_a * in_ratiobase_b = p_input_b * in_ratiodelta = (p_cache_a - p_input_a) * in_ratio - (p_cache_b - p_input_b) * in_ratioreturn (base_b - base_a) / delta if delta else float('inf')
6. The Third Category of Cost That Is Easy to Miss
Token fees are only part of the bill. Three kinds of hidden engineering spending are worth counting in total cost of ownership: first, duplicate billing from retries and failed requests, where a poor timeout-retry policy can double actual consumption; second, context bloat, where carrying the entire conversation history without trimming makes input grow linearly with session length; third, observability cost, where logging services, monitoring alerts, and retention policies for object storage can, without sampling and lifecycle management, end up costing close to the inference bill itself over time.
The corresponding optimizations are fairly mature: stabilize system prompts and high-frequency prefixes to raise cache hits; summarize and trim history with compression and a sliding window; schedule non-real-time jobs into off-peak windows; use a unified gateway layer to aggregate usage and alert on quotas. If the application runs on a container platform or function compute, elastic scaling can also push idle-time resource usage to a minimum.
7. Conclusion
Real cost = cache hit rate × input/output ratio × time-of-day structure × billing model. Miss any one of the four and the conclusion may be reversed. Engineering teams should treat cost measurement as a continuously running engineering capability rather than a one-off procurement comparison: first quantify your own traffic characteristics, then compare options horizontally with one unified model, and finally close the loop by calibrating against real bills. Only then can you make stable and explainable capacity and budget decisions in a market where unit prices keep changing.
