How to Calculate the Real Cost of LLM APIs: Caching, Billing, and Cost Optimization
Learn why LLM API bills often exceed the sticker price per token. This guide breaks down the full cost formula—including cached input, output tokens, cache writes, and time-of-day pricing—shows how cache hit rates shift cost comparisons between providers, and offers practical criteria for choosing between pay-as-you-go and subscription plans, plus engineering techniques to reduce spending.
How to Calculate the Real Cost of LLM APIs: Caching, Billing, and Cost Optimization
Why the Bill Doesn’t Match the Advertised Price
Many teams budget based on the token unit prices listed on marketing pages, only to find the month-end bill significantly higher. The reason is that API billing is usually affected simultaneously by cache hit rates, input/output ratios, time-of-day pricing, and subscription discounts. Comparing unit prices alone cannot produce a reliable cost figure. This article presents an accounting method that explains how each factor affects the final bill, and provides criteria for provider selection and cost reduction.
1. What Makes Up the Cost of an LLM API Call
The cost of a single call generally comes from three parts:
- Uncached input tokens: billed at the standard input price.
- Cached input tokens: billed at the cache read price, which is typically much lower than the standard input price.
- Output tokens: billed at the output price, which is usually several times the input price.
The basic formula is:
Total cost = uncached input tokens × input price+ cached tokens × cache read price+ output tokens × output price+ cache write tokens × cache write price (if applicable)+ storage fees (if applicable)
This formula covers the main cost items, but not the entire bill. When doing the accounting, also check the following:
- Cache write fees: Some providers charge for the first write to the cache at a price higher than regular input; the read discount only applies after writing. When write frequency is high, this fee may offset the savings from cache hits.
- Storage fees: Some providers charge based on how long the cache is retained. Confirm the billing rules in the price list.
- Minimum billing unit: Some APIs bill by a minimum number of tokens per request or at a fixed granularity. Short requests effectively cost more per token than the advertised rate.
- Time-of-day coefficients: Prices may vary by time period. Some providers offer off-peak prices around half of the standard rate; others have short peak windows affecting only a few hours. Compute a weighted coefficient based on your actual call-time distribution.
The ratios in the formula must use a consistent basis. In the examples below, all percentages refer to the share of total tokens—cached, uncached, and output add up to 100%.
2. How Cache Hit Rate Changes Real Cost
In scenarios like coding assistants, agent conversations, and RAG question answering, system prompts, tool definitions, code snippets, and conversation history recur frequently, so cache hit rates can be very high. Suppose a workload’s token composition is: 98% cached, 1.5% brand-new input, and 0.5% output.
Below is a comparison using two hypothetical services. All prices are illustrative examples and do not represent any provider’s actual pricing:
| Item | Service A | Service B |
|---|---|---|
| Input price (CNY/million tokens) | 2.0 | 4.0 |
| Cache read price (CNY/million tokens) | 0.5 | 0.2 |
| Output price (CNY/million tokens) | 8 | 8 |
Service A has a cheaper base input price but a more expensive cache read price. Service B is the opposite.
Using 100 million tokens as the calculation unit, split according to the above ratios and compute item by item:
| Hit rate | Service A cost | Service B cost | Cheaper option |
|---|---|---|---|
| 98% | 56 CNY | 29.6 CNY | Service B |
| 95% | 60.5 CNY | 41 CNY | Service B |
| 90% | 68 CNY | 60 CNY | Service B |
| 85% | 75.5 CNY | 79 CNY | Service A |
Taking the 98% hit rate as an example, the calculation for Service A is: 98 million cached tokens at 0.5 CNY/million = 49 CNY; 1.5 million uncached tokens at 2.0 CNY/million = 3 CNY; 0.5 million output tokens at 8 CNY/million = 4 CNY; total 56 CNY. Service B, calculated the same way, totals 29.6 CNY.
Extrapolating from these prices, the crossover point is at roughly a 86.5% hit rate. Above that point, Service B—with its lower cache read price—is cheaper; below it, Service A—with its lower base input price—is cheaper. When your hit rate sits near the crossover, the conclusion is sensitive to both price and hit rate, so recalculate with your real data.
Three rules follow:
- The lower the cache read price, the more favorable high-hit-rate scenarios become.
- The lower the base input price, the more favorable low-hit-rate scenarios become.
- The crossover point is determined by your actual hit rate—you cannot judge by a single unit price alone.
Teams should instrument production systems to measure real hit-rate distributions and run a sensitivity analysis against each provider’s pricing. Compute both ends of the hit-rate fluctuation range rather than drawing conclusions from averages alone.
3. Pay-as-You-Go vs. Subscription Plans
Subscription plans typically provide token quotas on a weekly or monthly basis, priced in tiers. Plan structures vary widely across providers, and this article does not cite specific tier numbers. Always refer to the target provider’s current public pricing page.
When choosing, check these four points one by one:
- Is the quota sufficient? Measure your team’s actual weekly consumption and compare it against each tier. Separate weekdays from weekends so averages don’t mask peaks.
- Peak-hour rules: Some plans accelerate quota consumption or limit speed during specific windows. Verify whether your team’s main usage hours fall inside restricted windows. Shorter windows generally matter less, but validate with call logs.
- Usage stability: When usage is stable and close to the quota limit, subscriptions usually make sense. When usage fluctuates widely or stays far below the quota long-term, pay-as-you-go is often cheaper.
- Overflow policy: After exceeding the quota, the service may throttle, cut off, or automatically switch to pay-as-you-go billing. This directly affects availability, so decide on a degradation strategy during system design.
Reference guideline: when estimated monthly pay-as-you-go spend consistently exceeds the plan price by about 1.5×, the subscription is worth serious evaluation. This ratio is only a screening filter, not a conclusion. Once in evaluation, still verify all four points above and validate against actual bills. Recalculate whenever plan terms change.
4. How to Reduce Costs at the Engineering Level
- Stabilize prompt prefixes: Caching typically matches by prefix. Place static content such as system prompts and tool definitions at the very front and keep it unchanged to improve hit rates. Put dynamic content like timestamps at the end so every request doesn’t change the prefix.
- Context trimming and summarization: Apply rolling summaries to long conversation histories to cut wasted input tokens. This also helps control context bloat, preventing output quality from degrading as length grows.
- Off-peak scheduling for offline tasks: Non-real-time tasks like evaluations and batch generation can run during off-peak hours to benefit from time-of-day pricing.
- Tiered model routing: Route simple tasks to smaller models and reserve flagship models for complex ones. Whether routing saves money depends on classification accuracy and quality loss. There is no universal savings figure—use A/B tests to compare total cost, task pass rate, and latency before rolling out at full scale.
- Usage monitoring and alerting: Set threshold alerts for daily token consumption and weekly usage to prevent runaway bills from abnormal calls. You can integrate cloud logging and monitoring services or build your own usage dashboard. Logs may contain user input, so apply masking, restrict access permissions, and set data retention periods according to compliance requirements.
5. How to Implement a Cost Estimation Method
- Instrument your systems to capture real cache hit rates, input/output ratios, and time-of-day distributions, aggregated daily or weekly.
- Compile each provider’s price list (input, cache read, cache write, output, storage) into a unified table, noting the price date and source.
- Feed the data from step 1 into the table from step 2, and compute costs under low, medium, and high hit-rate scenarios.
- Use the selection criteria from Section 3 to decide on the billing model, and reconcile estimates against the actual bill once a month.
This process depends on real data. Unit price is only one input—conclusions not validated against actual traffic should not be used directly for procurement decisions.
6. Conclusion
LLM API cost is a multivariable problem. The cache hit rate determines which unit price carries the most weight, usage timing determines the effective discount, and usage stability determines the right billing model. Every team should maintain its own cost estimation sheet, update it regularly with real data, and continuously drive costs down through prefix stabilization, off-peak scheduling, and model routing.
