LLM API Cache Hit Billing Optimization: A Practical Guide to Prompt Caching

    This article explains how cache hit pricing on large language model APIs works and how engineering teams can systematically raise prefix cache hit rates to cut inference costs. It covers the mechanics of prefix caching, the key factors that determine hit rates (prefix stability, reusable content length, routing and instance affinity, session structure), a cost formula for estimating savings, and a practical implementation path spanning prompt layering, deterministic template rendering, retrieval ordering, model version and region selection, and observability. It also lists common misconceptions, such as treating semantic similarity as a cache hit or optimizing only the tail of a prompt. The guidance is vendor-neutral and applies to any MaaS platform that bills cached input separately.

    1. Background and Technical Abstraction

    A cloud provider recently announced that, starting 00:00 Beijing time on November 23, 2026, it will lower service prices for specific model versions in specific regions on its Model-as-a-Service (MaaS) platform. The adjustment applies only to the “cached input” billing item, which is set to 20% of the original price; all other billing items remain unchanged.

    The announcement is short, but the information density is high. It carries at least three technical signals:

    1. Inference cost structure is being broken down in finer detail. The input side is no longer a single “per thousand tokens” rate, but is split into “cached input” and “uncached input.” This indicates that prefix reuse capability already exists underneath, and that price levers are being used to encourage callers to actively optimize the shape of their requests.
    2. Part of the control over cost optimization returns to the caller. Hit rate is not determined unilaterally by the platform; it is jointly determined by how prompts are organized, how sessions are reused, and how batching is handled.
    3. Regional and version-specific pricing differences are becoming the norm. The same model may be priced differently across regions and versions, so cost governance must account for deployment topology and version selection.

    This article does not evaluate or recommend any specific vendor’s product. Instead, it abstracts the change into a general engineering problem: under a billing model where part of the input is reusable, how to systematically improve cache hit rate and thereby reduce the inference cost per business request.

    2. How Prompt Caching Works (General Understanding)

    Mainstream inference acceleration approaches generally follow the idea of “prefix caching.” The core assumption is that if the beginning of an input token sequence in a request is exactly identical to that of a previous request, the intermediate computation results for that portion (attention keys and values, and so on) can be reused without recomputation.

    Several properties that follow from this are critical to engineering practice:

    • Matching is prefix matching, not arbitrary fragment matching. Cache reuse is evaluated starting from the beginning of the sequence; once a difference appears at some position, content after that position generally cannot hit.
    • Matching is at token granularity, not character granularity. Changing a seemingly harmless punctuation mark, space, or line break can alter tokenization and invalidate the entire prefix.
    • Cache entries are time-sensitive. They are typically constrained by capacity limits and time-to-live, and entries not accessed for a long time are evicted.
    • A hit delivers a double benefit. Beyond the billing discount, the skipped prefix computation also reduces time to first token (TTFT), and improves throughput under high concurrency.

    Understanding these four points explains most cases in practice where “the hit rate won’t go up.”

    3. Key Factors Affecting Hit Rate

    3.1 Prefix Stability

    System prompts, tool definitions, few-shot examples, and fixed knowledge base passages are low-frequency-changing, high-length-proportion content, and they are the main source of caching gains. If volatile fields such as timestamps, random request IDs, or user nicknames are placed at the beginning of the prompt, everything after them will fail to hit.

    3.2 Content Length and Proportion

    Caching gains correlate positively with the length of the reusable prefix. A 4,000-token fixed block followed by a 50-token user question yields a naturally high hit rate; conversely, if the fixed portion is only one or two hundred tokens, there is limited room for optimization.

    3.3 Request Routing and Instance Affinity

    Caches are usually bound to a specific inference instance or a specific model version. If a load balancer spreads semantically identical requests across a large number of instances, or if calls mix multiple model versions or multiple regional endpoints, the hit rate is diluted.

    3.4 Session and Concurrency Patterns

    In multi-turn conversations, stably concatenating the full history in a fixed order lets each turn reuse the prefix from the previous turn; frequently “summarizing and rewriting history” breaks that reuse chain.

    4. Cost Estimation: Do the Math Before Acting

    Assume a billing item has an original price of P (per thousand tokens), cached input is charged at 20% of the original price, and uncached input at the original price. Let a request have T thousand input tokens, of which the reusable prefix is H thousand tokens. The input cost per request is:

    1. Cost = 0.2 * P * H + P * (T - H)
    2. = P * (T - 0.8 * H)

    Input cost therefore falls linearly with the hit volume: every thousand tokens hit saves the original-price cost of 0.8 thousand tokens. When H / T = 0.75, input cost has already dropped to 40% of the original price; as H / T approaches 1, input cost approaches 20% of the original price.

    In engineering terms, it is advisable to build this formula into a cost dashboard and track T, H, and the discounted amount separately by business line, model version, and region, avoiding the situation of “seeing only the total bill without knowing where the money went.”

    5. Implementation Path

    5.1 Prompt Layering and Fixed Ordering

    Divide the prompt into a “stable layer — semi-stable layer — volatile layer,” and concatenate strictly in that order:

    1. [Stable layer] Role definition, output specification, tool schema, safety policy, fixed examples
    2. [Semi-stable layer] Retrieved knowledge fragments (organized by a fixed ordering rule)
    3. [Volatile layer] Session history, current user input, timestamps, etc.

    The key constraint: volatile content always goes last, and no runtime-generated field should be inserted into the stable layer.

    5.2 Deterministic Template Rendering

    Template engines often introduce nondeterminism by default, which needs to be constrained explicitly:

    1. import json
    2. def render_prompt(system: dict, history: list[dict], query: str) -> str:
    3. # 1) Stable layer: sorted keys + fixed separators to guarantee byte-level consistency
    4. stable = json.dumps(system, ensure_ascii=False, sort_keys=True,
    5. separators=(",", ":"))
    6. # 2) Semi-stable layer: sort retrieved results by id ascending to avoid ordering jitter
    7. # 3) Volatile layer: placed at the end
    8. parts = [stable, "...fixed knowledge fragments..."]
    9. parts.append(json.dumps(history, ensure_ascii=False))
    10. parts.append(query)
    11. return "\n".join(parts)

    The essentials are sort_keys=True, fixed separators, explicit sorting of retrieved results, and prohibiting the use of random IDs or local time during rendering.

    5.3 Session History and Retrieval Strategy

    • In multi-turn scenarios, prefer append-only history maintenance and avoid rewriting a summary every turn, which changes the prefix.
    • In retrieval-augmented scenarios, apply stable ordering and a cap on the number of recalled results, so the same question does not retrieve different content on two occasions.
    • For high-frequency similar requests, normalize on the business side (strip extra whitespace, unify letter case and full-width/half-width forms) to reduce meaningless prefix differences.

    5.4 Routing, Versions, and Regions

    • Give requests using the same template instance affinity, reducing the chance of caches being scattered and evicted.
    • Pin the model version identifier and clearly separate endpoints during canary releases, avoiding version mixing that punches through the cache.
    • Since pricing may differ across regions and versions, cost-sensitive workloads should factor “price + hit rate” jointly into scheduling decisions rather than routing on latency alone.

    5.5 Observability and Continuous Tuning

    It is recommended to collect at least the following metrics and correlate them with business labels:

    • Cache hit rate (measured by tokens, not by requests);
    • Average reusable prefix length;
    • Time to first token and the overall latency distribution;
    • Input/output cost per business request;
    • Cache eviction and invalidation counts (if exposed by the platform).

    Tuning loop: locate the business line with a low hit rate → check whether its prompt has a volatile prefix → rework the template and retrieval ordering → compare hit rate and cost in a canary → roll out fully and codify the convention.

    6. Common Misconceptions

    1. Treating “a hit” as requiring only semantic similarity. In reality it is exact token-level prefix matching; semantically close but literally different text will not hit.
    2. Optimizing only the end of the prompt. Changes at the tail do not affect the prefix, so the gain is nearly zero.
    3. Ignoring tokenization differences. Inconsistent full-width/half-width forms, emoji, whitespace, and line-break styles all change the token sequence.
    4. Estimating the discount by request count. The discount applies to the volume of input tokens hit, so long and short requests differ greatly in actual savings.
    5. Reworking once and never observing again. Business iteration keeps introducing new volatile fields, so hit rate needs long-term monitoring.

    7. Conclusion

    The essence of this price adjustment is turning “input reuse capability” into a quantifiable economic signal. For developers and platform providers alike, the real opportunity lies not in chasing one vendor’s specific price, but in establishing a vendor-neutral prompt engineering convention + deterministic rendering + cost observability system. Once such a system is in place, no matter how billing items are split or prices adjusted, optimization opportunities can be located quickly, inference cost can be kept within a range the business accepts, and more stable latency comes along as a bonus.