Troubleshooting Prompt Cache Misses in LLM APIs to Reduce Costs

    This article explains why multi-turn LLM API conversations can cost more than expected when prompt caching does not take effect. It covers the billing logic of cache writes and cache reads, methods for verifying cache usage through usage details and cost reconciliation, six common causes of cache misses, a step-by-step troubleshooting and remediation process, and long-term cost optimization practices such as hit-rate monitoring, spend alerts, prefix design, and model selection.

    1. Symptom: Multi-Turn Conversation Costs Exceed Expectations

    In long-context, multi-turn conversations, developers often notice that their balance decreases much faster than expected. Individual calls may be charged at a relatively high rate, ranging from a few tenths of a dollar to nearly one dollar. This usually has two causes: the context is genuinely long and contains a large number of input tokens, or prompt caching is not working and the historical content in each request is billed at the full standard input price.

    Do not rely on intuition alone when troubleshooting. A more reliable approach is to map each call’s input tokens, output tokens, cache-related usage, and actual charge, then reconcile the cost using unit prices. If the calculated cost matches the actual charge, the billing logic is behaving as expected. If the theoretical cost is clearly lower than the actual charge, there is a strong possibility that caching is not taking effect.

    2. How Prompt Caching Is Billed

    Prompt Caching is a mechanism offered by many large model services. The service records the computation results for a certain prefix in a request. When the prefix in a later request is exactly the same, that content does not need to be recomputed, and it is billed at a lower read price.

    The input tokens in a request are usually divided into three categories:

    • Uncached input: The portion that does not hit the cache and is billed at the standard input price.
    • Cache write: The portion written to the cache for the first time. The write price is usually higher than the standard input price and represents the cost of establishing the cache.
    • Cache read: The portion that hits the cache. The read price is usually much lower than the standard input price and is a major source of savings in multi-turn conversations.

    Output tokens are not affected by caching and are still billed at the output price.

    Note that write multipliers, read discounts, and cache lifetimes vary by provider. Specific values should be based on the provider’s public pricing documentation; this article does not assume specific numbers.

    3. How to Determine Whether Caching Is Actually Working

    3.1 Check Usage Details

    Most services include cache-related fields in usage responses or billing details, usually distinguishing cache read tokens from cache write tokens. If these fields remain at zero for a long time while the conversation history is already long, caching is very likely not taking effect.

    3.2 Reconcile Costs

    The following example converts usage into a theoretical cost so it can be compared with the actual charge:

    1. def estimate_cost(usage, price):
    2. """
    3. usage: Usage for a single request, including token counts for each category
    4. price: Public unit prices for each category from the provider (per million tokens)
    5. """
    6. plain_input = usage["uncached_input"]
    7. cache_write = usage["cache_write_input"]
    8. cache_read = usage["cache_read_input"]
    9. output = usage["output"]
    10. cost = (
    11. plain_input * price["input"]
    12. + cache_write * price["cache_write"]
    13. + cache_read * price["cache_read"]
    14. + output * price["output"]
    15. ) / 1_000_000
    16. return cost

    If the calculated result is close to the actual charge, cache billing is working. If the calculated result is close to the value obtained by billing all input at the standard price, the cache is not hitting.

    3.3 Run a Controlled Experiment

    The most direct verification method is to send the same request twice in succession, with an interval shorter than the cache lifetime. The first request should produce a cache write, and the second request should show a cache read. If the second request still has no read record, the problem must be somewhere in the request path.

    1. def check_cache_effect(send, payload):
    2. first = send(payload)
    3. second = send(payload)
    4. if second.usage["cache_read_input"] > 0:
    5. return "Cache is working"
    6. return "Cache is not working; inspect the request path"

    4. Six Common Causes of Cache Misses

    4.1 Protocol Conversion Drops Cache Markers

    Some intermediate gateways convert requests into a unified chat API format. If the conversion process discards cache breakpoint markers, the upstream service cannot identify where caching should occur. In this case, requests return normally but are billed at full price, making the issue difficult to notice.

    To address this, confirm whether the API format in use supports passing through cache-related parameters, and review the provider’s documentation on caching. If uncertain, compare the results directly against a native API connection.

    4.2 Unstable Prefix Content

    Caching depends on an exactly identical prefix. The following practices can break the prefix:

    • Inserting dynamic content such as the current time or a request ID at the beginning of the system prompt.
    • Changing the order of tool definitions on each request.
    • Modifying, deleting, or reordering historical messages in the middle of a conversation.

    4.3 Prefix Too Short

    Many services require a cacheable prefix to reach a certain minimum length. Even if a short prompt has a stable structure, it may not enter the cache.

    4.4 Cache Expiration

    Caches have a lifetime and expire after no new requests for an extended period. If the interval between conversation turns is too long, the next turn will write the cache again.

    4.5 Scattered Request Routing

    A single service is often backed by multiple compute nodes. Caches are generally stored on specific nodes. If requests are distributed across different nodes, even a stable prefix may fail to hit. Some services offer session affinity or same-channel routing options to reduce this problem.

    4.6 Concurrency and Duplicate Writes

    Multiple concurrent requests carrying the same prefix may all be writing the cache while none of them complete a cache read. For batch jobs, send one request first to complete the cache write, then send the remaining requests concurrently.

    5. Troubleshooting and Remediation Steps

    Check the following items in order:

    1. Confirm the API format: Verify that the API in use supports passing through cache parameters.
    2. Run a controlled experiment: Send the same request through a direct connection and through the intermediate gateway, then compare the usage fields.
    3. Stabilize the prefix structure: Put static instructions first and dynamic information at the end in the user message.
    1. # Not recommended: dynamic content is in the prefix, so the prefix changes on every request
    2. system = f"Current time: {now()}\nYou are a coding assistant. Follow these guidelines..."
    3. # Recommended: static instructions are in the prefix, and dynamic information is at the end of the user message
    4. system = "You are a coding assistant. Follow these guidelines..."
    5. messages = history + [
    6. {"role": "user", "content": f"Current time: {now()}\n{question}"}
    7. ]
    1. Control request intervals: When idle time approaches the cache lifetime, you can send a lightweight request at an appropriate moment to keep the cache alive. This practice should be balanced against the cost of the keep-alive requests themselves.
    2. Compress historical content: When the history is too long, compress earlier conversation into a summary. This reduces input volume and also helps stabilize the prefix.

    6. Long-Term Cost Optimization Recommendations

    6.1 Monitor Cache Hit Rate

    Record cache reads, cache writes, and uncached input for each request in logs, and calculate the hit rate daily:

    1. def cache_hit_rate(records):
    2. read = sum(r["cache_read_input"] for r in records)
    3. write = sum(r["cache_write_input"] for r in records)
    4. plain = sum(r["uncached_input"] for r in records)
    5. total = read + write + plain
    6. return read / total if total else 0.0

    If the hit rate remains low over time, prioritize checking prefix stability and the API request path.

    6.2 Set Spend Alerts

    When balance consumption rate becomes anomalous compared with the historical hit rate, trigger an alert immediately to avoid sustained full-price spending over time.

    6.3 Distinguish Task Types

    Fixed instructions, tool definitions, and reference materials are suitable for the cache prefix and should remain unchanged for long periods. Frequently changing task content should be placed at the end. Separating the two types of content can improve hit rate and reduce duplicate writes at the same time.

    6.4 Evaluate Model Choice

    High-end models have higher unit prices. For tasks such as classification, format conversion, and simple question answering, test with a lower-cost model first before deciding whether a high-end model is necessary. Model selection should be based on task quality; caching is only one part of reducing per-call cost.