LLM Prompt Caching Discounts: The Engineering Logic Behind Cache Hit Pricing

    This article explains why LLM providers can cut the price of cached input tokens to a fraction of the standard rate, and why this is a matter of pricing aligned with real workload structure rather than a short-term promotion. It covers why agent workloads naturally produce a long stable prefix plus a short variable suffix, how compact key-value cache representations reduce the memory cost of caching a prefix, how to treat cache hit rate as a designable metric across token-level, request-level, and prefix-length dimensions, and a cost model showing where the savings come from. A practical checklist and common pitfalls are included for developers optimizing token bills.

    1. The Discount Is Not Just a Promotion

    When a model service cut the billing price of the cached portion of input tokens to one tenth of the launch price, many teams assumed the vendor was stacking discounts. From an engineering standpoint, it looks more like pricing being aligned with the real structure of the workload than a short-term concession. Two things have to be examined together to see this: what happened to the prefix structure on the request side, and how much it actually costs to cache a prefix on the inference side.

    The conclusion up front: when requests naturally carry a long, stable prefix, and the key-value cache for that prefix is small enough and reused often enough, the marginal cost of a cache hit is far below recomputation, which leaves room for the price to drop. A high hit rate is only the surface. The real drivers are the workload shape and the cost of the cache implementation changing together.

    2. Why Agent Workloads Suit Prefix Caching

    Traditional single-turn request/response traffic has short prefixes that change quickly, so caching yields little. Agent workloads such as coding assistants and automated operations helpers look completely different. Every turn carries the system prompt, structured descriptions of tools and functions, repository context, long-term memory, and a session summary. Together these run from thousands to tens of thousands of tokens, and they barely change across a session.

    Only a small tail changes each turn: the latest observation, the current subtask description, and a run identifier or timestamp. The request therefore has a typical “long stable prefix + short variable suffix” shape:

    1. [ system prompt ][ tool schema ][ repo context ][ memory ][ session summary ] | [ observation ][ task ][ run id ]
    2. └──────────────── stable prefix, reusable ────────────────┘ └── changes every turn ──┘

    This shape matches exact prefix caching very well. The rule for exact prefix caching is simple: compare token by token from the beginning until the first difference, and everything before that point can reuse the already computed key-value state. The longer and more stable the prefix, the higher the reusable fraction; the shorter the suffix, the smaller the repeated computation.

    3. Why a Small Key-Value Cache Is the Key Variable

    Even with a high hit rate, the discount is impossible if caching a prefix is expensive. This is where the memory footprint of the key-value cache has to be estimated. For a common decoder architecture, cache size can be approximated as:

    1. KV_bytes ≈ 2 × num_layers × num_kv_heads × head_dim × seq_len × bytes_per_element × concurrency

    The factor of 2 accounts for the two tensors, keys and values. The formula shows that cache cost scales linearly with sequence length and concurrency, and with the product of model width and depth. When the attention part of the model uses a more compact key-value representation, such as a shared strategy along the lines of multi-query or grouped-query attention, or a low-rank compressed latent cache, the “num_kv_heads × head_dim” term shrinks substantially, and the same prefix length occupies an order of magnitude less memory.

    The smaller footprint has three knock-on effects. First, more prefixes from different sessions can be cached without squeezing out batch space. Second, swap-in and swap-out are faster, so the scheduler is more willing to keep long prefixes around. Third, the amortized cost of a single cache entry is lower. Together these give a provider the confidence to push the hit price down to one tenth of the launch price.

    4. Making Hit Rate a Designable Engineering Metric

    Hit rate should not be luck observed after the fact; it should be a metric you design for. It helps to measure it in three layers:

    • Token-level hit rate: cached tokens / total input tokens, which reflects the billing benefit.
    • Request-level hit rate: the share of requests with at least one cached token, which shows whether the path is working at all.
    • Prefix length distribution: percentiles of the cached prefix length, which shows whether the design is stable.

    The optimization work centers on one idea: do not let the prefix break early.

    1. Push volatile content to the end. Session identifiers, timestamps, random numbers, and retry counts all belong at the tail of the prompt.
    2. Serialize deterministically. Sort tool and function descriptions by a fixed key so that a different traversal order does not produce byte-level differences.
    3. Control early stop markers. Do not insert per-request rendered output into the system prompt.
    4. Reuse in segments. Split repository context into independently cacheable blocks and concatenate them in reference order.

    Illustrative code:

    1. def build_prompt(system, tools, repo_ctx, memory, summary, observation, task, run_id):
    2. # Stable segment: fixed order and serialization
    3. stable = system + canonical_json(tools) + repo_ctx + memory + summary
    4. # Volatile segment: always last, so the prefix stays clean
    5. volatile = f"\n[obs]{observation}\n[task]{task}\n[run]{run_id}"
    6. return stable, volatile

    5. Cost Model: How Much the Discount Actually Saves

    Let the total input tokens be T, the stable prefix length be P, the hit ratio be h, and the read price of a cache hit relative to the normal input price be r. Cache writes require a one-time computation and write to storage. Relative to the original input cost, the savings can be approximated as:

    1. savings ≈ h × (1 - r) × (P / T) - write and storage amortization

    This gives three clear conclusions: the larger the prefix share P/T, the greater the benefit; the hit ratio h must be stable rather than occasional; and write and storage amortization has to be spread over many reuses. When P/T approaches 0.8, h stays above 0.9, and reuse reaches dozens of turns, an order-of-magnitude drop in overall input cost is entirely possible, which is where the “stacked discount” impression comes from.

    Note that this is a general estimation framework. Actual unit prices, cache capacity, and billing definitions should follow the public documentation of the chosen cloud service and model service. Cache granularity, invalidation policies, and minimum cacheable length can differ across platforms.

    6. Implementation Checklist and Common Pitfalls

    • Measure before optimizing: turn on monitoring for input cache hits and establish a baseline with logging and alerting.
    • Fix the prefix hash: content-address the stable segment and treat any change as a new prefix, avoiding false hits.
    • Watch the invalidation boundary: a session summary update invalidates the whole prefix, so place the summary after the stable segment.
    • Concurrency and capacity: cache eviction intensifies under high concurrency, so session affinity scheduling on a container platform may be needed.
    • Security and compliance: caching means context stays resident, so sensitive data should be masked and a data retention policy should be explicit.
    • Load test setup: replay real sessions rather than synthetic short requests, otherwise the hit rate will be badly overstated.

    7. Conclusion

    Reading this price cut as a “promotion” misses the real engineering signal. Agent workloads make long stable prefixes the norm, and compact key-value representations make caching a prefix cheap; together they push the marginal cost of the cached portion very low. For developers the actionable work is not complicated: move volatile content to the end, fix serialization, bring hit rate into monitoring, and work out the cost model. The same approach applies to model services on platforms such as Baidu AI Cloud: understand the workload shape first, then talk about the bill.