LLM Inference Cost Optimization: A Practical Guide to Cache Hit Billing
This article explains how prefix cache hit pricing works and how to turn cache hit rate into a measurable cost lever. It breaks down the input cost model, the block-based prefix matching logic that determines a hit, and a four-layer prompt design that keeps stable content at the front. It also covers multi-turn chat, RAG, and batch workloads, plus the observability metrics and attribution formulas needed to quantify savings, a deployment checklist, and common mistakes that silently drive hit rates to zero.
1. Background and Technical Reading
A cloud provider’s model-as-a-service (MaaS) platform announced a price adjustment: starting 00:00 Beijing time on November 23, 2026, for a general-purpose LLM deployed in a single region (Guiyang), the unit price of “cache hit input” will be set to 20% of the original price. All other billing items (cache miss input, output, and any batch or long-context add-ons) remain unchanged.
The announcement is dense, but it is easy to misread as “an 80% overall price cut.” An accurate technical reading has three points:
- The scope is narrow: it covers one region, one model version, and one billing item. Cross-region calls, other models, and output-side charges are unaffected.
- What gets cheaper is the recomputed part: only input tokens that hit the prefix cache receive the discount; tokens written into the cache for the first time are still billed at the original price.
- This is a structural price change: it turns “cache hit rate” from a pure performance metric into a cost lever that converts directly into a bill.
For developers, the implication is that the optimization focus shifts from “switch to a cheaper model” to “increase the reuse rate of cacheable prefixes.”
2. A Cost Model for Inference
Before optimizing, decompose the bill. The input-side cost of a request can be abstracted as:
InputCost = N_total * P_miss + N_hit * P_hitwhere N_total = N_hit + N_missP_hit = 0.2 * P_miss (after this adjustment)
Let the hit rate be r = N_hit / N_total, then:
InputCost = N_total * P_miss * (1 - 0.8r)
Two conclusions follow:
- At
r = 0there is no change; atr = 0.5input cost drops 40%; asr → 1the theoretical ceiling is an 80% reduction. - The benefit is linear in
r, so engineering effort spent on raising the hit rate can be converted directly into money, which makes ROI evaluation straightforward.
Note that output tokens are usually billed at a higher unit price and are not affected by this discount, so the overall reduction in long-answer scenarios is diluted. Evaluations must use the real ratio from your own workload, not the theoretical ceiling.
3. How a Prefix Cache Hit Is Determined
The caching implemented by mainstream inference services is a prefix-level, content-addressed reuse mechanism. Its decision logic can be approximated as: split the request’s token sequence into fixed-size blocks, hash each block, and count a hit only for the consecutive, byte-identical blocks starting from the very first token. A single token difference at any position invalidates every block after it.
Illustrative pseudocode:
def hit_prefix_len(cached_blocks, tokens, block=16):n = 0for i in range(0, len(tokens) - block + 1, block):h = hash(tokens[i:i+block])if cached_blocks.get(h) != tokens[i:i+block]:break # stop at the first mismatchn += blockreturn n # hit length; the rest is billed as a miss
This yields four engineering rules:
- Stable content first: system prompts, tool declarations, output format constraints, and a few examples belong at the very front and must be byte-stable.
- Variables last: timestamps, user IDs, conversation summaries, and retrieved snippets go at the tail of the prompt.
- Never inject randomness into the prefix: random IDs, map iteration without a guaranteed order, and floating-point formatting differences all punch holes in the cache.
- Align to blocks: keeping the stable segment close to an integer multiple of the block size reduces waste at the boundary.
4. Layered Design of Reusable Prefixes
Organize prompts into four layers, from most stable to most volatile:
| Layer | Content | Change frequency | Cache value |
|---|---|---|---|
| L0 | Safety policy, role definition, output contract | Very low | Highest |
| L1 | Tool/function declarations, field descriptions, examples | Low | High |
| L2 | Domain knowledge, long documents, codebase context | Medium | Medium |
| L3 | User question, real-time data, session state | Every request | None |
Implementation notes: render L0/L1 from a shared template and put it under version control; for L2, use “document chunk + stable ordering + content-hash naming” so the assembly order does not drift between requests; keep L3 strictly at the end.
5. Adapting to Multi-Turn Chat and RAG
Multi-turn chat: maintain history in append-only fashion, adding content only at the end of each turn while the earlier part stays byte-identical, so later turns of a long conversation get a high hit rate. If summarization is unavoidable, treat the summary as the start of a new turn and accept one miss.
Retrieval-augmented generation: the hit rate depends on how stable the retrieved results are. Normalize recalled snippets (strip whitespace differences, unify punctuation, fix the truncation length) and order them by content hash rather than by an unstable tie-break order when scores are equal. For high-frequency questions, a semantic cache can skip the model call entirely on a semantic hit.
Batch offline jobs: submit tasks that share a template in consecutive groups so the shared prefix is reused repeatedly within the cache lifetime; avoid interleaving multiple templates, which causes cache thrashing.
6. Observability and Cost Attribution
No measurement, no optimization. Collect these metrics and build a dashboard:
- Hit rate
r, split by business line, model, and region; - Average hit prefix length and the distribution of missed tokens;
- Input/output tokens per request and the converted cost;
- Share of cache invalidation events (TTL expiry, eviction).
Example attribution:
saved = hit_tokens * (P_miss - P_hit) # savings for a single requestrealized_rate = saved / (total_input_tokens * P_miss)
Aligning realized_rate with business gross margin tells you whether further investment in prompt governance pays off.
7. Implementation Checklist
- Manage templates centrally; never concatenate prompts as strings in business code.
- Run a “prefix stability test” before release: issue two consecutive requests that differ only in tail variables, and verify the hit length matches expectations.
- Version every prompt template, and assess the risk of a hit-rate regression when it changes.
- Deploy regionally and call nearby to reduce the extra latency and cost of cross-region requests.
- Set budget alerts and quotas to keep long-context jobs from running away.
- Add a cache hit rate regression gate that blocks a release below the threshold.
8. Common Pitfalls
- Reading it as an overall price cut: only the hit portion is discounted; output cost is unchanged.
- Putting a timestamp at the start of the prompt: a single difference invalidates the whole prefix, and it is the most common cause of zero hits.
- Chasing extremely long context: the missed portion is billed at the original price, so long context amplifies cost rather than spreading it.
- Ignoring TTL and concurrency: during low-traffic periods the cache may already have expired, so the hit rate fluctuates with traffic.
- Treating a semantic cache as a universal fix: requests that are semantically similar but factually different may return wrong results, so limit it to low-risk scenarios.
9. Conclusion
This adjustment, limited to one region and one billing item, essentially binds prompt engineering to cost engineering. If developers build a stable prefix structure, measure hit rates properly, and fold cost attribution into the release process, they can capture verifiable savings quickly whenever pricing changes, instead of waiting passively for the next announcement.
