LLM Prompt Caching Hit Rate and Cost Optimization: A Practical Guide

    This article explains how to diagnose and resolve unexpectedly high costs in long-context LLM conversations. It shows how to compare billing with token usage, trace why prompt caching may look enabled but never take effect, apply fixes such as explicit cache markers, stable prefixes, and gateway passthrough, and verify results through cache read and write counts. You will also learn how caching prices work and which operational practices prevent cached context from being billed at full price repeatedly.

    1. Where the Problem Starts: Unexpected Costs in Long Conversations

    In practice with AI coding tools and multi-model aggregation gateways, a common pattern is that as conversations grow longer and context keeps accumulating, account balances drain faster than expected. A few turns can consume several dollars, each request record sits in the 0.3–0.7 USD range, and every entry stays at roughly the same level. This kind of “consistently expensive” behavior is itself a warning sign.

    The first step in troubleshooting is to turn “expensive” from a subjective impression into a measurable indicator. A practical approach is to build a simple reconciliation table:

    Metric Source Purpose
    Input tokens Request-side statistics Estimate theoretical cost
    Output tokens Response-side statistics Estimate theoretical cost
    Actual charge Billing details Compare with theoretical cost
    Total context length Session management Determine whether the long-context range is reached

    Calculate theoretical cost by multiplying the official price tiers by token usage, then compare it item by item with the actual charge. If the actual charge is much higher than the theoretical value, the request is not receiving any discounted billing. If the two are close, the caching mechanism is most likely already working. This step is the foundation of the entire investigation. Skipping it and guessing whether “caching is not enabled” often leads to wandering through configuration options.

    2. Root Cause Breakdown: Why Caching Looks Enabled but Is Not Working

    Token consumption in long conversations has clear structural characteristics: the system prompt, tool definitions, and conversation history are almost identical across turns, and only the latest turn’s incremental content actually changes. This means more than 70% of input tokens could theoretically be billed at cache prices. When actual charges are calculated at full input prices, the root cause usually falls into one of the following four categories:

    1. Missing fields at the protocol layer

    Different protocols control caching differently. Native vendor SDKs often automatically include cache control markers in request bodies, while the OpenAI-compatible protocol does not inherently contain an equivalent explicit field and requires the caller to inject it. If the call path uses a compatible protocol and neither the client, gateway, nor routing layer supplies the field, caching exists only nominally.

    2. Intermediate layers do not pass through extension fields

    Multi-model aggregation gateways are essentially protocol conversion and request forwarding. Some gateways proactively trim extension fields they do not recognize to keep the interface simple. Others require extension parameters to reach the backend through a dedicated passthrough mechanism, such as extra request headers or a nested provider configuration object. Fields being dropped at the gateway is the most common failure cause in long conversations.

    3. Cache key granularity mismatch

    Cache hits depend on exact prefix matches. A request must start with the cacheable portion and put content that changes each turn at the end. The following patterns all drive the hit rate to zero:

    • Dynamically inserting timestamps, random IDs, current usernames, and other volatile content before each turn;
    • Placing the system prompt after historical messages or mixing dynamically rendered content into history;
    • Regenerating tool definitions every turn, causing subtle changes in field order or content.

    4. Routing policies rewrite requests

    Changing routing preferences from the default to options such as “price first” only affects backend provider selection and scheduling and does not participate in cache marker generation. Such changes therefore do not improve the hit rate. This is one of the easiest places to go astray during troubleshooting.

    3. General Remediation: Getting Cache Markers to Reach the Backend Reliably

    Without changing the model, verify the following items in order, from lowest to highest cost:

    Step 1: Explicitly declare the cache scope

    If using a compatible protocol, attach cache control markers to the system message and early user messages. The structure is shown below (field names follow the documentation of the platform you use and must not be invented):

    1. {
    2. "model": "claude-opus-4.7",
    3. "messages": [
    4. {
    5. "role": "system",
    6. "content": [
    7. {
    8. "type": "text",
    9. "text": "<stable system prompt>",
    10. "cache_control": { "type": "ephemeral" }
    11. }
    12. ]
    13. },
    14. { "role": "user", "content": "<current turn's question>" }
    15. ]
    16. }

    The key point is that content must use a structured array to carry the markers. Plain string messages usually cannot carry cache control information.

    Step 2: Raise the stable prefix

    Caching matches by prefix, so more stable content means more benefit. The recommended content order is: system prompt → tool/function definitions → domain knowledge or long-term context → conversation history → current turn’s input. Keep reusable long documents, coding standards, and interface descriptions at the front and do not reorder them between turns.

    Step 3: Send parameters through the gateway passthrough channel

    If the gateway supports provider-level extension configuration, pass caching parameters together in a nested structure:

    1. {
    2. "model": "claude-opus-4.7",
    3. "provider": {
    4. "order": ["available channels prioritizing price"],
    5. "allow_fallbacks": true
    6. },
    7. "messages": []
    8. }

    Check the interface documentation of your gateway for the available key names and values. Guessing is not recommended. Invalid key names may be silently ignored, leading to a false assumption that caching is “enabled.”

    Step 4: Verify hits, not just the absence of errors

    A 200 response only proves the call succeeded, not that caching worked. The real evidence is the token usage breakdown in the response: cache read and cache write should appear as separate counts, and cache read tokens should grow as turns increase. The accounting formula can be simplified as:

    1. Theoretical cost this turn = Uncached input × Input unit price
    2. + Cache write tokens × Write unit price
    3. + Cache read tokens × Read unit price
    4. + Output tokens × Output unit price

    Sum the four items and compare with the billing amount. An error within a reasonable range indicates the caching pipeline is working.

    4. Cost Analysis: How Much Can Caching Actually Save

    Understanding the savings requires distinguishing three types of prices: regular input price, cache write price, and cache read price. The industry convention is that cache write prices are at the same tier as or slightly higher than regular input prices, while cache read prices are only a small fraction of the regular input price. Therefore, the economics of caching come from “write once, read many times” reuse, not from a single call.

    Three practical conclusions follow:

    1. The longer the session, the greater the benefit. For short single-turn conversations, write costs cannot be amortized and may even slightly increase total spending. Caching only has a positive return when the same stable prefix is called repeatedly.
    2. Caching expires when the session ends. Caches usually have an expiration time and must be rewritten after prolonged idleness. Batch offline tasks should run continuously in close succession to avoid long gaps.
    3. Frequent prefix changes mean paying repeatedly. If the system prompt or tool definitions change every turn, the cache will keep invalidating and rewriting, and the final cost may be higher than not using caching at all.

    5. Engineering Implementation Checklist

    • Encapsulate request construction at the application layer to ensure the system message and tool definitions are generated from the same template. Prohibit business modules from assembling them individually.
    • Build logging for token usage and costs, recording the cache read/write ratio per session and setting alerts for abnormal thresholds.
    • During the grayscale stage, route the same batch of requests through two paths—one with cache markers and one without—and verify the benefit with real billing before full rollout.
    • Clean volatile fields from requests, including timestamps, request IDs, and randomly ordered keys.
    • Keep a minimal reproducible test case to enable quick regression after platform interface changes.

    6. Frequently Asked Questions

    The fields are confirmed to be sent, but why is there no cache read count in the response?

    Possible reasons include the stable prefix length not meeting the platform’s minimum cacheable size, or subtle changes to the prefix between turns. Print two turns’ request bodies and perform a byte-by-byte diff to confirm.

    Why does the cache hit rate fluctuate in multi-turn conversations?

    This is usually caused by parallel branch conversations or tool call results being inserted into the middle of the history, breaking prefix continuity. Dynamic content should be uniformly appended to the end of the sequence.

    What if different models have inconsistent caching capabilities?

    Caching is a capability jointly determined by the model and the platform. You cannot assume consistent behavior when switching models. It is recommended to maintain separate request construction templates and billing assumptions per model at the routing layer.

    7. Summary

    The essence of abnormal costs in long conversations is often not that the model is too expensive, but that reusable context is being billed repeatedly at full price. The correct troubleshooting order is: first use billing and token details to complete quantitative comparison, then check protocol fields, gateway passthrough, prefix stability, and routing policies in sequence, and finally use cache read/write counts as the sole acceptance criterion. Once these four steps are embedded into the request construction and monitoring systems, spending in long-context scenarios can usually be optimized by an order of magnitude, while model capabilities and interaction experience remain unchanged.