Understanding LLM API Input Caching and Billing: How Cache Hits Drive Cost Optimization

    This article explains how input cache hits work in LLM API billing and why they have become a core cost variable in production deployments. It breaks down the per-request cost formula, summarizes engineering lessons from evolving pricing rules such as peak and off-peak tiers, and outlines prefix design principles that improve hit rates. You will also find a practical cost estimation method, capacity planning metrics, a stability checklist for handling price changes, and common misconceptions about input caching versus application-level caching.

    1. Why Input Cache Hits Have Become a Core Cost Variable

    As LLM applications move from demos to production, the cost structure of API calls has changed fundamentally. Early on, developers mainly focused on the price per output token. But with the rise of long-context, multi-turn, and batch document processing workloads, input-side spending often exceeds output-side spending. This is where input cache hits emerge as a distinct billing dimension that directly determines the effective cost of each request.

    The basic idea is this: when the input prefix of a request closely matches content processed recently, the server can reuse the already-computed intermediate state (typically the attention key-value cache) instead of running the full prefill computation again. The portion of the input that hits the cache is billed at a significantly lower rate than standard input, while the portion that misses is billed at the standard rate. The cost of a single request can therefore be expressed as:

    1. Cost per request ≈ cached tokens × cache hit rate
    2. + uncached tokens × standard input rate
    3. + output tokens × output rate

    This formula highlights a key fact: cost optimization is not only about using fewer tokens, but about getting more tokens into the cache hit range. When the cache hit rate is reduced substantially, the marginal cost of workloads with a high proportion of repeated prefixes drops sharply. Conversely, if that rate is raised several times over, input costs that were once considered negligible can grow quickly and even surpass output costs.

    2. Three Engineering Conclusions from Evolving Billing Rules

    Looking at publicly available pricing changes in the industry, one cloud provider went through several rounds of adjustments over a few months: first lowering the cache hit price and extending a promotional period for new models, then converting the promotional price into long-term pricing, then introducing time-based tiered billing with peak and off-peak rates, and finally adjusting to charge weekend rates at the off-peak level all day. These changes are business decisions, but they lead to three stable conclusions for architecture design.

    First, the cache hit price is the most active variable, and it must be treated as a configurable item rather than a constant. If a cost model hardcodes unit prices in business code or reporting scripts, every price change requires a new release, which makes it easy to miss updates and distort budgets.

    Second, time-based pricing makes “time” a cost dimension. Peak hours (usually weekday daytime) carry higher rates, off-peak and nighttime hours are lower, and weekends go lower still. This means the same workload can produce bills that differ by several times depending on which time window it is scheduled into.

    Third, price changes come with advance notice and an exit mechanism. The common industry practice is to provide a notice period before a change, and users who do not accept the new price can stop the service and request a balance refund. Cost governance therefore needs matching alerts and circuit breakers, rather than after-the-fact reviews.

    3. Prefix Design Principles for Improving Cache Hit Rates

    Hit rates are not determined solely by the server; how requests are constructed matters a great deal. Reuse requires the prefix to be byte-for-byte stable, so the following principles are recommended.

    Put stable content first and volatile content last. System prompts, tool definitions, output format constraints, and a few examples should go at the very front, while user input and retrieval results go at the end. Any timestamp, random ID, or request sequence number inserted into the prefix will invalidate the entire prefix.

    1. [Stable] System role and rules → tool schema → output format → fixed examples
    2. [Volatile] Retrieved snippets → session history increments → current user input

    Keep the prefix consistent at the byte level. Number formatting, date time zones, JSON key order, whitespace, and line breaks are all part of the prefix, so serialization logic should be consolidated into a single function to avoid subtle differences from assembling strings in multiple places.

    Match prefix length to its lifecycle. Caches usually have a time-to-live window. If the prefix is very long but the reuse interval exceeds the lifetime, misses will still occur repeatedly. For high-frequency short sessions, trimming the prefix is more effective than piling on examples.

    4. Cost Estimation and Capacity Planning

    It is advisable to build an offline estimation script with pricing parameters externalized as configuration, so the budget can be recalculated within a minute of a price change announcement.

    1. # Example: cost estimation, all prices in CNY per million tokens
    2. def estimate_cost(hit, miss, out, p_hit, p_in, p_out):
    3. return (hit * p_hit + miss * p_in + out * p_out) / 1_000_000
    4. # Estimate with peak and off-peak prices separately, then weight by actual traffic distribution
    5. cost_peak = estimate_cost(70_000, 30_000, 2_000, 0.30, 4.0, 16.0)
    6. cost_off = estimate_cost(70_000, 30_000, 2_000, 0.03, 0.8, 4.0)
    7. print(cost_peak, cost_off)

    Planning should produce three metrics: cache hit rate, share of peak-hour load, and unit business cost (per thousand requests or per ten thousand users). When the cache hit price rises by a double-digit percentage, the savings from a ten-percentage-point improvement in hit rate often outweigh the gains from shortening outputs, and optimization priorities should be reordered accordingly.

    5. Stability and Price Change Checklist

    Price and billing rule changes are external dependency changes and should be brought into change management. A minimal actionable checklist is as follows:

    • Configurable: unit prices, time window boundaries, and weekend rules are all externalized, with support for hot updates and version rollback.
    • Observable: track cached tokens, uncached tokens, and peak/off-peak distribution by business line, and configure budget threshold alerts.
    • Schedulable: move deferrable batch jobs (offline summarization, batch labeling, report generation) to off-peak or weekend windows, and keep interactive requests in peak hours.
    • Degradable: when hit rates drop abnormally, automatically shorten prefixes, switch to a smaller model, or return cached results.
    • Exitable: retain the operational path to check balances and stop the service, so you can cut losses quickly if you do not accept a new price.

    6. Common Misconceptions

    The first is treating a “hit” as an application-layer cache. They operate at different levels: an application cache reuses a complete response, while an input cache hit reuses the prefill intermediate state, and decoding still has to run, so the output portion gets no discount.

    The second is assuming latency always drops after a hit. A hit mainly reduces computation and cost; actual latency is also affected by queuing, network, and output length, so it should not be promised as the sole performance metric.

    The third is ignoring multi-tenant prefix isolation. Sharing an identical system prefix across tenants may increase hit opportunities, but it carries a risk of information cross-talk, so isolation and hit rate must be balanced according to compliance requirements.

    7. Conclusion

    Input cache hits turn LLM cost from a “unit price problem” into a “structural problem”: cost is jointly determined by prefix stability, time-of-day distribution, and the cache hit price. By making pricing parameters configurable, standardizing prefix design, and scheduling workloads by time window, you can keep bills predictable in an environment of frequent price adjustments and ensure optimization efforts always land where the returns are highest.