Reducing LLM Input Costs with Prefix Caching: A Practical Guide

    This article explains why input tokens dominate inference bills in long-context, multi-turn, and AI agent applications, and how prefix caching reduces that cost. It covers the core constraints of prefix matching, a cost model that makes the cache hit rate the primary metric, four engineering factors that determine hit rate, a reusable layered prompt structure, measurement and validation practices, and the limits and risks of relying on cached prefixes. The approach is provider-neutral and applies to any inference service that supports prefix caching.

    1. Why Input Cost Is the Main Problem

    In long-context, multi-turn, and AI agent applications, input tokens usually cost far more than output tokens. System prompts, tool descriptions, retrieved knowledge snippets, and conversation history are carried on every request, and each turn is billed again. Cost therefore depends not on how much new content the business actually produces, but on how many times repeated content is billed. The core idea is not to compress wording, but to identify and reuse repeated prefixes.

    2. How Prefix Caching Lowers the Price

    Most mainstream inference services support prefix caching. When the token prefix of a request exactly matches a recent request, the server reuses the already computed intermediate state and skips the repeated computation. Those tokens are billed at a cache price significantly below the standard price, while the uncached incremental portion is still billed at the standard price. Three general constraints apply:

    • A hit requires a strictly identical prefix and uses longest common prefix matching. Any change in the middle invalidates everything after it.
    • Cached entries have a lifetime and a capacity limit. Treat the cache as volatile, not as persistent storage.
    • The server decides whether a request hits. The client can only raise the probability by constructing a stable prefix.

    3. Cost Model: Turning Hit Rate into a Computable Variable

    Let the standard input price be P and the cache price be kP (k is commonly between 0.1 and 0.25 in the industry), with a hit rate of h. The actual cost per million tokens is:

    1. Cost = h * k * P + (1 - h) * P
    2. = P * (1 - h * (1 - k))

    Using a common set of values: P = 4 CNY per million tokens, k = 0.175 (a cache price of 0.7 CNY), h = 0.9:

    1. Hit portion: 0.9 * 0.7 = 0.63 CNY
    2. Missed portion: 0.1 * 4 = 0.40 CNY
    3. Total: 1.03 CNY per million tokens, about 25.75% of the standard price

    The value of this model is that it shows the sensitivity. With k fixed, cost is roughly linearly sensitive to h. If h drops from 0.9 to 0.5, the effective unit price rises from 1.03 CNY back to 2.5 CNY. In other words, the cache hit rate is the first metric for cost control, not price negotiation.

    4. Where the Hit Rate Comes From: Four Engineering Factors

    1. Prefix stability. Timestamps, random IDs, usernames, and request trace numbers placed at the very front of the system prompt turn every request into a new prefix. Move dynamic content to the end.
    2. Content ordering. Arrange content in layers from stable to semi-stable to dynamic: global instructions and tool definitions first, knowledge snippets in the middle, conversation history and user input last.
    3. Call cadence and concurrency. Cache entries can expire during idle periods, so the first requests after a long gap in traffic will necessarily miss. Low-concurrency, long-interval workloads have a naturally lower hit rate.
    4. Routing and instance affinity. If requests are spread randomly across many backend instances, the same prefix is unlikely to land on an instance that holds the cache, which dilutes the hit rate.

    5. Implementation: A Reusable Layered Prompt Structure

    1. def build_prompt(static_block, semi_static_block, history, user_input, ts):
    2. # Order determines hit rate: the more stable, the earlier; dynamic data always goes last
    3. return (
    4. f"{static_block}\n" # System instructions and tool schema: almost never change
    5. f"{semi_static_block}\n" # Retrieved snippets: updated by version, reusable for a while
    6. f"{history}\n" # Multi-turn history: grows by appending, prefix stays stable
    7. f"[req={ts}]\n{user_input}"# Dynamic fields at the tail to avoid polluting the prefix
    8. )

    Supporting practices:

    • Maintain conversation history by appending. Do not rewrite or summarize it every turn, because rewriting truncates the common prefix.
    • Update the knowledge base by replacing versioned blocks as a whole, so that small local edits do not invalidate a long prefix.
    • Warm up very long stable prefixes by proactively sending a few regular requests before a traffic peak.
    • Bring the hit rate, the share of cached tokens, and per-request input cost into monitoring, alerting, and logging, with attribution dashboards per business line.
    • Use a message queue to smooth out peaks and keep a steady request cadence, reducing natural cache expiry caused by idle gaps.

    6. Validation: Measure First, Then Optimize

    Do not judge the effect of an optimization by intuition. Log the total input tokens and the cache hit status for each request on the client side (most APIs return input token and cached token counts in the response), then compute the measured h and the effective unit price as a baseline. After each change to the prompt structure, compare the same batch of samples and observe how h moves. If h stays significantly below the common industry range, investigate two root causes first: dynamic fields placed at the front and dispersed routing.

    7. Limits and Risks

    A cheaper cache price does not mean the context can grow without limit. The uncached portion is still billed at the standard price, and a long prefix causes cost spikes during cold starts or jitter. Putting sensitive information into a reusable prefix also requires an isolation review. A sound approach is to leave headroom in the cost model and budget against the lower bound of h rather than the upper bound.

    8. Conclusion

    Optimizing the input side is about reuse, not compression. Restructure the prompt into a stable prefix plus a dynamic tail, and combine it with cadence control, versioned knowledge blocks, and observability. Under a general-purpose caching mechanism, this brings the effective input cost down to roughly a quarter of the standard price. The method is independent of any specific vendor, transfers to any inference service that offers prefix caching, and can serve as a standard formula for capacity planning and budget reviews.