Cache Reuse and Cost Control in Long-Running AI Agent Tasks

    Long-running agent tasks can consume far more input tokens than single-turn conversations because every iteration re-sends accumulated context to the model. This article explains how prompt caching affects cost, how to calculate cache hit rates correctly, what breaks prefix stability, and which engineering practices—stable prefixes, controlled compression, and lean subtask handoffs—help reduce overall cost. Includes a cost model, worked examples, and logging code for monitoring hit rates.

    Cache Reuse and Cost Control in Long-Running AI Agent Tasks

    Why Long-Running Tasks Need Their Own Cost Model

    The cost of a single Q&A request is easy to estimate: multiply input tokens by output tokens. Agent tasks are different. Within one session, an agent may call tools, read files, run tests, and modify code across dozens or even hundreds of iterations. Each iteration re-sends the accumulated context to the model, so total input grows with every turn—and cost grows with it.

    The cost of such tasks consists of three parts:

    1. Input tokens not served from cache;
    2. Input tokens served from cache;
    3. Output tokens generated by the model.

    Many teams only look at the price list and ignore the second part. In practice, cached tokens often make up the majority of input in long-running tasks, and their unit price largely determines the final bill. When budgeting for agent tasks, cache hit rate should be treated as a core metric.

    Understanding Prefix Caching and Hit Rate

    How Prefix Caching Works

    Most LLM inference services reuse computation for the prefix of a request. When two requests start with identical content, the server can skip recomputing that prefix and reuse the stored intermediate state (typically the KV cache). Only content after the first differing position needs to be recomputed.

    This means caching depends on prefix identity, not content similarity. If even a single character changes near the beginning of the request, everything after it loses its cached state.

    How Hit Rate Is Calculated

    Cache hit rate is usually defined as:

    Hit rate = cached input tokens / total input tokens

    For a complete task, aggregate across all requests before computing the ratio, rather than averaging per-request hit rates. Long requests have a much larger impact on total cost, and simple averaging underweights them.

    Why Hit Rate Varies Within a Task

    The main session typically keeps appending context, so its prefix stays stable and its hit rate is high. Subtasks, by contrast, each start with their own system prompt, task description, and local context. Their first request has no reusable history—this is a cold cache—so hit rate is low at startup and gradually recovers as iterations accumulate within the same subtask.

    Understanding this distinction helps you tell normal fluctuation apart from a design problem.

    Key Factors Affecting Cache Hit Rate

    Prefix Stability

    Any dynamic content in the prefix causes cache misses. Common culprits include:

    • Timestamps, random IDs, or request numbers embedded in the system prompt;
    • Tool definitions whose ordering changes between requests, e.g., unstable dictionary iteration order;
    • Reformatted history messages—changed whitespace, line endings, or field order;
    • New system prompts inserted mid-conversation, shifting everything that follows.

    The general fix: pin all static content to the front and put dynamic content at the end.

    Append-Only vs. Rewritten Context

    Append-only context adds each new message at the end and leaves history untouched. Rewritten context summarizes, compresses, or deletes history each turn, which changes the prefix.

    Each approach has trade-offs. Append-only context maximizes cache reuse, but the context grows continuously and may eventually exceed the window limit. Rewriting controls length but repeatedly invalidates the cache. A common compromise: append while under a length threshold, then perform a single consolidated compression, and keep the new prefix stable afterward.

    The Trade-offs of Splitting Into Subtasks

    Delegating work to subagents isolates context, keeps individual sessions shorter, and enables parallelism. But every subtask must rebuild its own prefix, incurring cold-start cost.

    To decide whether splitting is worthwhile, ask:

    1. Can the subtask finish independently and return only a short result?
    2. Is the background information it needs small and fixed?
    3. Does the time saved through parallelism outweigh the extra cold-cache overhead?

    If most answers are yes, splitting usually pays off. Otherwise, keeping the work in the main session is more economical.

    Cost Model and Estimation

    Once these factors are quantified, the cost of a single request can be written as:

    Total cost = (uncached input tokens × uncached price + cached input tokens × cached price + output tokens × output price) / 1,000,000

    All prices are per million tokens.

    Here is a worked example with hypothetical numbers. Suppose a task consumes 1,000,000 input tokens, of which 900,000 hit the cache, and generates 100,000 output tokens. Assume an uncached input price of 1 per million, a cached price of 0.1 per million, and an output price of 2 per million:

    • With caching: uncached input 0.1, cached input 0.09, output 0.2—total 0.39.
    • Without caching: all input billed at the uncached rate, 1.0, plus 0.2 output—total 1.2.

    A roughly threefold difference. In long-running tasks, every percentage point of hit rate meaningfully moves the bill. Note that these prices are for illustration only; actual rates depend on your provider’s official pricing.

    Engineering Recommendations

    1. Fix the Prefix Structure

    Put stable content—system prompt, tool definitions, project context—at the very front, and make serialization deterministic. For example, sort dictionary keys before serializing so the same content always produces the same string.

    2. Move Dynamic Content to the End

    Place changing content such as timestamps or task IDs at the end of the message list, or append it as a separate message—never inside the fixed prefix.

    3. Control Context Growth

    Set a length threshold. Below it, keep appending. Above it, compress earlier procedural details into a brief summary and re-stabilize the prefix after the compression point. Compress as infrequently as possible to limit cache invalidation.

    4. Have Subtasks Return Concise Results

    When a subtask finishes, return only conclusions, key file paths, and unresolved issues—not the full execution trace. This keeps the main session growing more slowly and its prefix more stable.

    5. Set Up Monitoring

    Track at least the following metrics:

    • Total input tokens, cached tokens, and output tokens per session;
    • Hit rate over iterations for each subtask;
    • The reason for each prefix change—compression, tool set changes, or system prompt edits.

    With this data, teams can pinpoint which stage is responsible for cost anomalies.

    Log Analysis Example

    The following code aggregates hit rate from request logs and estimates cost. Field names are illustrative—adapt them to your own logging format.

    1. def cache_hit_rate(records):
    2. """Aggregate across all requests instead of averaging per-request rates."""
    3. total_input = 0
    4. total_hit = 0
    5. for r in records:
    6. total_input += r["input_tokens"]
    7. total_hit += r["cached_input_tokens"]
    8. return total_hit / total_input if total_input else 0.0
    9. def estimate_cost(input_tokens, cached_tokens, output_tokens,
    10. price_miss, price_hit, price_out):
    11. """All prices are per million tokens."""
    12. miss_tokens = input_tokens - cached_tokens
    13. cost = (miss_tokens * price_miss
    14. + cached_tokens * price_hit
    15. + output_tokens * price_out)
    16. return cost / 1_000_000
    17. if __name__ == "__main__":
    18. logs = [
    19. {"input_tokens": 120_000, "cached_input_tokens": 110_000},
    20. {"input_tokens": 130_000, "cached_input_tokens": 125_000},
    21. {"input_tokens": 8_000, "cached_input_tokens": 0}, # subtask cold start
    22. ]
    23. print(f"Hit rate: {cache_hit_rate(logs):.2%}")

    Two points deserve emphasis: hit rate is computed over total volume, and cold-start requests are observed separately rather than hidden inside an overall average.

    Model Architecture and Cost

    Cost depends not only on how you call a model but also on its computational structure. A few concepts are worth knowing:

    Total vs. Active Parameters

    Sparsely activated architectures invoke only a subset of experts or parameters during each forward pass. Total parameter count can be large while the parameters actually engaged per token remain small. This balances capacity against compute overhead, but it does not change the context-reuse logic discussed above.

    Compute Efficiency and Capacity

    Common directions for improving models include optimizing attention computation, refining information flow in residual connections, and expanding embedding capacity. These changes mainly affect per-request latency and memory usage; their impact on long-running task cost must be evaluated against each provider’s pricing and caching policies.

    When evaluating models, compare task success rate, average latency, and per-task cost together—rather than unit price or any single benchmark score alone.

    Caveats

    1. Cost cannot be evaluated in isolation from quality. A cheaper model that requires multiple rounds of rework may end up costing more.
    2. Cache retention time and capacity limits are controlled by the provider and may change. In long tasks, if too much time passes between requests, a stored prefix may already have been evicted.
    3. Cached-token prices can differ substantially from uncached prices, so compressing context and reducing prefix churn is often more effective than switching models.
    4. Keep token accounting consistent. Different services may count input, output, and reasoning tokens differently—verify definitions before comparing across providers.

    Summary

    The core of cost control in long-running agent tasks is efficient context reuse. Stable prefixes, disciplined compression, lean subtask handoffs, and continuous hit-rate monitoring are the main levers for reducing cost. Model selection should be evaluated alongside these engineering measures, with final judgment based on per-task completion quality and total cost.