How Context Caching Cuts LLM API Costs

    This article explains how context caching (also known as prefix caching) reduces LLM API bills by reusing previously computed input prefixes instead of recomputing them. It breaks down a token-based cost example, outlines the three conditions required for cache hits, and presents six practical optimization techniques, common pitfalls, and an engineering checklist for managing stable prefixes in long-context applications.

    1. The Starting Point: Why “Reading It Again” Becomes the Main Cost

    As large model applications move into the long-context stage, one easily underestimated fact stands out: what really drives up the bill is often not new content, but existing content that gets carried over repeatedly. Take a cloud vendor’s public off-peak pricing as an example: each million input tokens costs about 1 RMB on a cache miss and about 0.02 RMB on a hit. The two rates for the same reusable context differ by roughly 50x. If a project document of about 100,000 tokens needs to be read in full ten times, the gap between misses and hits widens to two orders of magnitude.

    Here, “cache” refers to context caching (often called prefix caching): when multiple requests share an exactly identical input prefix, the server can reuse the already-computed intermediate state and only compute the new portion, so the cached portion is billed at a significantly lower rate. Understanding this mechanism is the first step in cost governance.

    2. Breaking Down the Example: Where the Difference Comes From Across Ten Reads

    Assume a single input of 100,000 tokens, repeated 10 times, for a total of 1,000,000 tokens.

    • All misses: 1,000,000 × 1 RMB/million ≈ 1.00 RMB
    • All hits (except the first): about 1 miss + 9 hits ≈ 0.01 + 0.18 = 0.19 RMB

    The gap is nearly 5x, and it grows linearly with the number of repetitions: when repeated N times, the miss cost is on the order of N times the hit cost. If you scale the document to hundreds of thousands of tokens and the repetition count to over a hundred (typical of multi-turn code repository Q&A, long-document review, and batch extraction tasks), the cost difference shifts from “a few RMB” to the “hundreds of RMB” level.

    Key takeaway: caching gains do not depend on how strong the model is, but on whether the prefix is stable, whether requests are consecutive, and whether the content is reusable.

    3. Hit Conditions: Three Prerequisites That Must All Be Met

    1. Byte-for-byte identical prefix: The cache is keyed on the input prefix, so any change anywhere (even a single space or a timestamp) invalidates everything after it.
    2. Order cannot change: Putting variable content at the front drags all the reusable content behind it along for the ride.
    3. Reuse within the time window: The cache has a lifetime; too long an interval or improper concurrent scheduling degrades it to a miss.

    Illustrative pseudocode showing the “stable prefix + incremental suffix” organization:

    1. SYSTEM_PROMPT = "You are a code review assistant..." # stable
    2. PROJECT_INDEX = load_index("repo_v3") # stable, pinned by version
    3. def build_request(question, snippet):
    4. # keep the prefix exactly identical; only the suffix changes
    5. return [
    6. {"role": "system", "content": SYSTEM_PROMPT},
    7. {"role": "system", "content": PROJECT_INDEX},
    8. {"role": "user", "content": f"{snippet}\nQuestion: {question}"},
    9. ]

    4. Six Actionable Optimization Techniques

    • Pin the prefix: Fix system instructions, specification notes, repository indexes, and similar content by version number, and bump the whole version when changes occur rather than tweaking it each time.
    • Remove volatile fields: Move timestamps, random IDs, and request sequence numbers to the end or delete them, to avoid polluting the prefix.
    • Layer the content: Put static knowledge (specifications/glossaries) first, semi-static content (directory structure) in the middle, and dynamic content (the current question) last.
    • Batch and concurrency orchestration: Merge tasks that share the same context into a nearby time window to reduce cache idling.
    • Trim the input: Deduplicate, remove blank lines, and compress the number of examples; reducing the total token count benefits both hits and misses.
    • Cost observability: Log each request’s input size, hit status, and converted cost in logging and monitoring/alerting systems, aggregate by business dimension, and build a reviewable cost dashboard.

    5. Common Pitfalls

    • Assuming “switching models saves money”: unit price drops are linear, while hit-rate improvements are multiplicative.
    • Inserting the current time into the prompt: this is the most typical prefix killer.
    • Caching only the final response: what is reusable is on the input side; the output side cannot hit.
    • Ignoring version management: failing to bump the version after content updates leads to stale cache being misused or a full invalidation.

    6. Engineering Implementation Checklist

    1. Divide context into “stable / semi-stable / volatile” layers, and enforce the separation in the code structure;
    2. Establish a version-number mechanism for prompts and indexes, with changes going through review;
    3. Wrap a unified entry point on the calling side, and prohibit business code from assembling prefixes on its own;
    4. Add two core metrics—hit rate and per-request cost—and set threshold alerts;
    5. Prioritize prefix governance for high-repetition scenarios (batch review, long-document Q&A, repository-level retrieval in AI coding tools).

    7. Conclusion

    The cost optimization from context caching is essentially turning “repeated computation” into “compute once, reuse many times.” When input size reaches the hundreds-of-thousands-of-tokens level and call frequency reaches hundreds or thousands, the gains from stable-prefix design usually far exceed those from swapping any single parameter or model. Treating context as a “data asset” that needs version management is the sound engineering path to controllable cost in the long-context era.