LLM Inference Cost Optimization: Engineering Practices Behind Cache Hit Discounts
This article explains why some cloud providers now charge a fraction of the original price for cached input tokens, and what that shift reveals about LLM inference cost structure. It covers how prefill and decode stages differ, why shared prefixes can be reused, and the four boundary conditions that determine whether a cache hit occurs. You will also find a cost formula with hit-rate comparisons, five engineering practices for improving hit rates, fallback and observability design, and a reproducible load-testing approach.
1. What the Pricing Change Actually Signals
A recent billing adjustment in the industry is worth a closer look: a cloud provider cut the price of the “input token cache hit” portion of its LLM service to one tenth of the original rate. On the surface this is a price change. In practice it reflects two things. First, repeated prefix computation on the inference side can be reused and amortized. Second, billing dimensions are moving from coarse-grained input/output tokens toward finer-grained dimensions that reflect actual compute consumption.
For developers, the key takeaway is not “it got cheaper.” It is that how you construct a request directly determines your bill. The same business intent, organized with a different prompt structure, can cost several times more or less.
2. How Prefix Reuse Works
Mainstream LLM inference has two stages:
- Prefill: a single forward pass over the input sequence that produces the KV cache for all positions. Compute scales roughly with input length, and the stage is matrix-multiplication heavy, so it is clearly compute-bound.
- Decode: token-by-token autoregressive generation. Each step reads the historical KV cache, so the bottleneck is memory bandwidth.
In many real workloads, requests share a long identical prefix: system prompts, tool and function definitions, few-shot examples, long document bodies, repository context. If every request recomputes that prefix from scratch, you pay the same prefill cost over and over.
Prefix caching works by keying on content features, keeping the computed KV cache in a memory or VRAM tier, and letting later requests that hit the prefix skip the duplicate work and process only the incremental part. Because the savings are real compute and memory bandwidth, providers have room to offer a substantial discount on the hit portion.
This capability is typically applied automatically by the serving side when conditions are met, and callers usually do not need to declare it explicitly. But “automatic” does not mean “guaranteed to hit.” Whether a hit happens depends on whether the request prefix is byte-for-byte stable.
3. Hit Determination: Four Overlooked Boundary Conditions
- Strict prefix matching: the cache is keyed on the token sequence and requires an exact match from the very beginning. A single inserted space, a change in newline style, a timestamp, or a random ID makes everything after it miss.
- Order sensitivity: putting stable content first and volatile content last is the first rule of hit rate. Placing the user question before the system prompt invalidates the entire prefix.
- Limited lifetime: cache entries have a time-to-live and are evicted after long idle periods. A low-traffic workload with “one call in the morning, one in the evening” will rarely hit; high-frequency, stable calls are the ones that benefit.
- Isolation and compliance: caches are isolated per account or tenant and do not leak content across users. For sensitive data, however, you should still follow least-necessary and data-masking principles.
4. Cost Math: Turning the Discount into Comparable Numbers
Let the input unit price be P, the hit discount be d (here d = 0.1), the hit rate be h, and the input token count be L. The input cost per request is:
Cost_in = P * L * (1 - h + h * d) = P * L * (1 - 0.9h)
Cost is highly sensitive to the hit rate:
| Hit rate h | Cost relative to original input cost |
|---|---|
| 0% | 100% |
| 50% | 55% |
| 80% | 28% |
| 95% | 14.5% |
Suppose a call uses 20,000 input tokens and 500 output tokens, with input and output unit prices estimated at a 1:3 ratio. The input portion accounts for about 93% of total cost, so optimizing prefix hits pays off far more than compressing output length. This is why long-context scenarios (document QA, codebase understanding, batch summarization) are the biggest beneficiaries of this billing change.
5. Engineering Practice: Five Actions to Improve Hit Rate
- Layer your prompts: organize them into a stable layer, a semi-stable layer, and a dynamic layer. Put system instructions and tool definitions in the stable layer, and user input in the dynamic layer.
[Stable layer] Role definition + output spec + tool schema + few-shot examples[Semi-stable layer] Long document / code context (cached by version)[Dynamic layer] Current user question, conversation increments
- Make template rendering deterministic: disable auto-filled timestamps, request IDs, and random ordering in templates; serialize dictionary-like structures stably (sorted keys) so the rendered output does not differ on every render.
- Version your context: cache long documents keyed on a content digest, and replace the whole document when it changes rather than editing it locally, avoiding “change one word, invalidate the whole thing.”
- Append conversation increments: in multi-turn chats, only append the new turn and never reorder history; rebuilding the entire history each turn causes prefix drift.
- Batch and schedule concurrency: submit requests that share a prefix together to shorten the prefix’s idle interval and reduce the chance of eviction.
6. Stability and Fallback Design
A cache is an optimization, not a correctness dependency. Engineering must assume the system works even if it “never hits”:
- Result consistency checks: outputs on the hit and miss paths should be consistent within an acceptable range; run dual comparisons on critical paths when necessary.
- Fallback strategy: on a hit failure, automatically fall back to a normal call, record metrics only, and never block the business.
- Observability: instrument your logging service to record input token count, hit token count, hit rate, and latency percentiles, and set an alert threshold for abnormal drops in hit rate.
- Capacity and rate limiting: a higher hit rate changes the traffic shape, so re-evaluate quotas and concurrency limits to avoid throttling under burst traffic.
7. Verification: A Reproducible Load Test
# Illustrative: verify how prefix stability affects hit behaviorstable_prefix = build_system_prompt(tools, examples) # no timestamps or random IDsdoc = load_document(version="v3") # versioned contextdef call(q):return client.chat(messages=[{"role": "system", "content": stable_prefix + "\n" + doc},{"role": "user", "content": q},])# Group A: stable prefix; Group B: inject a random string into the prefix as controlfor i in range(200):call(f"Question {i}")
Compare the hit token ratio and average latency of groups A and B to quantify the benefit of template determinism.
8. Closing Thoughts
Dropping the cache hit price to one tenth is essentially making “repeated computation” visible and putting a price on it. For developers, the most worthwhile investment is not finding a cheaper channel but restructuring requests: keep stable content first and byte-for-byte stable, keep dynamic content last and as incremental as possible. This work is independent of any specific provider and is a general engineering fundamental for long-context applications. In scenarios that offer LLM services, such as Baidu AI Cloud, it is equally advisable to continuously measure optimization results with three metrics: hit rate, latency percentiles, and cost per request.
