Prefix Cache Optimization: How We Cut Long-Session Costs by 80%

    This article explains why costs grow faster than conversation length in long-running AI agent sessions and how prefix caching can reduce them. It covers how prefix cache matching works, six engineering practices for keeping the prompt prefix stable, a breakdown of where the savings come from, common anti-patterns, and a practical checklist for implementation. The guidance applies to teams building coding agents, multi-turn assistants, and automated operations agents on top of LLM APIs.

    1. The Problem: Why Long Sessions Get Expensive Fast

    When building terminal-style coding agents, multi-turn Q&A assistants, or automated operations agents, one pattern shows up consistently: the longer the session, the faster the bill grows, and the growth curve is noticeably steeper than the linear increase in conversation turns.

    The reason is not mysterious. Every turn resubmits the full history to the model, so input tokens accumulate with each turn while output keeps stacking on top. The result is roughly quadratic cost growth.

    One optimization path that is increasingly common in the industry relies on the prefix cache offered by model providers. For the leading portion of a request that is unrelated to other users and identical to the previous turn, the server can reuse already-computed intermediate state and charge a significantly lower rate for that segment. The common industry practice is differential pricing for cached versus uncached portions, with the cached segment typically costing only a fraction of the uncached one.

    This means the real engineering opportunity is not switching models. It is making the leading bytes of each request byte-for-byte stable.

    2. First Principles: What the Prefix Cache Actually Caches

    Prefix cache matching is very mechanical: the server compares the request token by token from the very beginning until it hits the first difference. Only the portion that matches completely before that point counts as a cache hit. Three consequences follow:

    1. Position is destiny. Identical content produces completely different results depending on where it sits. Placed in the stable region at the front, it can hit; moved further back, it may miss entirely.
    2. Any single change contaminates everything after it. One extra space in the header, one changed digit in a timestamp, one reworded tool description, and everything from that point onward must be recomputed.
    3. Appending is friendly; inserting and reordering are fatal. Adding content at the tail does not break existing hits. Inserting or reordering in the middle causes the hit rate to fall off a cliff.

    Once you understand these three points, it becomes clear why so many agent frameworks run on the same model yet differ severalfold in cost. The difference is not the model. It is how the request is assembled.

    3. Implementation: Making “Never Touch the Prefix” an Architectural Constraint

    Keeping the hit rate consistently high cannot rely on developer discipline alone. It has to be enforced as a system design constraint. The reusable engineering techniques fall into the following categories.

    3.1 Prompt Layering: Stable / Semi-Stable / Volatile

    Split request content into three segments by how often each changes, and keep them in strict order:

    1. [Stable] System role definition, safety policy, output format contract, tool list and parameter schema
    2. [Semi-stable] Project-level conventions, coding standards, directory structure summary (versioned snapshot)
    3. [Volatile] Current user input, current tool calls, tool return results

    The key discipline: the volatile region may only be appended at the tail. No writing back, no reordering, no in-place modification of prior turns.

    3.2 Push Dynamic Information to the Tail

    A common cause of collapsing hit rates is dynamic content stuffed into the header: current time, random request IDs, live feature-flag state, latency stats from the previous call, and so on. The correct approach is to extract these as tail variables, or leave only a fixed placeholder note in the stable region.

    1. # Bad: changes every turn, so the header can never hit
    2. system = f"Current time {now()}, request {uuid4()}, you are a coding assistant..."
    3. # Good: header stays constant, dynamic info moves to the tail
    4. system = "You are a coding assistant and follow the conventions below: ..."
    5. tail = f"[Runtime context] time={now()} request={request_id}"

    3.3 Snapshot Tool Descriptions and Schemas

    The tool list is the most frequently overlooked source of contamination. Frequently adding or removing tools, rewording descriptions, or changing field order all invalidate the stable region. The recommendation is to take a versioned snapshot of tool definitions: lock the same snapshot within a session, and start a new session when a change is needed rather than hot-updating.

    3.4 Compress and Deduplicate Tool Results

    Tool output is often huge and highly repetitive (directory listings, dependency trees, repeated errors). Apply structured compression before writing it into history: merge similar entries, collapse duplicate fragments, and keep only conclusions and key locating information. This reduces tokens and slows tail growth at the same time.

    3.5 Context Budget and Rolling Strategy

    Set a budget ceiling for history. When it is exceeded, use a “keep the header + summarize the middle + keep the full tail” strategy. Note that the summary must be generated once and then frozen. Regenerating it every turn continuously breaks cache hits.

    3.6 Observability: Treat Hit Rate as a First-Class Metric

    Optimization has to be measurable. Log the cached token ratio per request, the starting position of the uncached region, and the average prefix length at the gateway layer, and alert on sudden drops in hit rate. Without this instrumentation, any optimization is guesswork.

    4. Where the Savings Come From: How the 80% Reduction Is Calculated

    The gains are clearer when broken apart. Assume 50 agent loops per day with roughly 8K input tokens per turn:

    • Differential segment pricing: the cached segment typically costs about one quarter of the uncached segment. Raising the hit rate from near zero to above 95% cuts more than half of the input-side cost on its own.
    • Tail growth suppression: compressing and deduplicating tool results reduces new tokens per turn and keeps cost from accelerating with turn count.
    • Eliminated recomputation: snapshot reuse in the stable region avoids repeatedly paying for the header.
    • Output-side savings: a more stable context leads the model to produce less ineffective reasoning and fewer retries, indirectly lowering output consumption.

    Stacked together, a 60% to 80% reduction in long-session scenarios is a logical outcome rather than a marketing claim. The exact ratio depends heavily on the scenario: the more turns, the longer the context, and the more frequent the tool calls, the more pronounced the benefit. Short conversations see limited gains.

    5. Common Anti-Patterns

    • Inserting timestamps, random numbers, or session IDs into the stable region;
    • Regenerating the system prompt or reordering the tool list every turn;
    • Writing large blocks of logs into history verbatim without compression;
    • Switching models or parameters such as temperature mid-session, causing the prefix semantics and configuration to diverge;
    • Looking only at the total bill and not at the hit rate, which makes problems impossible to locate.

    6. Broader Methodology: Model Capability Plus a Custom Scheduling Layer

    A clear trend has emerged over the past two years: the combination of a general-purpose scheduling framework with a general-purpose model is giving way to a co-design of “model capability + deeply customized scheduling layer.” The reason is simple. The model’s capability ceiling is set by training, while how requests are assembled, how the cache is hit, how tool calls are passed, and how failures are retried are where engineering has real room to maneuver. Treating the scheduling layer as a first-class citizen improves cost structure and stability together.

    For teams building agents on Baidu AI Cloud model services together with general capabilities such as container platforms, logging services, and monitoring and alerting, the same methods apply: first get hit rate data at the gateway layer, then rework request assembly according to the layering and snapshot rules, and finally use compression and budget strategies to hold down tail growth.

    7. Implementation Checklist

    1. Is the header fully static, with no dynamic variables at all?
    2. Is history append-only, with no modification and no reordering?
    3. Are tool definitions version-locked and snapshotted?
    4. Are tool results compressed and deduplicated?
    5. Is instrumentation in place to capture hit rate and the start of the uncached region?
    6. Are a context budget and a frozen-summary strategy configured?
    7. Are the gains validated against real bills rather than estimates?

    Follow this order, and lower long-session costs are not a matter of luck. They are the inevitable result of how the prefix cache mechanism works.