Prompt Caching for LLMs: A Practical Guide to Reducing Token Costs

    This guide explains why LLM API bills can stay high despite long-context caching expectations, and how to fix it. It covers how prompt caching works, why aggregation gateways often break cache hits, and step-by-step actions to enable caching, stabilize prefixes, and track cost observability. You will learn how to verify field pass-through, switch to native protocols when needed, and use a validation checklist to confirm that caching is actually reducing costs.

    1. Background: Why the Bill Is Higher Than Expected

    After connecting a third-party model aggregation gateway to an AI coding tool, many developers run into a familiar problem: only a few turns into a conversation, the account balance drops sharply. The charge for a single request climbs from a fraction of a dollar to an amount that exceeds what one session should reasonably cost. Intuitively, as the context grows, caching should kick in and the unit cost should fall, but the billing curve never shows an inflection point.

    To find the cause, the first step is not to compress the prompt further, but to break down the cost of a single request. LLM API billing usually consists of four parts: input tokens that miss the cache, input tokens that hit the cache, output tokens, and optional cache write (creation) overhead. The unit price for cache-hit input is typically only a small fraction of the regular input price, so when long contexts are submitted repeatedly, the hit ratio determines the order of magnitude of the overall cost.

    If the bill shows that every request is charged at the full input price, the most likely conclusion is that the cache was never created, or it was created but never reused. These two cases require different troubleshooting paths and should be verified separately.

    2. How Prompt Cache Hits Work

    The core idea of prompt caching is prefix reuse. For an identical prefix, the model service can reuse the already-computed intermediate state and skip redundant computation. This leads to two direct constraints:

    • The prefix must be byte-for-byte identical. Any character change, including timestamps, random numbers, or auto-generated session titles, invalidates the cache from the point of change onward.
    • Caches have a lifecycle. After an idle timeout, the cache is reclaimed and must be written again, so scattered, low-frequency requests benefit little.

    From this, an important engineering principle follows: put stable content first and volatile content last. System prompts, tool definitions, and long-term reference material belong to the stable zone; the user’s current-turn input, retrieval results, and temporary variables belong to the volatile zone. If this order is reversed, the hit rate approaches zero.

    A schematic message layout looks like this:

    1. [Stable prefix]
    2. system: role definition, output rules, tool schema, long-term knowledge
    3. [Reusable history]
    4. user/assistant: completed multi-turn conversation
    5. [Volatile tail]
    6. user: current-turn input, timestamp, retrieved snippets

    3. Common Causes of Cache Misses with Aggregation Gateways

    When calling models through an aggregation gateway, cache misses are often not a model capability issue but a case where some link in the chain drops or rewrites a critical field. Common causes include:

    1. Protocol conversion loss. The gateway exposes a generic OpenAI-style interface, while cache declarations are vendor-specific extension fields upstream. If the conversion layer does not pass the field through, the cache creation instruction is dropped before it reaches the model side.
    2. The request body is re-serialized. Changes to field order, whitespace, or escaping make the prefix hash inconsistent.
    3. Opaque provider routing. The default route may switch between multiple backends, spreading the same prefix across different instances and diluting the hit rate.
    4. Billing differences. Some gateways bill cache writes separately, so the bill may not drop in the short term; you need to observe the average over a longer window.

    It is worth emphasizing that support for caching and field naming vary across vendors and models, and you cannot assume it is enabled by default. Treating it as an optional capability that must be explicitly declared is the safer engineering assumption.

    4. Practical Steps to Enable Cache Hits

    Step 1: Confirm Whether the Field Is Passed Through

    Start with a minimal test: build a single-turn request with a long stable prefix, explicitly add the cache declaration in the request body, and check whether the response and usage details show cache creation and cache read counts.

    1. {
    2. "model": "<your model identifier>",
    3. "messages": [
    4. {
    5. "role": "system",
    6. "content": [
    7. {
    8. "type": "text",
    9. "text": "<place hundreds of lines of stable content here>",
    10. "cache_control": { "type": "ephemeral" }
    11. }
    12. ]
    13. },
    14. { "role": "user", "content": "current-turn question" }
    15. ]
    16. }

    If the usage fields in the response never show a cache read count, the declaration was dropped along the way, and you need to switch the calling protocol or connect through the native protocol.

    Step 2: Switch to the Native Protocol for Direct Connection

    When the generic protocol cannot carry extension fields, switching to the model vendor’s native interface usually solves the problem. The native interface treats cache declarations as first-class citizens, and its default behavior leans more toward automatic reuse. The cost is that you need to adjust the client’s request construction and response parsing logic.

    Step 3: Stabilize the Prefix and Extend the Reuse Window

    Fix tool definitions, system prompts, and fixed reference material so they are not mixed with changing content in every request. If you use an AI coding tool, disable options that automatically inject time, random identifiers, or dynamic titles.

    Step 4: Build Cost Observability

    Do not look only at the balance. At minimum, record the input, output, and cache-read token counts and converted cost for each request, and aggregate by session, so you can tell whether the optimization is actually working.

    1. Session A: 12 requests | 150k input total | 132k cache read (88%) | cost down ~70% vs. baseline
    2. Session B: 9 requests | 90k input total | 0 cache read | no cost change -> check field pass-through

    5. Validation and Tuning Checklist

    • Submit the same prefix in two consecutive turns; the second turn should show a clear cache read count.
    • If the second turn shows no hit, troubleshoot layer by layer: whether the client sends it, whether the gateway passes it through, and whether routing is fixed.
    • Watch cache write costs; short sessions may not be worthwhile, while long sessions and high-frequency calls offer the greatest benefit.
    • Version your prompts; when the prefix changes, assess the temporary cost increase from cache invalidation.

    6. Conclusion

    Cache hits are not an invisible default benefit, but an engineering capability that requires explicit declaration, a stable prefix, and an observable bill working together. On an aggregation gateway path, first confirm whether extension fields are passed through, return to native protocol access if necessary, and combine prefix layering with cost monitoring to bring long-context costs back into a reasonable range. If you need managed model services with supporting observability, you can look into Baidu AI Cloud’s related LLM services and log monitoring products.