How to Cut LLM API Costs by Up to 90%: A Practical Guide to Prompt Caching

    This article explains why LLM API bills often grow faster than request volume, and how prompt caching addresses the root cause. It covers how caching works, the write premium and read discount in cache-based pricing, a break-even formula for cost estimation, which workloads benefit and which do not, a six-step engineering rollout, common pitfalls, and suggestions for building a measurable cost optimization loop on Baidu AI Cloud. Readers will learn how to structure context layers, align reuse windows, and track hit rates to reduce input-side costs.

    1. The Root of Cost Anxiety: You Are Not Only Paying for Answers

    Many teams discover after launch that their LLM bill grows much faster than their request volume. The reason is that cost is not determined only by how many questions users ask. It is also shaped by the size of the context carried in each request, how much of that context is repeated, and how well caching is used.

    A typical request input consists of three parts: system instructions and role settings, domain knowledge and tool descriptions, and multi-turn conversation history. The content that actually adds new information for the user is often only a small fraction. The rest is transmitted repeatedly. When that repeated content is billed at full price, cost is amplified without delivering value.

    So the first principle of cost optimization is this: identify the reusable prefix, make it billed once at a discounted rate, and pay only a small fee to read it on subsequent requests.

    2. How Prompt Caching Works

    The mainstream approaches share the same basic idea: mark the stable, unchanging prefix of a request (system instructions, long documents, codebase context, tool definitions, and so on) as cacheable. The server retains the computed result for a period of time. If a later request has an identical prefix, the result is reused directly, with no recomputation.

    A cache hit usually requires the prefix to match byte for byte. This means that inserting a timestamp, a random ID, or a username anywhere will invalidate the entire cache. In engineering terms, the “stable part” and the “dynamic part” must be strictly separated into layers.

    An illustrative way to organize a request:

    1. [Stable prefix: role settings + domain knowledge + tool descriptions] ← marked as cacheable
    2. [Semi-stable section: conversation summary] ← handle with care
    3. [Dynamic tail: current user input, timestamp, session ID] ← placed last

    3. Billing Characteristics: Discounts and the Write Premium

    Cache-based pricing generally has two directions:

    • Write (cache creation): when the cache is first created, input tokens are billed at a markup, commonly around 25% above the original price. This is a one-time premium paid in exchange for later discounts.
    • Read (cache hit): the hit portion is billed at a small fraction of the original price. One of the more aggressive approaches in the industry charges as little as 10% of the original price.

    At the same time, caches are not retained permanently. A common lifetime is on the order of minutes (for example, around 5 minutes), and requests can extend the survival time, though extension also incurs additional storage charges.

    Transparency is another key capability: mature implementations return the number of tokens written and the number of tokens hit in the response, which makes precise accounting possible. Without such metering fields, cost optimization cannot be verified.

    4. Cost Estimation: Calculate the Break-Even Point First

    Let the prefix token count be P, the write premium coefficient a = 0.25, the read discount coefficient r = 0.10, and the number of reuses within the cache lifetime window be N. The savings ratio relative to “no cache” is:

    1. Savings = (N - 1) × (1 - r) - a
    2. Break-even: N ≥ (1 + a) / (1 - r) ≈ 1.39

    The conclusion is clear: as long as the prefix is reused more than twice within one cache cycle, you already start to profit. The more reuses, the closer the marginal benefit approaches 90%. Conversely, if the prefix differs on every request, the write premium only makes the bill more expensive.

    5. When It Fits and When It Does Not

    Good fits:

    • Coding tools and code assistants: repository conventions, dependency descriptions, and interface documentation are stable over the long term and reused frequently.
    • Customer support and knowledge base Q&A: the same product manual or terms document is shared across a large number of requests.
    • Batch structured extraction: the same schema and prompt template process thousands of records.
    • Agent loops: multiple tool calls within the same task share the same system context.

    Poor fits:

    • Prefixes that contain volatile fields such as timestamps, random numbers, or auto-increment IDs.
    • Low-frequency long-tail requests, where the cache expires before it is reused.
    • Scenarios where the context is highly personalized on every request.

    6. Six Steps to Production

    1. Layer the context: split the prompt into a stable layer, a semi-stable layer, and a dynamic layer, and always place dynamic content last.
    2. Stabilize the prefix: remove timestamps and random identifiers from the prefix, and move variable information to the tail.
    3. Align the reuse window: schedule batch jobs and concurrent requests within the same cache cycle to increase N.
    4. Meter and build dashboards: collect write tokens, hit tokens, and hit rate, and calculate unit cost per business line.
    5. Fallback on a miss: when the cache misses, automatically fall back to a normal call so functionality is unaffected.
    6. Lifecycle governance: periodically compress the prefix size and remove expired, redundant knowledge to avoid a “long prefix with low hit rate.”

    Illustrative pseudocode:

    1. def call_llm(stable_prefix, dynamic_tail):
    2. payload = {
    3. "system": stable_prefix, # stable, cacheable
    4. "cache_control": {"ttl": "short"}, # short-lived cache
    5. "messages": [{"role": "user", "content": dynamic_tail}]
    6. }
    7. resp = client.create(**payload)
    8. usage = resp.usage
    9. hit = getattr(usage, "cache_read_input_tokens", 0)
    10. write = getattr(usage, "cache_creation_input_tokens", 0)
    11. metrics.record(hit=hit, write=write)
    12. return resp

    7. Common Pitfalls

    • Prefix drift: a formatted timestamp embedded in the template keeps the hit rate at zero over the long term.
    • Unstable ordering: knowledge fragments are concatenated in dictionary order rather than a fixed order.
    • Over-caching: stuffing an entire large document into the prefix, so the write cost exceeds the read savings.
    • Watching only the discount, not the hit rate: no matter how high the discount is, it means nothing if the hit rate is zero.
    • Ignoring consistency: prefixes generated by different instances differ, so the cache is rebuilt repeatedly.

    8. Putting It into Practice with Baidu AI Cloud

    On Baidu AI Cloud’s model services and general cloud infrastructure, the methods above can be consolidated into standardized capabilities: use object storage to host stable knowledge documents, use a message queue to smooth peaks and align cache reuse windows, and use log services with monitoring and alerting to build dashboards for hit rate and unit cost, forming a “measurable, regression-testable, governable” cost optimization loop. Note that the specific billing coefficients and cache duration should be based on the actual service documentation; the figures in this article are only used to explain the methodology.

    9. Conclusion

    The focus of LLM cost governance is shifting from “switching to a cheaper model” to “paying only once for repeated context.” If you make context layering solid, arrange the reuse window well, and bring the hit rate into monitoring, most high-frequency scenarios can compress input-side costs by an order of magnitude. First calculate the break-even point, then restructure the prompt, and finally validate the gains with data. This is a reproducible, auditable path to lower costs.