Cache Reuse and Cost Control in Long-Horizon Agent Tasks
Long-horizon autonomous agents repeatedly resend accumulated context, so input-token cost and cache hit rate matter more than per-call pricing. This article explains prefix caching, the cost model, main-agent versus subagent cache behavior, engineering practices for improving cache hit rates, and quality controls for long-running agent tasks.
Cache Reuse and Cost Control in Long-Horizon Agent Tasks
1. Background: Long-Horizon Autonomous Tasks Change the Cost Model
In the past, using a large model usually meant one request containing one question and one answer, so cost could be estimated directly per call. Autonomous coding agents operate differently. Within the same session, an agent repeatedly reads files, calls tools, modifies code, and runs tests, and at every step it resends all previously accumulated context to the model. For a task with dozens of rounds of tool calls, cumulative input tokens are often dozens or even hundreds of times the final output tokens.
Therefore, when evaluating this type of task, the focus should shift from unit price to two questions: how many input tokens can hit the cache, and how many rounds are needed to complete the entire task.
A typical engineering loop usually includes five stages: research, implementation, testing, documentation, and commit. Each stage may spawn subtasks, forming a structure in which a main agent collaborates with subagents. This structure makes cost calculation much more complex than in a single-turn conversation.
2. Why Cache Hit Rate Determines the Cost of Long-Horizon Tasks
2.1 Basic Principles of Prefix Caching
Most inference services use a prefix caching mechanism. The server calculates and stores intermediate results for the continuous unchanged portion from the beginning of the request. If the next request starts with exactly the same prefix, that portion of computation can be reused directly, and billing is usually lower than for the uncached portion.
The key phrase is “continuous and unchanged from the beginning.” If even one character in the middle of the prefix changes, none of the content after it can be reused.
2.2 Cost Model
The cost of a single task can be divided into three parts:
Single-task cost = uncached input tokens × uncached unit price + cached input tokens × cached unit price + output tokens × output unit price
The following hypothetical numbers demonstrate the impact of hit rate. The unit prices and usage below are for illustration only and do not represent the pricing of any actual product.
Assume a task has 10 million cumulative input tokens, 200,000 output tokens, an uncached unit price of CNY 1.0 per million tokens, a cached unit price of CNY 0.1 per million tokens, and an output unit price of CNY 2.0 per million tokens.
- At a 97% hit rate: 300,000 tokens are uncached, and the cost is 0.3 + 0.97 + 0.4 = CNY 1.67.
- At a 50% hit rate: 5 million tokens are uncached, and the cost is 5.0 + 0.5 + 0.4 = CNY 5.9.
The difference is about 3.5 times. In long-horizon tasks where input dominates, every one-percentage-point drop in hit rate significantly increases cost. Therefore, caching strategy often determines the actual expense of a task more than simply comparing model unit prices.
2.3 Why Input Far Exceeds Output
At every round, the agent must carry the complete history, including system instructions, tool definitions, the contents of files already read, and previous tool returns. The output is usually just a code change or a tool-call instruction. The ratio of input to output continues to grow with the number of task rounds, which is also why cache optimization delivers the greatest benefit in long-horizon tasks.
3. Cache Differences Between Main Agents and Subagents
A subagent usually carries its own system prompt, task description, and independent context. Its first request cannot hit the cache of the main agent or other subagents; this is called a cold start. As a result, the hit rate of subagents is generally lower than that of the main agent. This is structurally determined and is normal.
The overall hit rate should be weighted by token count, not calculated as a simple average of each agent’s hit rate:
Overall hit rate = total cached tokens across all agents ÷ total input tokens across all agents
Example: the main agent inputs 8 million tokens with a 98% hit rate, and three subagents input a total of 2 million tokens with a 90% hit rate. The overall hit rate is (8 × 0.98 + 2 × 0.90) ÷ 10 = 96.4%. The higher the subagents’ share of tokens, the more easily the overall hit rate is pulled down.
Common ways to reduce subagent cold-start losses include:
- Have all subagents share the same basic system prompt, and place common specifications in a shared prefix.
- Control the number of subagents, creating them only for independent, long-running subtasks.
- Keep each subagent’s context small and stable, avoiding repeated injection of the full history.
- After a subtask ends, return a short summary of the conclusion to the main agent rather than the complete process record.
4. Engineering Practices for Improving Cache Hit Rate
4.1 Fix the Prefix Structure
It is recommended to organize request content in the following order: system instructions, tool definitions, project specifications, long-term memory, current task, and dynamic conversation. Content that changes more frequently should be placed later.
The following should be avoided in the prefix: timestamps, random request IDs, debugging information that differs on every request, and collection data with nondeterministic ordering. Once these appear in the prefix, all subsequent content cannot hit the cache.
4.2 Keep Context Append-Only
In long-horizon tasks, it is best to append new messages only at the end of the history and not to rewrite old messages arbitrarily. If context compression is truly necessary, compression operations should be concentrated at a few points in time, forming a new stable prefix after compression that can be reused in subsequent rounds.
Frequently rewriting history makes every round a cold start, and costs rise rapidly.
4.3 Standardize Serialization Format
Structured content such as tool definitions and configuration objects should use a fixed key order and consistent whitespace and line-break formatting. The serialized result of the same content must be byte-for-byte identical every time; otherwise, the prefix fingerprint changes and the cache is invalidated.
4.4 Detect Prefix Changes
You can calculate a fingerprint for the prefix and compare it with the previous one before each request to detect unexpected changes. Example code:
function build_request(system_prompt, tool_defs, project_rules, history, new_message):prefix = system_prompt + serialize_sorted(tool_defs) + project_rulescurrent_fp = hash(prefix)if current_fp != last_fingerprint:log_warning("Prefix changed; cache may be invalidated")last_fingerprint = current_fpreturn prefix + history + new_message
The purpose of this logic is to move cache invalidation detection from “only visible on the bill” to “visible before the request is sent.”
4.5 Track Usage by Stage
Each request should record input tokens, cached tokens, output tokens, stage, and agent ID. After aggregating by stage and agent, you can accurately identify which step has a low hit rate and optimize it accordingly.
5. Quality Assurance for Long-Horizon Tasks
Autonomous runtime alone does not indicate task quality. Long-horizon tasks require explicit quality control mechanisms:
- Milestone breakdown: split the requirements document into verifiable milestones, each with clear acceptance criteria.
- Automated test gates: a task must not enter the commit stage if tests have not passed.
- Operation logs: record every tool call and file change so the cause can be traced when problems occur.
- Human confirmation checkpoints: irreversible operations such as deleting data, pushing code, and changing permissions should still require human confirmation.
