LLM API Cache Hit Rate and Cost Optimization: A Practical Guide

    This article explains why standard LLM API pricing rarely matches real bills, mainly because prefix caching changes the effective cost of input tokens. It introduces a general cost model based on cache hit rate and discount rate, breaks down the factors that determine hit rate, and presents engineering practices such as placing stable content first, ensuring deterministic serialization, using append-only conversation management, and building observability. It also outlines an iterative optimization loop and common pitfalls to help teams reduce costs without sacrificing output quality.

    1. The Overlooked Cost Variable: Why Standard Pricing Is Not Your Real Bill

    When evaluating the ROI of an LLM API, many teams start by opening the pricing page, comparing the per-million-token input and output rates, and multiplying them by the estimated call volume. The logic is sound in principle, but it assumes that all input tokens are billed at the standard rate. In real systems, this assumption rarely holds.

    Most mainstream LLM services now support prefix caching: when multiple requests share an identical context prefix, the server can reuse the already computed intermediate state (KV Cache) and only run forward computation on the newly added tokens. Cached input tokens are usually billed at a rate significantly lower than the standard rate, while uncached tokens are billed at the standard rate. As a result, the real cost on the input side is determined by two variables:

    • The standard input price;
    • The cache hit rate.

    As the hit rate rises from near 0% to 90%, the effective price of the same input can differ by several times. This means two teams using the same model and the same standard pricing can end up with very different bills. The difference comes not from the model, but from how requests are constructed and how context is reused.

    2. A General Cost Model

    Let the standard input price be P, the discount rate for cached tokens be d (so the cached price is P × d), and the hit rate be h. The effective cost per million input tokens is:

    1. EffectiveCost = P × (h × d + (1 - h))

    Using hypothetical example parameters (for illustration only, not the price of any specific service): P = 4 CNY/M tokens, d = 0.175, h = 90%, the effective cost is roughly 4 × (0.9 × 0.175 + 0.1) ≈ 1.03 CNY/M tokens, about 25% of the standard price.

    Three conclusions follow from this formula:

    1. The impact of hit rate on cost is non-linear. In the low-hit-rate range, a 10-percentage-point improvement yields limited savings; once the hit rate exceeds 80%, the effective price drops rapidly toward the cached price.
    2. The discount rate d sets the cost floor. Even at a 100% hit rate, the cost cannot go below P × d.
    3. The output side usually does not benefit from prefix caching, so the total bill must also include output costs. End-to-end optimization must address both input reuse and output length control.

    Note that the numbers above are illustrative. Actual rates, discounts, and billing rules should be based on the latest public documentation of the service you choose. Architecture decisions should not treat any specific discount value as a long-term assumption.

    3. What Determines the Cache Hit Rate

    Once the billing logic is clear, the real engineering work is improving the hit rate itself. The hit rate essentially depends on the stability and sharing of request prefixes, which can be broken down into four factors:

    • Prefix consistency: caching usually matches token-sequence prefixes, and any character change in the prefix invalidates everything after it.
    • Sharing scope: whether multiple sessions or users share the same system prompt and knowledge background.
    • Request cadence: cache entries have a time-to-live (TTL), and long gaps between requests can cause passive invalidation.
    • Context growth pattern: append-only growth (only adding content at the end) is more cache-friendly than repeatedly rewriting earlier content.

    4. Key Practices for Improving the Hit Rate

    4.1 Put Stable Content First

    System prompts, role definitions, output format constraints, glossaries, and a few fixed examples change the least. They should be placed at the very beginning of the prompt to form a long-term stable common prefix. Conversely, putting the user question, timestamps, or random IDs at the front makes the prefix change every turn, driving the hit rate close to zero.

    1. [Stable] System role + output rules + domain terms + fixed examples
    2. [Semi-stable] Retrieved knowledge snippets (sorted by content hash to keep order stable)
    3. [Volatile] Current user input, new turns in the session

    4.2 Ensure Deterministic Serialization

    The concatenation order of knowledge base results, dictionary iteration order, float formatting, and timestamp precision can all produce prefixes that are “semantically identical but token-different.” In practice, sort retrieved results by a stable key, truncate timestamps or express them relatively, and avoid writing millisecond-level timestamps into the prefix.

    4.3 Use Append-Only Conversation Management

    For multi-turn conversations, keep the original history and only append at the tail rather than summarizing and rewriting the history every turn. If history must be compressed, fix the compressed result as an independent paragraph and never modify it afterward, so it becomes part of the new stable prefix.

    4.4 Control Redundant and Exploratory Calls

    In batch tasks, submit multiple calls using the same template together to reduce gaps. For low-value requests that require frequent trial and error, use a smaller model or rule-based pre-filtering to avoid disrupting the cache cadence of high-value pipelines.

    4.5 Build Observability

    Cost optimization cannot rely on guesswork. It is recommended to log the input token count, cached token count, hit ratio, output token count, and end-to-end latency for each request, and build dashboards broken down by business line, with alerts for abnormal drops in hit rate. A common approach is to integrate logging and monitoring/alerting capabilities and use the prompt version as a label dimension, so issues like “a prompt change caused a sudden drop in hit rate” can be traced.

    5. Turning Cost Optimization into an Engineering Loop

    A reusable iteration process:

    1. Baseline measurement: without changing any prompts, collect one week of real hit rate and effective price distribution.
    2. Structural layering: rearrange prompts into “stable / semi-stable / volatile” layers, roll out gradually, and compare hit rates.
    3. Hit rate attribution: sample missed requests to determine whether the cause is prefix drift, TTL expiration, or insufficient sharing scope.
    4. End-to-end accounting: include input savings, output costs, and retry costs in the total bill to avoid local optima.
    5. Codify standards: write prompt layering, ordering rules, and time handling into coding standards and review checklists.

    Illustrative evaluation script logic:

    1. def effective_input_price(p_std, d, hit_tokens, total_tokens):
    2. miss = total_tokens - hit_tokens
    3. return (hit_tokens * p_std * d + miss * p_std) / total_tokens
    4. # Pseudocode for alerting on a sudden hit rate drop
    5. if hit_rate < baseline_hit_rate * 0.7:
    6. alert("prefix cache hit rate dropped", labels={"prompt_ver": ver})

    6. Common Pitfalls

    • Budgeting only from the price table: ignoring the hit rate can overestimate or underestimate costs by several times.
    • Putting dynamic content in the prefix: random IDs, current time, and user nicknames at the beginning are the most common hit rate killers.
    • Chasing 100% hit rate: TTL, concurrent eviction, and context changes cause fluctuations, so leave headroom in planning.
    • Optimizing input only and ignoring output: output tokens usually do not benefit from prefix reuse, and verbose output directly offsets input-side gains.
    • Rewriting prompts all at once: without gradual rollout and version labels, problems are hard to attribute.

    7. Conclusion

    Cost control for LLM calls is shifting from “price comparison” to “context engineering.” Putting stable content first, ensuring deterministic serialization, adopting append-only context, and building hit rate observability determine where the effective input price lands relative to the standard price. If you use Baidu AI Cloud services, the same approach applies: first run baseline measurement and prompt layering using the general methods above, then calculate costs based on the official public billing documentation to form a sustainable cost governance loop.