Prompt Caching and LLM API Cost Reduction: A Technical Breakdown of Cache-Hit Pricing

    This article explains how cache-hit pricing works for large language model (LLM) services and why a discount on cached input does not automatically lower your bill. It covers the prefill and decode stages of inference, how prompt caching reuses intermediate KV states for identical prefixes, and a cost model showing that effective input price depends on the cache hit rate. You will also find guidance on structuring requests with stable and volatile segments, observability metrics to track, latency and throughput benefits, common pitfalls, and an action checklist for reducing LLM API costs.

    1. Background: A Structural Price Cut, Not a Blanket Discount

    A cloud provider recently announced a price adjustment for a general-purpose LLM service on a single regional node of its Model-as-a-Service (MaaS) platform: the input charge for the cache-hit portion drops to 20% of the original price, while all other billing items stay unchanged. This kind of change is easy to misread as an across-the-board price cut. In terms of billing structure, however, it applies to only one dimension—cached input tokens. The unit prices for uncached input and for output remain the same.

    This distinction matters. The bill is no longer determined by unit price alone; it is determined by an engineering metric: the cache hit rate. For the same traffic, raising the hit rate from 20% to 60% can cut input-side cost by more than half. Conversely, if the way you call the API repeatedly breaks the cached prefix, actual spending may barely change even with the lower unit price.

    2. How It Works: Why Identical Prefixes Cost Less

    LLM inference has two stages: prefill and decode. Prefill runs every input token through the model once and computes the intermediate key-value (KV) states. Decode then generates output tokens one by one. Prefill is compute-intensive: the longer the input, the more time and compute it consumes.

    The core idea of prompt caching is that if multiple requests share exactly the same prefix (system instructions, tool definitions, long documents, few-shot examples, and so on), the intermediate states for that prefix can be reused instead of recomputed. Billing therefore splits into two tiers:

    • Cache-hit input: reuses already-computed intermediate states, low compute overhead, lower price.
    • Uncached input: requires full prefill, original price.

    Note that a hit typically requires the prefix to be token-for-token identical and positioned at the start of the request. This is a common implementation constraint in the industry; the exact granularity and invalidation policy should be confirmed in the official documentation.

    3. Cost Model: Writing the Bill as a Formula

    Let the total input tokens be $T$, the hit ratio be $h$, the original input price be $P{in}$, the output price be $P{out}$, and the output tokens be $T_{out}$. Then:

    1. Cost = T * P_in * (h * 0.2 + (1 - h) * 1.0) + T_out * P_out

    Here 0.2 is the cache-hit discount factor after this adjustment. Normalizing the input side gives the effective input price:

    1. P_in_effective = P_in * (1 - 0.8h)

    Two practical conclusions follow:

    1. Input cost is highly sensitive to the hit rate: every 10 percentage points of improvement in $h$ reduces input-side cost by about 8%.
    2. When inputs are short and outputs are long, optimizing the hit rate has limited effect on the total bill; controlling output length should take priority.

    4. Scenarios That Benefit Naturally

    • Agents and AI coding tools with long, fixed instructions: system prompts and tool descriptions often run to thousands of tokens and are carried on every turn.
    • Long-document Q&A and contract or log review: the same material is queried repeatedly.
    • Batch structured extraction: templates and field descriptions stay fixed while only the data segment changes.
    • Multi-turn conversations: history grows steadily and the prefix is naturally reusable.

    On the other hand, if every request prepends volatile content such as a timestamp, random ID, or username, the prefix differs from the very first token, the hit rate approaches zero, and none of the discount materializes.

    5. Engineering Practice: A Pattern for Stable Prefixes

    Split each request into a “stable segment + volatile segment”:

    1. def build_request(system_block, docs_block, user_query, trace_id):
    2. # Stable segment: version-controlled; identical content means identical bytes
    3. stable = f"[SYSTEM v3]\n{system_block}\n[DOCS]\n{docs_block}\n[/DOCS]\n"
    4. # Volatile segment: placed at the end to avoid polluting the prefix
    5. volatile = f"[META] trace={trace_id}\n[QUERY]\n{user_query}\n"
    6. return stable + volatile

    Supporting practices:

    • Version your prompts: treat a prompt change as a release; avoid “just fixing one punctuation mark,” which can cause a full miss.
    • Put volatile data last: session IDs, timestamps, and retrieval ranking jitter belong at the tail.
    • Keep document order stable: in retrieval-augmented scenarios, apply a fixed sort to retrieved chunks; do not re-sort on floating-point score jitter.
    • Temperature and sampling do not affect hits: a hit depends only on the input prefix, but output variance affects output cost and should be managed separately.
    • Graceful fallback: if caching is unavailable, fall back to a normal call automatically, prioritizing availability.

    6. Observability: Measure First, Then Optimize

    There is no optimization without measurement. Collect at least the following metrics:

    Metric Meaning Purpose
    Total input tokens Scale baseline Estimate the theoretical upper bound of savings
    Cached token ratio Core hit rate Assess how much of the discount is realized
    Average prefix length Structural health Judge whether the split is reasonable
    Mean output tokens Second cost driver Control generation length
    Cost per request Business-level view Attribute cost to the owning team

    Build a dashboard with log services and monitoring alerts, and set a threshold alert on the hit rate so that a single prompt release cannot silently push costs back up.

    7. Capacity and Architecture Benefits

    A higher hit rate does more than save money. Reusing intermediate states usually reduces prefill time, which helps time to first token (TTFT) and throughput. On a container platform, the same number of replicas can serve higher concurrency. At the gateway layer, message queues can smooth peaks and isolate retries so that a burst of misses does not hit the backend all at once. If an organization also uses similar general-purpose capabilities on platforms such as Baidu AI Cloud, the same methodology of “stable prefix + metric monitoring” applies, keeping cost accounting consistent across clouds.

    8. Common Pitfalls

    1. Assuming a price cut guarantees a lower bill: without changing how you call the API, the hit rate stays flat and savings are zero.
    2. Putting dynamic content first: a single timestamp can turn the entire input into a miss.
    3. Over-splitting prompts: switching templates too often invalidates the cache repeatedly.
    4. Optimizing input while ignoring output: for long-output scenarios, apply length limits and summarization as well.
    5. Overlooking regional differences: this adjustment covers a single regional node only; multi-region deployments must be calculated separately.

    9. Action Checklist

    1. Inventory the input composition of top call paths and locate long, fixed prefixes.
    2. Refactor request templates into stable and volatile segments and bring them under version control.
    3. Build dashboards for hit rate and cost per request, with regression alerts.
    4. Re-estimate budgets with the cost model and convert savings into higher concurrency or longer context.
    5. Validate the impact of prompt releases on hit rate in a canary environment before a full rollout.

    In short, a “discount on the hit portion only” policy hands cost optimization back to engineering. Whoever governs request structure first gains a multiple-fold cost difference at the same unit price.