Stable Prefix Caching for Long-Running Coding Agents
Long-running coding agents do not finish with a single question and answer. They read repositories, call tools, revise code after errors, and resend system constraints, tool definitions, project rules, conversation history, and tool outputs on every turn. Prefix caching can reduce the cost of the stable beginning of each request, but only if the request is built so that the beginning stays stable across turns. This article explains what prefix caches match, why coding agents often break them, how to layer context, when to trim and summarize, how tool output shape affects cache lifetime, and how to observe hit and miss input instead of tuning by feel.
Long-running coding agents are not “ask once, answer once” systems. They read repositories, call tools, revise code based on errors, and resend system constraints, tool definitions, project rules, conversation history, and tool outputs to the model on every turn. The only genuinely new input is often the latest step, while a large earlier portion is billed again each time. If the model service provides context caching for identical prefixes, a stable opening can be billed at the cached price and only the changing suffix at the full input price. Cache-aware context design is about keeping that opening as invariant as possible across turns.
What Prefix Caching Matches
Context caching usually performs prefix matching on the token sequence at the beginning of a request. When several consecutive requests share the same opening, that prefix may hit an existing cache, and billing covers only the unmatched portion. Matching generally requires byte-level or token-level consistency. An extra space, two messages swapped, or the current time inserted into the system prompt can invalidate the reusable prefix from a certain point onward. The result is not “slightly more expensive.” Everything after the divergence point is treated as a miss.
It helps to distinguish three kinds of content. The first is the stable prefix that should not change even across sessions, including role definition, safety boundaries, tool schemas, and output format. The second is history that only grows within a session, including user goals, confirmed decisions, and tool results that have not expired. The third is the suffix that necessarily changes every turn, such as the latest observation, the current plan, and newly produced patches. The design goal is to push change toward the end of the sequence rather than letting it leak back into the prefix.
A simple accounting model is that cache hit rate equals hit input tokens divided by the sum of hit and miss input tokens. A large numerator and a small miss portion in the denominator make long sessions cheaper. The ratio itself is not proof of capability; it only shows whether the prefix has been preserved. If history is rewritten every turn, the numerator stays at a very short common head, while the miss portion grows linearly or even superlinearly with the conversation.
Why Coding Agents Break Caches So Easily
Ordinary chat often has a fixed system prompt and appended user messages, so it naturally approaches a stable prefix. Coding agents are the opposite: their context is assembled by software.
Common breakage points include reordering history by “relevance” each turn and inserting old tool results into new positions; writing project rules or error summaries into the system prompt and rewriting them as steps change; adding timestamps, request IDs, random seeds, or “step N” high-entropy fields to the prefix; dynamically adding or removing tools so tool schemas shift as a whole; and replacing early messages with a new summary during compression, which rewrites an entire segment starting from some message.
Each practice looks reasonable in isolation. Reordering puts useful information where attention may be more sensitive. Timestamps help logging. Dynamic tools save window space. Summaries prevent context overflow. But for prefix caching, they share the same cost: the stable prefix is cut short. Once the cost model bills unmatched input, the bill for long tasks concentrates on repeated old context rather than on genuinely new code and logs.
Cache-Aware Context Layering
Think of a request as four layers and define a change policy for each.
The stable layer holds system instructions and tool schemas. The system prompt should remain verbatim within a version and should not embed a clock, a temporary user nickname suffix, or current-turn state. Tool schemas should be serialized in an ordered, deterministic way: fixed field order, description text that does not change with call results. If tools must be added or removed at runtime, treat it as an explicit schema version switch rather than silently changing schemas within the same cache generation. After the switch, accept that the prefix is invalidated at the schema point. Such switches should be rare and clear, for example when a task moves from read-only reconnaissance to modification allowed, not when a parameter description is tweaked every step.
The session layer is append-only. User goals, assistant plans, tool calls, and tool results follow the stable layer in chronological order. Messages already written should not be rewritten, reordered, or backfilled with later conclusions. When a correction is needed, append a correction instead of editing the original sentence. In this way, the entire prefix of the previous request remains the prefix of the next request.
The working layer holds the current turn’s delta: the action to execute, the diagnostic just returned, the diff awaiting confirmation. It changes by nature, so placing it at the tail does not break earlier hits.
The observation layer should not enter the model prefix. Request identifiers, latency, cache hit markers, and internal routing information belong in side logs. Putting troubleshooting fields into the system prompt is one of the most common and most easily overlooked cache killers.
The assembly order can be kept as follows:
request = stable_system + stable_tool_schema+ append_only_history+ latest_delta
The first two items keep the same hash across turns, the third only grows at the tail, and the fourth is replaced every turn. Use canonical serialization in the implementation to avoid unstable dictionary order, floating-point format changes, or whitespace differences that “look the same” but produce different tokens.
When the Window Fills: Trim First, Summarize Later
The context window is finite, and pure append-only history will eventually hit the limit. Compressing all history into a new summary immediately is equivalent to replacing the old prefix with text that has never appeared before, invalidating the cache from the summary start and paying for the summary itself as new long input. A safer order is restrained, layered reclamation.
First handle the oldest tool results with the lowest marginal value for later reasoning. Large read-only outputs—complete directory listings, repeated test logs, file contents already covered by later conclusions—can be truncated first: keep the tool name, arguments, status code, error summary, and a few key snippets, and delete repeated bodies. Make this trimming happen inside a single old message where possible, and keep the message count and surrounding boundaries unchanged. If the server cache granularity is the whole prefix, changing one message still invalidates the suffix from that message onward, but the invalidation point can be pushed far back into old history, and later effective history still has a chance to accumulate hits again in subsequent turns. Trimming should be deterministic: the same old result should always produce the same truncated text, avoiding back-and-forth rewrites.
Second, use discard-style pruning: remove an entire tool output that is fully expired and whose conclusion has already been written into a later message. Removal shifts the positions of all messages after it, so its cache impact is greater than in-place truncation. Use it only for early results confirmed to have no reference value, and batch it where possible instead of deleting one item per turn and pushing the invalidation point further back each time.
Only then consider summary compression. The trigger should be the context approaching a threshold, not “it grew a little.” The summary should be short and explicitly mark the interval it covers to avoid contradicting uncompressed history. After compression, treat the summary as a new stable starting point and resume append-only operation. Do not repeatedly revise summary wording in the next few turns, or the new prefix will also fail to stabilize. Compression frequency and the number of recent original turns to retain should be written as explicit policy, not left to the model to decide what to delete on the fly.
This can be summarized as: do not change the prefix unless necessary; when space must be reclaimed, start with the oldest tool bodies; only when the window is still insufficient should history be rewritten and a cache rebuild accepted.
Tool Result Shape Determines Cache Lifetime
The token hogs in coding tasks are usually not dialogue but tool returns. A recursive directory listing or a full build log can occupy tens of thousands of tokens and be sent almost unchanged on the next turn. Caching can lower the unit price of repeated sending, but it cannot eliminate window pressure or correct a design that keeps useless bodies in the prefix.
A better tool contract is to return structured, truncatable results; provide a summary and locators by default, and fetch full text on demand; return stable bodies for the same query when the result has not changed, avoiding timestamps, random order, and progress bars that turn every output into new text. File reads should include path and range rather than dumping unbounded content. Test output should prioritize failed cases and the first error stack. Even before a cache hit, the miss volume is smaller; once a hit occurs, stable old results can remain in the reusable prefix.
The assistant side also needs restraint. Rewriting the entire plan into history every step bloats the tail and tempts implementers to “clean up” old plans. A better approach is to append short plans and mark completed items in later messages rather than overwriting old messages.
How to Observe Instead of Tuning by Feel
Whether a caching strategy works depends on the input split, not just total tokens. At minimum, record the stable prefix length, appended history length, and current-turn delta length for each turn, along with the hit and miss input amounts returned by the server if the API provides them. Hit rate is hit divided by hit plus miss. Also watch the invalidation point: if miss length suddenly approaches the entire history, the middle of the prefix was rewritten rather than the tail growing normally.
Comparison experiments should fix the task and model and change only the assembly strategy: one group allows reordering and immediate summarization, and another keeps the prefix stable and delays compression. Compare cumulative miss input, the number of threshold hits, and task completion quality, not single-turn latency. Quality must not be sacrificed for caching. If an error still being referenced is trimmed away, later reasoning may hallucinate or call tools repeatedly, and the saved input will be consumed by extra turns.
Also accept that caching is not always available. Cold starts, schema version switches, a single oversized item above the cache threshold, and server eviction can all cause sudden drops in hits. The strategy should remain correct under misses, just more expensive, rather than depending on hits to complete.
Boundaries with Cloud Engineering
If inference calls go through a cloud model service, cache hit rules, billing treatment, and minimum cacheable length are subject to that service’s public documentation. The client should not assume undocumented discounts or a fixed hit rate. What the client controls is whether the request bytes are stable. Logs, monitoring, and object storage are suitable for holding trimmed full text and debugging information: keep indexes in the model context, keep raw logs in the logging service or object storage, and retrieve them by range when needed. In this way, window limits, caching, and auditing can all hold at the same time.
For example, a cloud platform such as Baidu AI Cloud generally provides model invocation, logging, and object storage capabilities. These can be used to store full tool outputs, record per-turn hit and miss splits, and support cost observation. Whether context caching is enabled and how it is priced must be checked against the documentation for the model service actually used; a sample ratio from one run should not be treated as a commitment.
Practical Checklist
Version system prompts and tool schemas, serialize them stably, and do not write time or request identifiers into them. Keep history append-only, including corrections. Have tools return truncatable structures by default; trim old results in place before deleting them. Summarize only near the window threshold, and once a summary is written, do not polish it. Record hit and miss input each turn and locate the invalidation point. Keep full text and troubleshooting data outside the context in storage and logs.
Prefix caching is not a score to “max out.” It is a constraint on request construction: put change at the tail, start reclamation with the oldest low-value bodies, and treat rewriting history as a last resort. Coding agents implemented under this constraint have a chance to make long-task input cost grow with new information rather than repeatedly billing for all history.
