Optimizing LLM Inference Cost: Prompt Caching and Cache-Hit Billing

    A practical guide to LLM inference cost: how cache-hit input pricing works, why prefix reuse and KV cache drive hits, and how to structure prompts, RAG, and observability to raise hit rate without sacrificing quality or compliance.

    Why inference bills are hard to predict

    After you put large language models into production, the first engineering problem is often cost, not quality. Unlike per-call pricing, LLM charges track token volume, and input and output are usually priced separately. As traffic grows, contexts lengthen, and multi-turn chat plus retrieval-augmented generation become standard, input tokens often dominate the bill.

    A recent MaaS price change in one region is typical: list prices were not cut across the board. Instead, input tokens that hit the cache were priced at a lower fraction of the uncached input rate; other line items stayed the same. That kind of structured change means cost work shifts from unit-price negotiation to using the billing structure. That is the premise of everything below.

    Billing as four variables

    A reusable cost model:

    1. Request cost = Cin_uncached * T_in_uncached
    2. + Cin_cached * T_in_cached
    3. + Cout * T_out
    4. where T_in_uncached + T_in_cached = total input tokens

    The four variables are uncached input unit price, cached input unit price, output unit price, and the corresponding token counts. Engineering can directly control token volume and hit ratio, so two tracks matter:

    • Cut wasted tokens: compress system prompts, trim retrieval snippets, dedupe history.
    • Raise hit ratio: keep as much of the input prefix identical across requests.

    Cached input cheaper than uncached input is a common design, but ratios, regions, and effective dates are vendor-specific and can change. Do not treat one price change as a constant; unit prices in the model must be configurable.

    How a hit happens: prefix reuse and KV cache

    During autoregressive generation the model keeps a key–value attention cache for tokens already processed. If two requests share an identical input prefix, the server can reuse that cache and skip repeated forward work. That is the physical basis of a cache hit and why hit tokens cost less: real compute drops, not a marketing discount.

    An important constraint follows: matching is on the prefix, not arbitrary spans. Any token change in the prefix makes everything after it uncached. That rule drives the optimizations below.

    Four factors that set hit rate

    1. Prefix stability. System prompt, tool/function definitions, few-shot examples, and output-format constraints form a long hittable prefix if they are identical every time.
    2. Prefix order. Put volatile content last. A common mistake is timestamps, request IDs, or user names at the start of the system prompt, which invalidates the whole prefix.
    3. Call rate and TTL. Caches usually expire. Rare long prefixes often miss the window; high-concurrency fixed templates hit most.
    4. Routing and placement. Different instances or regions do not share cache. Multi-region deployment improves availability but can dilute per-region hit rate.

    Practice 1: Layer prompts and freeze order

    Organize input as stable / semi-stable / volatile:

    1. [Stable] Role, safety policy, output format, tool definitions (rarely change)
    2. [Semi-stable] Domain knowledge, retrieved docs (batch updates, not per request)
    3. [Volatile] User question, new turns, timestamps (every request)

    Illustrative client code (endpoint and model names are placeholders):

    1. def build_prompt(system_static, docs, user_input):
    2. # Stable layer first so a long prefix can be reused
    3. parts = [system_static]
    4. if docs:
    5. parts.append(render_docs(docs)) # Semi-stable: changes with knowledge-base version
    6. parts.append(user_input) # Volatile: last
    7. return "\n\n".join(parts)
    8. resp = client.chat.completions.create(
    9. model="<model-name>",
    10. messages=[{"role": "system", "content": build_prompt(SYS, DOCS, q)}],
    11. temperature=0.2,
    12. )

    Three rules: concatenate knowledge-base documents in a fixed order, not randomly; keep tool and field order stable; never inject per-request variables into the system prompt.

    Practice 2: Multi-turn chat and RAG

    Multi-turn chat usually yields the largest hit-rate gains because history is a reusable prefix. Append only; do not rewrite. Add new user and assistant turns at the end. Summarizing or reordering history breaks the prefix.

    RAG is the opposite risk: different retrievals each time shake the semi-stable layer. A workable compromise is a document-level cache key: knowledge-base version plus document IDs, with a constant concatenation order within a version. When the version changes, accept one full miss rather than chronically low hit rate.

    Cost accounting and metrics

    Do not watch only the total bill. Attribute:

    • Hit rate h = cached input tokens / total input tokens, by product line, model, and region.
    • Effective input price P_eff = (1-h) * P_uncached + h * P_cached.
    • Output ratio r = output tokens / input tokens, to see whether input work actually moves the bill.

    Illustrative numbers only (not any vendor’s prices): uncached input 1.0, cached 0.2, output 2.0; 8000 input tokens, 500 output. At h=0, cost is 9.0; at h=0.8 it is 3.4, about 62% lower. When output share is small, input optimization has high leverage. When output share approaches or exceeds 1, shift effort to output length and generation policy.

    Pitfalls and risk control

    • Assuming reuse anywhere in the prompt. Only prefixes hit; changing the middle drops the rest of the cache.
    • Trading quality for hits. Freezing retrieval and refusing knowledge updates is not acceptable.
    • Cache consistency. When the semi-stable layer updates, confirm the server does not return results from stale cache; isolate strongly time-sensitive data from the cache path.
    • Multi-tenant isolation. Do not share prefixes across tenants’ templates or knowledge, so privileged content does not land in a reusable span.
    • Region trade-offs. A regional price cut can help cost, but weigh latency, data compliance, and capacity. Cross-region routing splits cache; balance availability and hit rate.
    • Hard-coded prices. Unit prices and effective dates change by region. Externalize config and alert so a price change does not spike the bill unnoticed.

    Rollout path

    1. Instrument token and cost attribution; see the structure before changing prompts.
    2. Layer prompts; freeze the stable layer and tool-definition order.
    3. Make multi-turn append-only; version RAG with cache keys.
    4. By product line, use output ratio to choose input vs. output work.
    5. Configurable unit prices and change alerts; pick regions on cost and compliance together.
    6. Put hit rate and effective input price on the standing dashboard and in iteration reviews.

    Cache-hit input billing returns cost control to engineering: stable, ordered, reusable prefixes, plus attributable metrics and configurable prices, are a reliable way to cut inference cost without sacrificing quality or compliance.