Prompt Caching: How It Works and How to Implement It

    This article explains how prompt caching reduces repeated computation and cost for long-context LLM requests. It covers prefix matching and cache keys, tenant isolation, declarative cache markers, asymmetric write-versus-read pricing with a break-even rule, cache lifetime and invalidation triggers, a practical engineering checklist, and guidance on which workloads benefit most.

    1. Why Long Contexts Need Caching

    In LLM application development, one cost pattern keeps recurring: every request resubmits content that is “almost unchanged” — system instructions, tool descriptions, domain knowledge, a few examples. This content often makes up the bulk of the total request length, yet it is repeated identically across calls. The inference side still has to spend compute processing the input sequence, so resubmitting means paying twice and waiting twice, and time to first token (TTFT) stretches accordingly.

    Prompt caching targets exactly this redundancy: the stable prefix of a request is kept in temporary storage on the inference side, and later requests that hit the cache skip the repeated computation and pay only for the new content. The approach was introduced by a cloud provider for its LLM inference service and has since become a common configuration option for long-context applications across the industry.

    One clarification matters: caching does not “remember answers,” it remembers intermediate computation results. It does not change model weights, it involves no training, and it offers no cross-request semantic memory.

    2. How It Works: Prefix Reuse and Cache Keys

    2.1 Prefix Consistency Is a Precondition for a Hit

    Most implementations use prefix matching: segments are compared from the start of the sequence, and only fully identical portions can be reused. Caching is therefore position-sensitive — insert a timestamp, a random ID, or a user nickname before the stable content, and everything after it is invalidated because the prefix has changed.

    The recommended request order is: stable system instructions → long-lived domain knowledge → tool and API descriptions → a few fixed examples → variable content for this session → the user’s current input.

    2.2 Cache Keys and Tenant Isolation

    The server side typically computes a cryptographic hash over cacheable content and uses it as part of the cache key, combined with a caller-identity dimension for isolation. This keeps tenants from reading each other’s cache, and it also means identical content is billed and expires separately under different accounts. Developers do not manage keys themselves, but should understand that the cache is a temporary, tenant-scoped, region-level resource — not persistent storage.

    2.3 Declarative Markers and the Minimum Cacheable Unit

    Callers mark “everything up to here is cacheable” through a cache control field in the request body (commonly expressed as a cache_control-style parameter). Most platforms enforce a minimum cacheable length, and fragments below the threshold are not cached. A schematic example:

    1. {
    2. "model": "<your-model-name>",
    3. "system": [
    4. {
    5. "type": "text",
    6. "text": "You are a senior code review assistant...(long stable instructions)",
    7. "cache_control": { "type": "ephemeral" }
    8. }
    9. ],
    10. "messages": [
    11. { "role": "user", "content": "Please review the time complexity of this implementation" }
    12. ]
    13. }

    The key point: content before the marker forms a reusable prefix; content after the marker is recomputed every time.

    3. Cost Model: Writes Are Expensive, Reads Are Cheap

    Prompt caching uses asymmetric pricing. The first write to the cache costs more than regular input (usually by a defined multiplier), while a cache hit read costs significantly less than regular input (often on the order of a 10% rate). Exact numbers vary by platform and model tier, so the official pricing page is authoritative.

    This yields a simple economic conclusion: caching only pays off when the same prefix is reused enough times. Let the write multiplier be w, the read discount be r, and the number of reuses be n; relative to no caching, break-even is roughly n > (w-1)/(1-r). If a piece of content is used only once or twice, forcing a cache in actually increases spend.

    4. Lifetime and Invalidation Scenarios

    Cache entries are short-lived, with a typical survival window measured in minutes (commonly around five minutes, with longer tiers on some platforms). The following invalidate a cache entry and trigger a rewrite:

    • Any character in the prefix changes, including spaces, line breaks, and punctuation;
    • The entry is not accessed within its lifetime and is reclaimed;
    • The hit count reaches the platform’s usage limit;
    • Switching model versions, switching regions, or changing the calling identity.

    In engineering terms, treat a cache miss as a normal path rather than an exception, and reserve cold-start cost in capacity planning.

    5. Engineering Checklist

    1. Put stable content first: move session variables, retrieval results, and time information to the end of the message.
    2. Control cache granularity: mark segments for very long knowledge bases instead of caching everything at once, which lowers the hit rate.
    3. Batch warm-up: for offline jobs, send a warm-up request before the real batch run to amortize the write cost.
    4. Observability: log cache hit status and token usage, and break dashboards down by business line.
    5. Graceful degradation: fall back to regular calls automatically when the cache is unavailable, prioritizing availability.
    6. Content governance: keep secrets and personal information out of cacheable prefixes to reduce cross-request exposure.

    6. When It Helps and When It Doesn’t

    High-return scenarios: agents with fixed system prompts, multi-turn Q&A over long documents, batch code review, structured extraction pipelines, and always-resident customer support knowledge base prefixes.

    Low-return scenarios: one-off tasks where nearly every request is new, short prompts called at high frequency, and debugging phases where the prefix changes constantly.

    7. Summary

    Prompt caching is essentially trading space for repeated computation: declarative markers delineate the stable prefix, hash keys provide tenant isolation, and asymmetric pricing steers reuse behavior. What developers actually need to master is not a parameter name but three things — how to structure requests so the prefix stays stable, how to estimate reuse counts to decide whether it is worth it, and how to keep the pipeline robust when a hit fails. On model inference services such as those offered by Baidu AI Cloud, similar capabilities are typically provided as a general category; when rolling out, use the thresholds, multipliers, and lifetimes in the official documentation as the basis for load testing and cost accounting.