LLM Cost Optimization: A Practical Guide to Prefix Caching and Cache-Hit Billing

    This article breaks down why input-side cost has become the main battleground in token-based LLM inference, and how cache-hit billing turns prefix cache reuse into a measurable pricing dimension. It explains the prefill and decode cost structure, presents the core cost formula with a configurable discount factor, and lists the engineering factors that determine hit rate. You will find a five-layer prompt design for stable cacheable prefixes, key metrics for cost observability, common pitfalls, and a step-by-step rollout roadmap to reduce per-request input cost without sacrificing output quality.

    1. Background and the Technical Abstraction

    A cloud provider recently announced a price reduction for a general-purpose large model service on its Model-as-a-Service (MaaS) platform, effective November 23, 2026, 00:00 (Beijing time), in a specific region. The adjustment: input pricing for the cache-hit portion drops to 20% of the original price, while all other billing items remain unchanged.

    Strip away the specific date, region, and product name, and the part worth a developer’s attention is not “another price cut.” It is the structural shape of the cut: only cached input gets cheaper, everything else stays the same. This signals that cloud providers are turning prefix cache reuse from an internal engineering optimization into a public, auditable billing dimension. For consumers, that is both a cost-optimization opportunity and a signal that architecture needs to be reorganized around “cacheability.”

    This article does not evaluate any specific vendor’s capabilities. Instead, it abstracts the topic into a general engineering question: in token-billed inference services, how do you systematically reduce per-request cost through prompt prefix caching and billing model design?

    2. Why the Input Side Is the Main Cost Battleground

    The cost of LLM inference can be roughly split into two phases:

    • Prefill: a single forward pass over all input tokens to produce the KV Cache. This is compute-intensive and scales roughly linearly with input length.
    • Decode: token-by-token autoregressive generation, mainly constrained by memory bandwidth and tied to output length.

    In many real workloads (customer support Q&A, coding assistants, document review, multi-turn agent tool calls), the input is often several times to tens of times longer than the output. System prompts, tool definitions, knowledge base snippets, and conversation history get prepended to every request, and this prefix content is highly repetitive across consecutive requests.

    The waste is obvious: every request re-runs prefill over the same few thousand or tens of thousands of tokens. The idea behind prefix caching is to retain the KV Cache for that shared prefix so subsequent requests can reuse it and skip the duplicate computation.

    Billing then becomes more granular: cached input tokens are no longer charged at full price but at a discounted rate. In this case, “adjusted to 20% of the original price” means the hit portion is billed at two-tenths, while the miss portion and other billing items stay at full price.

    Note that the discount ratio, the region where it applies, and the effective window are commercial decisions that each platform can change at any time. Do not hardcode any fixed discount into your cost model; make it a configurable parameter.

    3. The Core Formula for Cache-Hit Billing

    Let:

    • N: total input tokens per request
    • H: input token hit ratio (0 to 1)
    • P_in: full input token unit price
    • d: cache-hit discount factor (0.2 in this case)
    • P_out: output token unit price
    • M: number of output tokens

    The cost of a single request is:

    1. Cost = N * P_in * (H * d + (1 - H)) + M * P_out
    2. = N * P_in * (1 - H * (1 - d)) + M * P_out

    Here H * (1 - d) is the cost savings rate. With d = 0.2, every 10 percentage point increase in hit ratio cuts input cost by 8%.

    A concrete comparison: at H = 0.8, input cost falls to 1 - 0.8 * 0.8 = 36% of the original. Raising H from 0.5 to 0.9 drops input cost from 60% to 28%, a reduction of more than half. Hit ratio is a more sensitive lever than unit price.

    4. Key Engineering Factors That Determine Hit Ratio

    Hit ratio is not luck; it is determined by how requests are constructed. The main factors:

    1. Prefix stability: the shared prefix must be byte-for-byte identical. A timestamp, a random request ID, or a change in JSON field order invalidates the prefix.
    2. Prefix position: reuse happens over the longest common prefix. Put volatile content first and everything cacheable after it is invalidated too.
    3. Content length and granularity: a very short prefix yields little benefit; a very long prefix with low reuse adds maintenance cost.
    4. Eviction policy: cache capacity is limited and hot prefixes get evicted. Retention duration and eviction strategies differ per platform and must be measured.
    5. Routing and region consistency: requests scheduled to different instances or regions hit differently. Since this change applies in a single region, billing policy is region-specific, and multi-region deployments need per-region accounting.
    6. Concurrency and timing: the first request populates the cache; only the requests that follow enjoy the hit. Cold starts and traffic bursts lower the overall hit ratio.

    5. Prompt Layering for High Hit Rates

    Order request content by rate of change, from lowest to highest, to form a stable cacheable prefix:

    1. [Layer 1] System role and global constraints -- almost never changes
    2. [Layer 2] Tool/function definitions and specs -- changes per version
    3. [Layer 3] Domain knowledge, long docs, code context -- changes per batch
    4. [Layer 4] Multi-turn conversation history -- appended within a session
    5. [Layer 5] Current user query, timestamps, other volatile fields -- changes every request

    Construction example (pseudocode):

    1. def build_prompt(sys_cfg, tools, kb, history, query):
    2. # Layers 1-3 form the stable prefix; keep field order and serialization fixed
    3. prefix = (
    4. render_system(sys_cfg) # Layer 1
    5. + render_tools(tools) # Layer 2
    6. + render_kb(kb) # Layer 3
    7. )
    8. # Use canonical serialization to avoid prefix drift from dict order or whitespace
    9. prefix = canonical_json_dumps(prefix)
    10. suffix = render_history(history) + render_query(query)
    11. return prefix, suffix

    Engineering checklist:

    • Fix the serialization: standardize JSON key order, whitespace, and escaping; never concatenate random IDs.
    • Keep knowledge base chunks stable: name chunks by content hash after splitting, so re-splitting does not change the prefix.
    • Version tool definitions: switch prefixes by version when a tool schema changes instead of editing in place.
    • Append within a session, do not rewrite: keep the history prefix unchanged across turns and only append at the tail.

    6. Cost Observability: Make Hit Ratio a First-Class Metric

    No measurement, no optimization. Collect at least:

    • input_tokens_total, input_tokens_cached, cache_hit_ratio
    • prefill_latency_p50/p95 (a hit usually lowers time-to-first-token)
    • cost_per_request, cost_per_successful_task
    • breakdowns by region, business line, and model version

    A simplified accounting script:

    1. def estimate_cost(n_in, n_out, hit_ratio,
    2. p_in, p_out, discount=0.2):
    3. billable_in = n_in * (1 - hit_ratio * (1 - discount))
    4. return billable_in * p_in + n_out * p_out
    5. # Compare the benefit of raising hit ratio from 0.40 to 0.85
    6. base = estimate_cost(8000, 500, 0.40, 1.0, 2.0)
    7. tuned = estimate_cost(8000, 500, 0.85, 1.0, 2.0)
    8. print(f"Savings: {(1 - tuned / base):.1%}")

    Also build a regression dashboard: after each prompt template or chunking strategy change, check whether hit ratio and cost per task regress, so you do not “optimize the template and break the cache.”

    7. Common Pitfalls

    • Pitfall 1: Watching only unit price. Unit price is an external variable; hit ratio is the one you control.
    • Pitfall 2: Putting volatile fields first. A single timestamp invalidates the entire prefix.
    • Pitfall 3: Assuming uniform pricing across regions. Billing policies often vary by region and time window; model them per region.
    • Pitfall 4: Hardcoding the discount. Commercial terms change; inject the discount as configuration.
    • Pitfall 5: Ignoring cold starts. The first batch of requests after a deploy, scale-out, or cache eviction will have a low hit ratio; leave headroom in capacity planning.
    • Pitfall 6: Sacrificing quality for hits. Do not trim necessary context just to reuse a cache; hit optimization must not come at the cost of quality.

    8. Rollout Roadmap

    1. Baseline measurement: change nothing, and collect one week of input length distribution and current hit ratio.
    2. Prefix restructuring: reorder prompts into the five layers, unify serialization, remove random fields.
    3. Knowledge base stabilization: content-hash naming, fixed chunk granularity, version control.
    4. Routing affinity: keep the same session on the same instance/region as much as possible to improve local hits.
    5. Cost dashboard and alerts: put hit ratio and cost per task into daily monitoring with threshold alerts.
    6. Continuous tuning: review weekly and A/B test template changes for their impact on hit ratio and quality.

    9. Conclusion

    The signal from this price adjustment is clear: inference billing is moving from flat per-token pricing toward fine-grained pricing based on how much computation is reused. For developers, the real dividend does not go to those who wait passively for price cuts; it goes to teams that treat cache reusability as an architectural constraint. Build a solid stable prefix, measure the hit ratio, and make the discount configurable, and you can push input-side cost far below full price at the same level of business quality.