LLM Inference Cache Pricing and Cost Optimization in Practice

    Lower prices for cached input tokens make prompt-prefix stability an important lever for reducing LLM inference costs. This article explains prefix caching, practical ways to improve cache reuse, a cost calculation model, and the monitoring and validation steps needed to turn caching improvements into measurable savings.

    1. What a Pricing Change Reveals About Inference Billing

    A cloud provider recently adjusted pricing for a lightweight text model at a regional endpoint on its Model-as-a-Service (MaaS) platform. The price of cached input tokens fell to 20% of its previous level, while other billing items remained unchanged.

    Although this looks like a pricing announcement, it changes the relative importance of different billing components. For developers, architectural improvements that increase cache reuse can now deliver a more direct financial return.

    To understand the implications, first break down an LLM inference bill. Common billing components include:

    • Input tokens: The prompt content sent with a request.
    • Output tokens: The content generated by the model.
    • Cached input tokens: The portion of the input that matches a cached prefix and does not need to be recomputed.
    • Cache writes or storage: Some platforms charge separately for writing to the cache or retaining entries.

    When cached input is priced separately and substantially below regular input, input costs depend not just on request volume but also on the proportion of tokens that miss the cache. How stable your request prefixes are becomes an important cost driver alongside how often you call the model.

    2. Why Cache Hits Cost Less

    Lower cached-input pricing reflects computational reuse.

    During autoregressive generation, the model uses the key-value states of preceding tokens, commonly called the KV cache. If two requests share an identical prefix, the computed KV states for that prefix can be reused. The server only needs to perform new forward computation for the additional tokens.

    A common implementation uses prefix hash matching: the request’s token sequence is divided into blocks, hashes are computed for those blocks, and the service checks for matching cache entries. The longest matching prefix can then be reused.

    1. Request = [System prompt][Tool definitions][Conversation history][Current user input]
    2. └──────── Stable, cacheable prefix ────────────────┘└─ Variable portion ─┘

    Cache reuse depends on three conditions:

    1. Exact token-level matching: A space, line break, or punctuation change that alters the token sequence can break matching from the affected block onward.
    2. A contiguous prefix: Reuse must begin at the start of the request, not at an arbitrary point in the middle.
    3. An available cache entry: The entry must still exist within the retention window and must not have been evicted because of capacity limits or TTL expiration.

    3. Engineering Practices That Improve Cache Hit Rates

    3.1 Layer Prompts and Keep Their Order Stable

    Ordering prompt components from least frequently changed to most frequently changed is one of the most effective ways to improve cache reuse without adding infrastructure.

    1. def build_request(system_prompt, tools, history, user_msg, ts):
    2. # Layer 1: Rarely changes and remains stable over time
    3. head = system_prompt
    4. # Layer 2: Changes less frequently; manage through versioning
    5. head += render_tools(tools) # Keep tool definitions in a fixed order
    6. # Layer 3: Frequently changing content belongs at the end
    7. tail = render_history(history) + user_msg
    8. # Append volatile metadata; never insert it into the stable prefix
    9. tail += f"\n<request_id>{ts}</request_id>"
    10. return head, tail

    The opposite pattern is equally important to recognize. Placing the current time, a request ID, a random value, or a changing user nickname at the beginning of the system prompt can drive cache reuse toward zero.

    These unnecessarily dynamic prefixes are a common source of avoidable latency and cost.

    3.2 Maintain Conversation History Through Appends

    Multi-turn conversations should preserve append-only semantics wherever possible.

    If every turn rewrites, summarizes, or reformats the existing history, the prefix changes each time, preventing reuse. When context compression is necessary, use segment-level summaries appended as a separate layer rather than repeatedly rewriting existing content.

    3.3 Coordinate Batch and Concurrent Requests

    Under high concurrency, cache entries may be evicted early because of capacity pressure. Scheduling requests with the same prefix close together within a time window can improve reuse.

    For offline workloads that are less sensitive to latency, reasonable retry backoff can also help avoid sudden traffic spikes that churn the cache.

    4. A Cost Calculation Model

    Let:

    • (I) be the number of input tokens per request.
    • (h) be the fraction of input tokens served from cache.
    • (p_{in}) be the regular input-token price.
    • (p{hit} = \alpha \cdot p{in}) be the cached input-token price.

    The input cost per request is:

    [
    C = I \cdot p{in} \cdot \big[(1-h) + \alpha h\big]
    = I \cdot p
    {in} \cdot \big[1 - (1-\alpha)h\big]
    ]

    When (\alpha = 0.2), increasing the cached-token fraction from 0 to 0.8 reduces input cost by approximately 64%. At 0.95, the reduction is approximately 76%.

    These figures describe input costs, not the entire inference bill; output and any cache write or storage charges remain separate.

    With a substantial discount for cached input, improving prefix stability can offer greater savings than modest reductions in prompt length. A team may spend considerable effort removing a few hundred tokens while overlooking a timestamp at the beginning of every prompt that prevents otherwise reusable prefixes from matching.

    The practical lesson is to identify the largest source of avoidable cost before choosing an optimization target.

    5. Observability and Validation

    Cache optimization must be measurable. Collect the following metrics and use them in dashboards and alerts:

    • Cache hit rate, broken down by workload, model, and region.
    • Average reused-prefix length and the distribution of cache invalidation or miss reasons.
    • Input cost per request and the share of total cost attributable to output.
    • P95 and P99 time to first token: Better cache reuse often reduces latency, providing a useful cross-check.

    Before deployment, run an A/B test with a fixed request corpus. Change only the prefix-construction logic and keep other variables constant. This makes it easier to attribute cost differences to the caching strategy rather than unrelated workload changes.

    6. Common Misconceptions and Risk Controls

    • Caching is not conversation memory. It is a server-side performance and billing optimization, not a guarantee of application semantics. Store conversation state reliably in the application.
    • Data isolation and compliance still matter. In multi-tenant systems, confirm the platform’s cache isolation boundaries and retention policies. Do not rely on cache reuse as a mechanism for handling sensitive data. Use regional endpoints or dedicated resources for isolation where necessary and supported.
    • Regional differences matter. Pricing and caching capabilities may vary by endpoint or region. Keep billing parameters in configuration rather than hard-coding them.
    • Avoid overengineering. Short prompts and workloads with little prefix repetition may offer limited savings. Validate the opportunity with data before investing in changes.

    7. A Practical Rollout Plan

    1. Audit: Sample real requests and measure prefix consistency. Identify where volatile fields appear.
    2. Refactor: Introduce prompt layers and move dynamic metadata behind the stable content.
    3. Validate: Use a fixed-corpus A/B test to quantify changes in cache reuse and billing.
    4. Standardize: Include prefix construction in code reviews and CI checks to prevent regressions.
    5. Monitor continuously: Add cache hit rates to cost dashboards and reassess the strategy as pricing changes.

    For deployments on Baidu AI Cloud, its model services and general cloud services—such as logging, monitoring and alerting, object storage, and message queues—can support the collection and scheduling workflow where available. Confirm service and regional availability in the official documentation before planning the deployment.

    Conclusion

    When cached input is priced at a small fraction of regular input, prompt-prefix stability becomes a central part of LLM cost optimization.

    The priority shifts from focusing only on shorter prompts to making reusable content consistently reusable. Stable ordering, append-only history, careful placement of dynamic metadata, and measurable validation can turn engineering discipline into sustained cost savings.