Prompt Caching for LLMs: A Practical Guide to Lowering Long-Context API Costs

    This guide explains why long-context LLM applications can rack up unexpectedly high bills even when prompt caching is supposedly enabled, and how to fix it. It breaks down how prompt caching reduces cost through prefix reuse, how to diagnose cache misses in aggregated model gateways, and a four-step workflow to make caching work reliably. You will also find verification methods, cost metrics, common pitfalls, and engineering recommendations for managing prompts as versioned assets.

    1. Background: Why Costs Spike in Long-Context Scenarios

    In AI coding assistants and multi-turn chat applications, developers often access models from different vendors through an aggregated model gateway. These gateways unify authentication and protocols, offering an experience close to a standard OpenAI-compatible interface, but they differ in billing details.

    A typical symptom: an account is topped up with $40, and after just a few long-context turns the balance drops to $30; individual request logs show costs ranging from $0.5 to $0.7. At this point the context is roughly 100K tokens. By common intuition, if caching were working, the incremental cost should be far lower.

    This raises a key question: does the cost curve show a “constant high price every turn,” or “high on the first turn, then a significant drop”? The former almost certainly means the cache is not being hit and every turn is billed at the full input price; the latter indicates caching is working normally.

    2. How Prompt Caching Actually Saves Money

    The core idea of prompt caching is reuse. During LLM inference, input tokens go through attention computation to generate intermediate states (KV Cache). If the prefixes of two requests are exactly identical, the server can reuse the already-computed intermediate states and skip redundant computation. As a result, those input tokens receive a significant discount, while the initial write into the cache usually carries a slight premium.

    This leads to three practical conclusions:

    • Caching takes effect on exact prefix matching; only the common portion starting from the very first token can be reused.
    • The hit rate depends on prefix stability; any change at any position invalidates everything after it.
    • Billing is itemized: input is split into regular input and cache reads, output is priced separately, and cache writes are charged separately.

    An illustrative cost estimation logic is shown below (prices are placeholders only; refer to the provider’s published pricing for actual values):

    1. # Pseudocode: per-turn cost estimation
    2. cost = (
    3. uncached_input_tokens * P_IN
    4. + cache_write_tokens * P_WRITE
    5. + cache_read_tokens * P_READ # usually far lower than P_IN
    6. + output_tokens * P_OUT
    7. ) / 1_000_000

    If the logs show no cache_read-related field, or that field is always 0, you can confirm the caching pipeline is not activated.

    3. Root-Cause Investigation: Why Caching “Looks Off”

    Protocol conversion in aggregated gateways is the most common cause. When the client uses the OpenAI-compatible protocol, cache control information must be translated by the gateway into the target vendor’s proprietary fields. If the conversion layer does not pass through this extension field, the caching request degrades into a regular request. This explains the phenomenon of “connectivity is fine, output is fine, but no savings.”

    The second cause is routing strategy. Setting the provider preference to “price first” only affects which upstream is chosen and does not change the request body, so it offers no real help for the cache hit rate.

    The third cause is unstable request structure, including:

    • Inserting timestamps, random IDs, or retrieval results before the system prompt on every turn;
    • Tool definitions (tools) changing in order or content across turns;
    • Sampling parameters such as temperature being placed in the prefix region and changing along with content;
    • Message history being repeatedly rewritten, summarized, or trimmed, breaking prefix continuity.

    The fourth cause is cache lifetime. Cache entries typically have a short survival time (on the order of minutes), and long interaction gaps cause natural expiration.

    4. The Fix: Four Steps to Make Caching Work Reliably

    Step 1: Switch to native protocol access. If both the gateway and the upstream vendor support the native Messages protocol, prefer the native endpoint and explicitly declare cache control points in the request. Example:

    1. {
    2. "model": "<your-model-id>",
    3. "system": [
    4. {
    5. "type": "text",
    6. "text": "<stable system prompt>",
    7. "cache_control": { "type": "ephemeral" }
    8. }
    9. ],
    10. "messages": [
    11. { "role": "user", "content": "..." }
    12. ]
    13. }

    Step 2: If you must use the OpenAI-compatible protocol, pass cacheable content through an extension field and confirm whether the gateway documentation states support for this pass-through:

    1. payload = {
    2. "model": "<your-model-id>",
    3. "messages": messages,
    4. # Non-standard extension field; only works if the gateway explicitly supports it
    5. "cache_control": {"type": "ephemeral"},
    6. }

    Step 3: Restructure prompt layering—put stable content first and volatile content last:

    1. [Layer 1] System role and rules (almost never changes) -> set cache point
    2. [Layer 2] Knowledge base / long documents / code context (low-frequency changes) -> set cache point
    3. [Layer 3] Tool definitions (fixed order) -> keep frozen
    4. [Layer 4] Conversation history (append-only growth)
    5. [Layer 5] Current user input (different every time)

    Step 4: Control pacing and call topology. Separate high-frequency small requests from low-frequency large ones; avoid firing an extra-long-prefix request right after a long gap; in batch scenarios, prefer merging into a single request to reduce repeated prefix writes.

    5. Verification and Measurement: Confirming Gains with Data

    Do not judge by feel; build an observability loop:

    1. Check the cache-read token count and cache-write token count in the logs line by line;
    2. Compute the cache hit rate = cache-read tokens / total input tokens;
    3. Compare the “average cost per turn” curve before and after the change; normally it should be high on the first turn and low afterward;
    4. Compute the standard deviation of per-turn cost across multi-turn sessions; if single-turn cost fluctuates wildly, the prefix is unstable;
    5. Run an A/B comparison with the same prompt, switching only the protocol or cache declaration while controlling other variables.

    A minimal verification script skeleton:

    1. def run_once(client, system_text, user_text):
    2. r = client.chat.create(
    3. model=MODEL,
    4. messages=[{"role": "system", "content": system_text},
    5. {"role": "user", "content": user_text}],
    6. )
    7. u = r.usage
    8. return {
    9. "in": u.prompt_tokens,
    10. "out": u.completion_tokens,
    11. "cache_read": getattr(u, "prompt_tokens_details", None),
    12. }
    13. # Two consecutive calls with the same prefix; the second should show clear cache reads
    14. print(run_once(client, SYSTEM, "Question 1"))
    15. print(run_once(client, SYSTEM, "Question 2"))

    6. Common Pitfalls and Engineering Recommendations

    • Pitfall 1: Assuming that switching to “price first” routing will cut costs. Routing only decides upstream selection and does not change request content.
    • Pitfall 2: Putting dynamic content first. Prefixing timestamps or session IDs permanently disables caching.
    • Pitfall 3: Frequently rewriting history. Summarization saves tokens but breaks prefix continuity, so it requires a trade-off.
    • Pitfall 4: Ignoring the minimum cacheable length. Too short a prefix may not meet the caching threshold; aggregate stable content to a sufficient size.

    From an engineering standpoint, treat prompts as “versioned assets”: set change cadences for the system prompt and knowledge context, configure monitoring and alerts with a per-turn cost threshold, and encapsulate a unified cache-declaration middleware at the gateway layer to avoid inconsistent behavior across business lines. If an organization has the capability to self-host, it can also deploy a unified inference entry on a container platform to centrally manage caching policies and a cost dashboard.

    7. Conclusion

    The root of abnormal costs is usually not that the model is “expensive,” but that the caching pipeline is not connected. The recommended investigation order is: confirm log fields → verify protocol and extension-field pass-through → restructure prompt layering → build a hit-rate and cost dashboard. After completing these four steps, the input cost of repeated long-context conversations generally improves by an order of magnitude, while output quality and interaction experience remain unchanged.