How Cache Hit Pricing Works in LLM API Billing

    This article explains how LLM API billing separates input and output costs into three price tiers: cache hit reads, cache miss inputs, and generated output. It covers why input tokens are not priced equally, how to estimate per-call and average costs with a generic formula, and how rising cache hit rates can cut input-side spending. It also outlines engineering practices for improving cache hits, such as keeping a stable prefix, appending to conversation history instead of rebuilding it, avoiding dynamic summaries, managing cache TTL, and tracking hit rate as a first-class metric, along with scenario-specific priorities and common anti-patterns.

    1. Why Call Costs Are Split Into Three Price Tiers

    When teams start using LLM capabilities, the first instinct is often to estimate cost as “token count multiplied by unit price.” This coarse approach is not very noticeable when call volume is low, but once a system reaches steady operation, especially with many repeated prefixes (fixed system prompts, long-document Q&A, fixed context for code completion), the actual bill can deviate noticeably from the naive estimate, sometimes leaving people confused about why it looks more expensive.

    The core reason for the deviation is that input-side tokens are not equivalent. In typical flows such as multi-turn conversations, RAG retrieval augmentation, and AI Agent tool calls, the same long prefix is submitted repeatedly. Cloud providers generally introduce a context caching mechanism: the portion that hits the cache does not go through full inference but directly reuses the already computed intermediate state, so it is billed lower than a first-time input.

    As a result, billing is usually split into three prices:

    1. Cache hit read price: for the reusable prefix portion, the unit price is significantly lower than normal input;
    2. Cache miss input price: the portion of this request’s input that genuinely needs to participate in inference again;
    3. Output price: tokens generated by the model, usually the highest unit price.

    Pricing these three items separately is essentially about aligning the bill with actual resource consumption. For developers, it also means cost optimization has a clear target: raising the cache hit rate converts “expensive input” into “cheap reads.”

    2. How the Three Tiers Are Constructed and Common Misunderstandings

    1. A Cache Hit Is Not “Free,” Just “Cheaper”

    A common misunderstanding is that “hitting the cache means no cost.” In fact, the hit portion is still billed, only at a unit price significantly lower than the miss input price. The reason is that the server still has to perform cache lookup, state loading, and attention splicing, which is not zero cost.

    So when building a cost model, treat the hit price as a discount factor rather than a zeroed-out item.

    2. The Miss Price Is the Real “First-Packet Cost”

    For a first request, or a request after the cache has expired, the entire input portion is charged at the miss price. This is effectively a one-time payment of the cold-start overhead. If a request has a long prefix but is called only once, the benefit from caching is nearly zero; only high-frequency reuse amortizes this cost.

    3. Output Price Often Sets the Cost Ceiling for Long-Answer Scenarios

    Even with the input side well optimized, scenarios such as long-text generation, code generation, and structured reports can still become the main cost item because of the large number of output tokens. The output price is usually the highest of the three, so in many scenarios “making the model say less” is more effective than “saving input.”

    3. A Generic Cost Estimation Formula

    Without relying on any specific provider’s parameters, you can use the generic formula below for self-testing:

    1. Cost per call =
    2. cached tokens × cache hit unit price
    3. + cache miss input tokens × input miss unit price
    4. + output tokens × output unit price

    Further, if a certain request type has a cache hit rate of h, total input of I, and output of O, then:

    1. Average cost per call =
    2. (h × I) × P_hit
    3. + ((1 - h) × I) × P_miss
    4. + O × P_out

    Where P_hit < P_miss, and P_out is usually the highest.

    Example: if each call has 8000 input tokens and 1500 output tokens, and the cache hit rate rises from 10% to 70%, assuming P_hit is about 1/4 of P_miss, the input-side cost drops from about 0.9·I·P_miss to about 0.325·I·P_miss, a reduction of roughly 64%. This calculation can be applied to any cloud provider model service that bills in these three tiers.

    Note: Because billing conventions, cache validity periods, and minimum cache granularity differ across providers, actual numbers should follow the official billing page of the platform you use. The formula above is for building an order-of-magnitude judgment, not a replacement for official pricing.

    4. Engineering Practices for Improving the Cache Hit Rate

    1. Stable Prefix: Put Reusable Content First

    Caching usually matches on the “longest common prefix.” So put the system prompt, tool descriptions, fixed rules, knowledge base documents, and similar content at the very front of the request, and do not insert volatile content such as timestamps, random IDs, or user nicknames into it. A common low-level mistake is concatenating “the current time is…” into the system prompt, which makes the prefix different on every request and causes the cache to fail completely.

    Recommended approach:

    • Fixed segment: role definition, output format constraints, tool schema → put first;
    • Semi-fixed segment: retrieved knowledge snippets → put in the middle;
    • Volatile segment: the user’s current-turn input, time, conversation context → put last.

    2. Appending to a Conversation Beats Rebuilding It

    In multi-turn conversations, if you reassemble the full history every time, the prefix length may be the same but if the content order changes, the hit will fail. The stable approach is append-style continuation: only append the new turn at the end, keeping the history part byte-for-byte identical.

    1. # Recommended: maintain the message list in append style
    2. messages.append({"role": "user", "content": user_input})
    3. resp = client.chat(messages=messages)
    4. messages.append({"role": "assistant", "content": resp.text})

    Rather than re-sorting, trimming, or rewriting a summary every turn.

    3. Use “Dynamic Summaries” Carefully

    Many frameworks automatically compress history into a summary when it gets too long. Once a summary is generated by the model, its content changes every turn, and prefix caching will inevitably fail. If compression is required, consider segmented caching plus re-warming the summary as a new prefix, instead of expecting the automatic summary to hit the cache.

    4. Control Cache Validity and Concurrency

    Caches usually have a time to live (TTL). If the business has clear peaks and troughs, the first request after a trough will cluster into misses. In that case you can:

    • Use low-priority scheduled requests to warm the prefix;
    • Split high-reuse content into its own segment to shorten the length that needs caching;
    • For very long documents, use “segmented caching + retrieval location” to reduce ineffective prefixes.

    5. Observability: Treat Hit Rate as a First-Class Metric

    It is recommended to bring cache_hit_tokens, miss_tokens, and output_tokens into monitoring and alerting, broken down by business line and by endpoint. Without measurement there is no optimization, and the hit rate is often most easily overlooked exactly where it is needed most (high-frequency calls with long prefixes).

    1. Suggested monitoring dimensions:
    2. - Hit rate = cached tokens / input tokens
    3. - Cost per request = total cost / number of requests
    4. - Cold start share = miss tokens / input tokens
    5. - Output cost share = output cost / total cost

    5. Optimization Focus for Different Scenarios

    Scenario Main Cost Item Optimization Focus
    Customer service bot with a fixed system prompt Input miss Stable prefix, enable caching
    Long-document Q&A / RAG Input and hits Shorten retrieved snippets, segmented caching
    Code completion Output Limit completion length, streaming truncation
    AI Agent multi-step tool calls Input miss (repeated prefix) Append-style history, avoid rebuilding
    Batch offline tasks Output Batch processing, result deduplication, templated output

    The value of this table is that you first determine “which item your money is going to,” then decide the optimization direction. Many teams blindly optimize input when the output side is actually the bulk; others overlook repeated prefixes in AI Agent scenarios, causing miss costs to multiply.

    6. Common Anti-Patterns

    1. Stuffing dynamic content into the system prompt: this directly causes the cache to never hit, and is the most widespread problem;
    2. Regenerating a summary on every request: the changing summary causes prefix mismatch;
    3. Over-pursuing “ask everything at once” and piling up an overly long context: high miss cost with low payoff;
    4. No per-scenario cost accounting: when the overall bill rises, the cause cannot be located;
    5. Ignoring output-side governance: waste from generating overly long answers often exceeds the input side.

    7. Conclusion

    Understanding LLM call costs through three prices (cache hit read price, input miss price, output price) is the first step in cost governance. The direct benefit is that you turn “whether it saves money” from a matter of feeling into an engineering problem that is calculable, verifiable, and continuously optimizable.

    The implementation path can be summarized in four steps:

    1. Understand the structure: use the generic formula to build a per-call and overall cost model;
    2. Design the prefix: put fixed content first and prevent dynamic content from polluting the prefix;
    3. Improve hits: append-style continuation, reasonable warming, and controlling cache TTL;
    4. Measure continuously: bring hit rate and cost per request into monitoring and alerting.

    In model service scenarios such as Baidu AI Cloud Qianfan, the same generic billing logic applies: the hit price is lower than the miss price, and the output price is the highest. When integrating in practice, developers should follow the official billing documentation of the platform they use, do quantitative estimation based on their own call mix, and then use prefix design and a monitoring system to keep the hit rate stably high, thereby significantly reducing cost per call without changing functionality.