How Context Caching Cuts LLM API Input Costs by Up to 90%

    This article explains why LLM bills grow faster than user traffic, and how context caching turns repeated prompt prefixes into discounted input tokens. You will learn the three mechanics that decide whether caching pays off (hit discount, write premium, cache lifetime), the break-even formula, the usage fields to collect for a cost dashboard, a layered caching architecture with example code, and common pitfalls to avoid.

    1. Where the Cost Actually Goes

    Many teams only notice the problem after traffic ramps up: the LLM bill grows far faster than the user base. The reason is straightforward. A single request is billed on both the input side and the output side, and the input side is routinely underestimated. System prompts, tool definitions, retrieved knowledge base chunks, and multi-turn conversation history are all replayed in full on every request. In other words, the same few thousand tokens of background context may already have been paid for hundreds of times.

    The first optimization step is not switching to a cheaper model. It is identifying this “repeat payment.” The common industry approach is context caching: keep the stable prefix of the context on the service side for a period of time, and when later requests hit that cache, those input tokens are billed at a significant discount. According to the source material, the deepest discount tier in the industry can drop to 10% of the original price, which is where the “90% cost reduction” claim comes from.

    One caveat matters: discount rates are billing policies set by each cloud provider, and they change with versions and regions. Do not hardcode a specific number in your engineering work; make it a configurable value.

    2. Hit Discount, Write Premium, and Lifetime: Three Mechanics You Must Understand

    Context caching is not a free lunch. Its economics are determined by three parameters that constrain each other.

    First, the hit discount. Cached input tokens are billed at a reduced rate, and the rate varies by provider, anywhere from 10% to 50% of the original price.

    Second, the write premium. Creating a cache entry usually means paying an extra “write fee” for the tokens being cached, commonly on the order of 1.25x the original price. The first request is therefore more expensive; only when there are enough subsequent hits does the premium get amortized.

    Third, the lifetime. Cache entries generally use a short-lived policy, commonly on the order of a few minutes, and extensions are often supported but are themselves billed. Once the window passes, the entry expires and the next request pays the write fee again.

    This yields a simple but critical break-even condition. Let the write premium be w (for example 0.25) and the hit discount be d (for example 0.1). The cumulative number of hits n must satisfy:

    1. n × (1 - d) > w → break-even
    2. With w=0.25, d=0.1: n > 0.28

    So a single hit within one lifetime already crosses the break-even line, and the denser the hits, the closer the savings get to the theoretical ceiling. Conversely, if the context changes on nearly every request, caching produces pure loss.

    3. Transparency and Observability: Verify Every Discount

    The most reusable idea in the source material is transparency. Mature implementations return cache-related usage fields in the response, such as the number of tokens written to the cache in this request and the number of tokens read from the cache. These two fields are the infrastructure for cost governance. Collect them consistently, ship them to your logging service and alerting system, and build a cache dashboard broken down by business line:

    • Cache hit rate = tokens read / (tokens read + uncached input tokens)
    • Write amplification ratio = tokens written / tokens read; a persistently high value means the prefix is unstable or the lifetime is too short
    • Cost per request = input cost + output cost, tracked separately for cache hits and misses

    Without this observability, any claim of “90% savings” is just an estimate.

    4. A Layered Caching Architecture You Can Ship

    The recommended engineering approach splits the context into three layers: stable, semi-stable, and dynamic. Only the stable and semi-stable layers go into the cache.

    1. # Illustrative code; confirm the interface shape against your platform's documentation
    2. SYSTEM_PROMPT = "You are an enterprise knowledge base assistant..." # stable layer: version controlled
    3. TOOL_SCHEMA = build_tools() # semi-stable layer: changes with releases
    4. def build_messages(user_query, history):
    5. return [
    6. {"role": "system", "content": SYSTEM_PROMPT},
    7. {"role": "system", "content": TOOL_SCHEMA},
    8. *history[-6:], # dynamic layer: not cached
    9. {"role": "user", "content": user_query},
    10. ]
    11. resp = client.chat.completions.create(
    12. model=MODEL,
    13. messages=build_messages(q, h),
    14. extra_body={"cache_control": {"type": "ephemeral"}}, # mark the cacheable prefix
    15. )
    16. usage = resp.usage
    17. print(usage.cache_creation_input_tokens, usage.cache_read_input_tokens)

    Four points matter in practice. First, the prefix must be byte-for-byte stable: timestamps, random IDs, and user nicknames all go at the end, because a one-character drift invalidates the entire prefix. Second, cache markers follow a longest common prefix rule: everything before the marker is included, so never insert volatile fields in the middle. Third, align cache writes with your release cadence, and rebuild proactively after a model or prompt change so stale entries are not reused. Fourth, add a kill switch that disables caching automatically when the write amplification ratio looks abnormal.

    5. Advanced Options and Common Pitfalls

    On top of basic prefix caching, there are three supplementary approaches. Semantic caching vectorizes past question-answer pairs into a vector database and reuses an old answer when a new question is similar enough; it fits high-repetition scenarios like customer support and FAQs, but you need a similarity threshold and a fallback generation path. Result caching keys on a normalized request fingerprint and stores responses in object storage or a distributed cache component, which suits batch jobs with a limited parameter space. Batching and asynchronous execution shift deferrable work off peak hours, trading throughput for unit price.

    The pitfalls are equally worth watching: putting volatile content in the prefix, which drives the hit rate toward zero; looking only at the discount and ignoring the write fee, which increases spending in low-frequency scenarios; assuming caching guarantees consistency, when in fact model output may change after an entry expires, so features with strong consistency requirements should not depend on the cache; and leaving sensitive information from prompts resident on the service side for long periods, which needs to be assessed against data lifecycle policies for compliance risk.

    6. Conclusion

    Context caching is essentially trading prefix stability for an input-side discount. It is not a feature exclusive to one product but a general pattern in LLM application engineering. Layer the context, keep the prefix stable, measure usage precisely, and make the switch easy to flip: most high-frequency, highly repetitive call paths can push input cost down to a fraction of what it was. To reduce engineering complexity further, you can build on general capabilities such as the model services, logging service, and monitoring and alerting offered by Baidu AI Cloud to stand up a call pipeline whose cost is observable and whose policies are configurable.