How to Calculate Long-Context LLM API Costs: The Impact of Cache Hits
Estimating the cost of large language model (LLM) APIs requires more than just comparing nominal unit prices. This article explains how prompt caching mechanisms impact billing for long-context models. It covers input and output pricing differences, how cache hits and misses work, and provides a cost estimation model. Additionally, it offers practical engineering strategies to optimize prompt structures, improve cache hit rates, and effectively manage API expenses across different application scenarios.
1. Why Nominal Unit Prices Aren’t Enough for Cost Estimation
LLM APIs typically bill by the token, with prices quoted per million tokens. Many teams compare only this nominal price during selection, but the actual bill accumulates from the input and output of each request, which have different pricing structures and proportions.
Three issues must be clarified first:
First, input and output are priced separately, with output generally costing more because token generation is computationally heavier.
Second, the input-to-output ratio depends on the use case. Q&A requests might have longer outputs, while code analysis, document summarization, and agent tasks often see inputs dozens of times larger than outputs.
Third, a significant portion of the input might be repeated, such as system prompts, tool definitions, and fixed code context. If the platform offers a caching mechanism for these, the actual input cost could be far lower than the nominal price.
Therefore, cost estimation should start with “the input structure, output length, and cache hit situation of each request type,” not the unit price itself.
2. Understanding the Input Cache Billing Mechanism
Prompt caching is a feature offered by many LLM platforms. The basic idea: when the beginning of a new request exactly matches a previous one, the platform can reuse previously computed intermediate results, reducing redundant computation. For users, this input portion is billed at a lower rate.
Billing typically includes the following categories:
- Cache hit input: The request prefix matches cached content, billed at a lower unit price.
- Cache miss input: Parts appearing for the first time or where the prefix changed, billed at the standard input price.
- Output: Generated content billed at the output price, generally unaffected by caching.
Note that different platforms have varying rules for minimum cache length, cache time-to-live (TTL), and whether writing to the cache incurs extra charges. These details directly affect estimations, so refer to the official documentation of each platform rather than making assumptions based on experience.
3. Why Cache Hits Occur and Why They Fail
Caching relies on prefix matching. The platform compares segments starting from the first token; once a change occurs, all subsequent content cannot be reused. This dictates how prompts should be organized.
Content suitable for the prefix usually includes:
- System prompts: Long-term stability, low version change frequency.
- Tool definitions and parameter descriptions: Fixed structure and order.
- Project background materials: E.g., codebase architecture descriptions, API specs, coding conventions.
- Few-shot examples: Fixed content that can significantly improve output stability.
Common cache-breaking factors include:
- Embedding dynamic values like current time or request IDs in the system prompt;
- Retrieving and inserting different document chunks at the beginning of each request;
- Unstable key ordering when serializing objects, causing identical content to produce different strings;
- Inserting temporary information into the middle of historical messages, invalidating all subsequent content.
The following example illustrates the difference:
from datetime import datetime# Bad example: Timestamp in the prefix changes every request, making cache hits almost impossiblesystem = f"Current time: {datetime.now()}\nYou are a code review assistant."# Good example: Stable system prompt at the front, dynamic info at the end in the user messageSYSTEM_PROMPT = "You are a code review assistant." # Version controlled, upgraded uniformly when changeddef build_messages(history, user_input):static_prefix = [{"role": "system", "content": SYSTEM_PROMPT}]dynamic_tail = f"[Current time: {datetime.now():%Y-%m-%d %H:%M}] {user_input}"return static_prefix + history + [{"role": "user", "content": dynamic_tail}]
4. Building a Cost Estimation Model
For easier comparison, convert unit prices to relative values and create a simple calculation model. Let:
- N_in: Input tokens per request
- N_out: Output tokens per request
- h: Cache hit rate (proportion of input that hits the cache)
- p_miss: Cache miss input unit price
- p_hit: Cache hit input unit price
- p_out: Output unit price
Cost per request is:
C = N_in × [h × p_hit + (1 − h) × p_miss] + N_out × p_out
The bracketed term is the effective input unit price. It shows that every percentage point increase in the hit rate lowers the effective input price, with the reduction depending on the gap between hit and miss prices.
Here is a calculation using hypothetical relative values (not actual prices from any platform):
- Let miss input price be 1, hit input price be 0.1;
- Let output price be 5 times the miss input price;
- Let a request have 1 million input tokens, 100k output tokens, and a 90% hit rate.
Effective input price = 0.9 × 0.1 + 0.1 × 1 = 0.19. Input cost = 0.19. Output cost = 10 (in 100k units) × 0.5 = 0.5. Total = 0.69. Without caching, cost = 1 + 0.5 = 1.5. In this example, caching reduces total cost by about 54%.
Effective input prices at different hit rates:
| Cache Hit Rate | Effective Input Price (Relative Value) |
|---|---|
| 50% | 0.55 |
| 80% | 0.28 |
| 90% | 0.19 |
| 95% | 0.145 |
As shown, increasing the hit rate from 50% to 90% significantly reduces input costs. However, above 90%, the marginal benefit of further improvements decreases.
This model reveals another conclusion: when output proportion is high, even with excellent input caching, total cost may still be dominated by output. Therefore, both input and output must be considered during estimation.
In practice, this formula can be wrapped into a small tool for batch evaluation across different scenarios:
def estimate_cost(n_in, n_out, hit_ratio, p_miss, p_hit, p_out):effective_in = hit_ratio * p_hit + (1 - hit_ratio) * p_missreturn n_in * effective_in + n_out * p_out
5. Cost Characteristics of Typical Scenarios
Different scenarios have distinct input structures and caching benefits.
(1) Code Completion
Code completion requests usually contain most of the current file, relevant imports, and project conventions. Content after the cursor changes frequently with edits, while preceding imports and type definitions remain relatively stable. Organizing stable content first and placing cursor context at the end improves prefix reuse.
(2) Agent Tasks
Agents resend complete message history to the model across multiple rounds. Input volume grows roughly linearly with rounds, while most historical content remains unchanged in subsequent rounds, yielding high cache benefits. However, if history keeps expanding, costs will still rise. Periodically summarizing and compressing history is more effective than relying solely on caching.
(3) One-off Q&A
Single Q&A inputs are typically short and vary per question, resulting in low cache hit rates. Costs in this scenario depend mainly on output length; optimization should focus on controlling response length and selecting the appropriate model tier.
6. Engineering Optimization Suggestions
- Stable prefix, dynamic suffix. Place fixed content like system prompts, tool definitions, and background at the beginning; put dynamic info like time, user IDs, and retrieval results at the end.
- Version control prompts. Every prompt change invalidates old caches. Bundle modifications into version releases and avoid ad-hoc adjustments in production.
- Maintain stable serialization. Use fixed key ordering for structured content like JSON to avoid different strings for identical semantics.
- Compress history. Set round or length limits for agents and multi-turn conversations. Replace exceeded history with summaries to control input growth.
- Limit output. Set reasonable max output lengths and require the model to return results in fixed formats to reduce redundant text.
- Monitor key metrics. Log input, output, hit tokens, and cost per request. Track hit rates by scenario. Integrate monitoring data into logging services and alerts to investigate promptly when hit rates drop abnormally.
- Application-level deduplication. For identical repeated questions, return existing results directly at the application layer to avoid redundant API calls.
7. Questions to Verify During Selection
When comparing different platforms or models, confirm the following items point-by-point to avoid looking only at the price table:
- Cache trigger conditions, including minimum length and prefix matching rules;
- Cache TTL and whether it expires after long inactivity;
- Whether writing to the cache incurs separate charges;
- Price differences between model tiers and the availability of lower-cost tiers matching the task;
- Other fees billed per request or per call;
- The impact of concurrency, rate limits, and quotas during traffic peaks.
After verifying these items, apply the model from this article to real request samples, average the input, output, and hit rates, to get a cost figure with practical reference value.
Conclusion: Nominal unit prices reflect only part of the billing. Cache hit rate, input-output structure, and prompt organization collectively determine actual costs, and all three can be optimized through engineering.
