LLM Inference: Prefix Caching and Cost Governance

    When deploying LLMs in production, billing is driven heavily by token volume and prefix cache hits, not just API call counts. This article explains how to evaluate true inference costs by distinguishing between three types of tokens, how to calculate weighted costs based on real traffic, the technical mechanics of prefix caching, and how to restructure applications to maximize cache hits while maintaining quality, latency, and budget observability.

    After integrating LLMs into online services, the bill is rarely determined solely by the number of API calls. Model-as-a-Service (MaaS) costs are driven primarily by token volume: the context sent to the model, the generated output, and how much content is covered by prefix cache hits. A common pricing adjustment seen in the market is reducing the unit price for “cached input tokens” while keeping other prices unchanged. While easily misunderstood as a general price cut, actual savings depend heavily on hit rate, output length, and request patterns. Below is a vendor-agnostic guide on how to evaluate and optimize these calls.

    Distinguish Three Types of Tokens

    Billing targets for a single inference call can generally be divided into three categories.

    1. Uncached Input Tokens. System prompts, business rules, long documents, chat history, and the current question that do not reuse a cached prefix are billed at the standard input unit price. In long-context applications, this is usually the largest cost driver.

    2. Cached Input Tokens. When a request prefix matches previously cached content, the server does not need to reprocess the entire prefix from scratch. Vendors often offer a lower unit price for these hits. A cache hit does not mean the result is free, nor does it mean the output is free; it only changes the pricing method for that specific input portion.

    3. Output Tokens. Newly generated text is billed at the output unit price, which is typically higher than the input price. If your business requires long answers, multi-turn explanations, or large code blocks, the total cost might still be dominated by output, even if input prices drop.

    Therefore, a price reduction for cached input only affects the second category. The unit costs for the first and third categories remain unchanged. The savings amount is approximately: Number of hit input tokens × (Original cached unit price - New cached unit price). Uncached input and output generate no such savings.

    Use Weighted Cost Instead of List Price for Decisions

    When evaluating pricing changes, do not just compare a single line on the price list. Break down real traffic over a period of time to calculate the weighted cost.

    Let standard input price = Pi, cached input price = Pc, and output price = Po. Let input tokens = Tin, hit ratio = h (0 to 1), and output tokens = Tout. The cost per request is approximately:

    Cost = Tin × (1 − h) × Pi + Tin × h × Pc + Tout × Po

    If only Pc drops to Pc’, the cost reduction is Tin × h × (Pc − Pc'). The reduction ratio equals this reduction amount divided by the original cost. This yields three direct conclusions:

    • If the hit rate is very low, savings approach zero. Cold starts, rewriting system prompts for every request, or placing variable content at the very beginning of the prefix will suppress h significantly.
    • If output is much longer than input, input discounts are diluted. The Po × Tout term in the denominator becomes very large. Tasks with short outputs (customer service QA, classification, information extraction) are more sensitive to cache pricing; long-form generation and step-by-step reasoning are the opposite.
    • Average length cannot replace distribution. A few super-long document requests might contribute the majority of input tokens. You should calculate by interface, scenario, and tenant, rather than just looking at site-wide averages.

    An illustrative estimation can be written using the pure calculation logic below. Prices should come from your own contracts or price lists; no fixed values are assumed:

    1. def estimate(tin, tout, hit_ratio, price_in, price_cache, price_out):
    2. missed = tin * (1 - hit_ratio)
    3. hit = tin * hit_ratio
    4. return missed * price_in + hit * price_cache + tout * price_out
    5. def saving_ratio(tin, tout, hit_ratio, price_in, old_cache, new_cache, price_out):
    6. before = estimate(tin, tout, hit_ratio, price_in, old_cache, price_out)
    7. after = estimate(tin, tout, hit_ratio, price_in, new_cache, price_out)
    8. if before <= 0:
    9. return 0.0
    10. return (before - after) / before

    Before deployment, replay historical logs: record input length, output length, and whether a cache hit occurred based on request records. If there are no hit markers, do not fabricate a hit rate; establish observability first, then discuss savings. The replay should also cover both peak and off-peak periods, as cache capacity and expiration policies can change with load.

    What Does a Cache Hit Technically Depend On?

    The intuitive meaning of prefix caching is identifying content that is stable and located at the beginning of the context across multiple requests as a shared prefix, allowing subsequent requests to reuse the intermediate computation results of that prefix. Whether a request hits the cache depends on server-side strategies. Common constraints include:

    • Prefixes must be byte-level or token-level identical. An extra space, a reordered paragraph, or inserting today’s date can invalidate the entire segment. Dynamic fields should be placed after the stable prefix, not in the middle.
    • Caches have capacity and expiration limits, sometimes isolated by region or deployment unit. The same prompt in another region, another account, or during low-traffic periods might not hit. Do not extrapolate a single experiment’s hit rate to all regions.
    • Hits reduce the processing cost of repeated prefixes, but do not change the model’s computation for the new suffix, nor do they guarantee identical answers. Temperature, sampling parameters, and suffix content still influence the output. Billing optimization cannot replace quality evaluation.
    • Security considerations: If cache keys contain user privacy or secrets, reusing them across requests poses isolation risks. Stable prefixes should be limited to shareable system instructions, tool definitions, and public knowledge. User raw text, identifiers, and order numbers belong in the suffix. Whether to enable cross-user shared caching requires separate review based on data classification.

    Restructure Applications for Higher Hit Rates

    The engineering goal worth pursuing is improving actual hit rates, not just playing with the price list.

    Fix system prompts and tool descriptions. Write role instructions, output formats, and tool lists as versioned templates and avoid modifying them post-release. Express business differences using short instructions in the suffix. Templates should have version numbers, but do not write the version number into the cached text; version changes should be switched globally via the release pipeline to avoid mixing frequently changing version strings into the same prefix.

    Separate stable and variable segments. The recommended order is: long-term stable system prompt, tool schema definitions, optional public reference materials, and only then chat summaries, retrieved snippets, and user questions. Retrieval results change with every query; placing them early will break the prefix.

    Control history growth. In multi-turn conversations, prepending all raw history makes the prefix change constantly, increasing uncached input and latency. A better approach is to periodically compress old turns into short summaries. The summary update frequency should be lower than the cache validity period; otherwise, the summary itself becomes a source of jitter.

    Keep sessions and routing stable. If cache scope is bound to session, account, or region, load balancing that sends the same session to different units will lower hit rates. Stateless gateways should still try to route the same session to the same scope within the cache validity period. This is an affinity strategy, not an exclusive feature of any specific vendor.

    Avoid meaningless wrappers. Some clients randomly insert request IDs, timestamps, or tracking fields at the beginning of the prompt. These fields should be placed in protocol headers or the suffix, not in the cached prefix.

    Batch tasks are better for amortizing cache costs. Offline labeling or document batch processing sharing the same template should be sent continuously within a short time window to keep the prefix in cache. Stretching this over hours with sporadic retries means repeatedly paying for uncached inputs.

    Observe Budget and Quality Together

    Price reductions or increases are just unit-price events; cost governance requires a closed loop.

    Logs should record at least: scenario name, template version, input tokens, output tokens, hit tokens or hit ratio, region/deployment unit, latency, and error codes. Without a hit token field, bills only show totals, making it impossible to explain where savings come from.

    Aggregate by cost breakdown dimensions: look at the “cached input ratio” and “output/input ratio” by application, template version, and tenant. A sudden drop in ratio usually indicates that templates were modified, retrieved content was moved forward, or cache expiration policies changed—not that the unit price failed.

    Set two budget lines simultaneously: cost per request and daily total token volume. Only watching unit price drops might mask rising call volumes. If a new feature changes an answer from one sentence to a full report, the growth in output tokens can completely offset the cached price discount.

    On the quality side, retain a fixed evaluation set. Prefix reordering and history compression might alter answers. Every time you modify a template to boost hit rates, regress against key use cases to ensure format adherence, factuality, and refusal policies haven’t degraded. Cost optimization at the expense of wrong answers means business losses greater than the billing difference.

    Latency should also be included in the same dashboard. Cache hits usually reduce Time to First Token (TTFT), but this isn’t a guaranteed result of pricing rules. If hit rate rises but latency stays flat, check if queues, tool calls, or external network retrieval are blocking it, to avoid falsely assuming the cache is working.

    Checklist for Billing Change Windows

    When encountering billing changes like “only adjusting the cached input price, others unchanged,” verify the following before and after deployment:

    • Confirm the effective time, applicable regions, and billing item names to avoid treating standard input as cached input. Traffic in uncovered regions will not benefit from this change.
    • Replay old vs. new prices using multi-day, scenario-based samples. Provide a savings ratio range, not a single average. Also list scenarios where hit rates are lower than expected.
    • Check if templates are stable, if dynamic fields are in suffixes, and if sessions maintain affinity within the cache scope.
    • Verify if billing dimensions can distinguish the three token types. If not, add observability first before promising savings targets to the business.
    • Notify budget owners: output price is unchanged, so savings are limited for long-output scenarios; increased call volume will still drive up the total bill.
    • Keep a rollback template version. If you merged prefixes that shouldn’t be shared to boost hit rates, you should be able to quickly split them back to avoid data cross-contamination.

    Conclusion

    Reducing the cached input price only saves on “the portion of input that is already reused.” It rewards stable prefixes and repeatable call patterns, not longer answers, and doesn’t automatically reduce the cost of uncached long documents. Splitting prompts into stable and variable segments, using real hit rates and token distributions for weighted estimates, and placing quality evaluation and cost breakdown observability in the same process turns a price adjustment into explainable, reproducible cost governance—rather than just a vague claim that “the model is cheaper now.”