DEV Community

Cover image for Your Subagent Cache Expires Every 5 Minutes
Max Quimby
Max Quimby

Posted on Edited on Originally published at agentconn.com

Your Subagent Cache Expires Every 5 Minutes

Your Claude Code main session enjoys a generous 1-hour prompt cache on Max and Pro subscriptions. Every cached token reads back at one-tenth the base input price. You feel efficient. Your bills tell a different story.

📖 Read the full version with charts and embedded sources on AgentConn →

The subagents that Claude Code spawns — Explore agents, fan-out workers, review tasks — do not inherit that 1-hour window. They default to a 5-minute cache TTL. Every time one of those caches expires, Anthropic charges the full cache-write price to rebuild it: 1.25x the base input rate, compared to 0.1x for a cache hit. That is a 12.5x cost difference between a hit and a miss on the same tokens.

This is not a theoretical concern. One developer measured their subagents consuming 48% of their entire Claude Code bill while producing just 0.9% of the output tokens. Another found that fan-out subagent patterns used 2.6x to 5.9x more input tokens than doing the same work sequentially. The cache rebuild tax is a major driver of both numbers.

The core problem in one sentence: Each subagent starts its own cache, that cache expires in 5 minutes, and rebuilding it costs 12.5x more than reading from it. If your workflow spawns subagents faster than your cache can stay warm, you are paying write-rate prices on tokens you already cached.

How Prompt Caching Actually Works (and Where Subagents Break It)

Anthropic's prompt caching documentation describes a prefix-matching system. The API caches everything from the start of a request up to each cache_control breakpoint — tools, system prompt, then messages, in that order. Any change anywhere in the prefix invalidates everything after it.

The pricing is straightforward:

Token Type Cost (vs Base Input) Example: Opus 5 at $5/MTok
Uncached input 1.0x $5.00 / MTok
5-minute cache write 1.25x $6.25 / MTok
1-hour cache write 2.0x $10.00 / MTok
Cache read (hit) 0.1x $0.50 / MTok

The economics are clear: one successful cache read pays for itself immediately. The 5-minute cache write costs 1.25x and reads at 0.1x, so you break even after a single reuse. The problem is not the cache mechanism — it is what happens when subagents cannot take advantage of it.

The Subagent Cache Isolation Problem

Anthropic's engineering blog post "Lessons from Building Claude Code: Prompt Caching Is Everything" reveals how seriously Anthropic takes caching internally — they run SEV alerts when cache hit rates drop. But there is a structural issue the post does not address: subagent caches are isolated from the parent session.

Each subagent is a full separate agent loop. It carries its own system prompt (roughly 3,500-4,500 characters), its own tool schemas (24 tools), and its own conversation history. It does not inherit the parent's cache. This means:

  1. Cold start on every spawn. The first request from any subagent is always a full cache write — no prefix reuse from the parent.
  2. 5-minute TTL, not 1-hour. Even on Max/Pro subscriptions where the main session gets a 1-hour cache, subagents have been empirically measured at 5-minute TTL 100% of the time across 17 consecutive days of monitoring.
  3. Short-lived by design. Most subagents finish in under 5 minutes. By the time a follow-up task could reuse the cache, it has already expired.

Dev.to article showing empirical measurement of Claude Code sub-agent cache TTL consistently at 5 minutes for 17 straight days

View the full analysis on Dev.to →

This was confirmed in GitHub issue #99360, where users reported that the main session uses a 1-hour cache while subagents are locked to the 5-minute default. A separate issue #29966 revealed that the Agent SDK had enablePromptCaching hardcoded to false for subagents entirely.

A Claude Code team member confirmed in an HN thread that the main agent uses a 1-hour cache window, and that resuming a session after more than 1 hour means a full cache miss. The community's reaction was immediate — a separate HN discussion debated whether the TTL difference between main sessions and subagents is intentional or an oversight.

Hacker News thread where a Claude Code team member confirms the 1-hour cache window for main sessions

View the full thread on Hacker News →

The Real Cost: Measuring the Subagent Tax

The community has been auditing this aggressively. Here are the numbers that matter.

48% of the Bill, 0.9% of the Output

Developer jidonglab published a month-long audit of their Claude Code usage, parsing local transcripts to separate subagent from main-session costs. The findings:

  • Subagents: 48% of total spend for just 0.9% of output tokens
  • ~51,000 token starting context per subagent before it does any actual work (system prompt + tool schemas + CLAUDE.md + memory index + task prompt)
  • 15-subagent fan-out = ~15 million input tokens of mostly identical preamble
  • Sessions over 400K tokens made up 54% of main-session cost

Dev.to article breaking down Claude Code subagent costs — 48 percent of bill for 0.9 percent of output

View the full audit on Dev.to →

Their recommendation: cap subagents at 20 per workflow, batch 5-8 files per agent instead of one-per-file, and hand off before 400K tokens.

The Fan-Out Multiplier: 2.6x to 5.9x

Systima.ai ran controlled experiments across three Claude model families, running the same task sequentially vs. with subagent fan-out. Using a SHA-256 hash-chained audit trail for verification:

Opus (same task, same workspace):

Strategy Requests Metered Input Tokens Wall Time
Sequential 4 295,271 4m 15s
2 subagents 12 762,226 (2.6x) 8m 0s
5 subagents 15 945,187 (3.2x) 4m 45s

Fable 5 (same task):

Strategy Requests Metered Input Tokens Wall Time
Sequential 3 166,459 2m 15s
2 subagents 13 974,987 (5.9x) 7m 0s
5 subagents 15 781,293 (4.7x) 17m 0s

The two-subagent Opus lane cost roughly 5x the sequential lane on a price-weighted basis, because the subagents' cost was concentrated in premium cache writes. The sequential lane's tokens were mostly cache reads at one-tenth the input rate.

Systima.ai controlled experiment results showing subagent fan-out using 2.6 to 5.9 times more input tokens than sequential work

View the full benchmark on Systima.ai →

Worse still: a cache race was observed where subagents spawned within seconds of each other both wrote full 50K+ token prefixes with zero cache reads. The cache is per-model, but even same-model subagents launched near-simultaneously can miss each other's writes because cache entries are only available after the first response starts.

85% of Cache-Write Cost Is Overhead You Cannot Trim

A separate three-method audit found that 85% of cache_creation cost comes from Claude Code's own fixed overhead — system prompts, tool schemas, and framework context. Only 15% comes from your project files and conversation. You cannot shrink the 85%. The only lever is ensuring it gets cached and stays cached.

Dev.to analysis showing 85 percent of Claude Code cache creation cost comes from fixed overhead that cannot be trimmed

View the full analysis on Dev.to →

The Fix: Keep-Alive with max_tokens=0

Anthropic's own documentation describes a pre-warm pattern that most developers have never seen:

import anthropic

client = anthropic.Anthropic()

# Pre-warm the cache — zero output tokens billed
response = client.messages.create(
    model="claude-sonnet-4-5-20250514",
    max_tokens=0,
    system=[
        {
            "type": "text",
            "text": "Your system prompt here...",
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[
        {"role": "user", "content": "ping"}
    ]
)
# Returns: empty content array, stop_reason="max_tokens"
# Cost: cache-read price on hit, cache-write price on miss
# Output tokens billed: 0
Enter fullscreen mode Exit fullscreen mode

The key insight: a max_tokens=0 request does full prefill, writes or refreshes the KV cache, and returns immediately with zero output tokens. On a cache hit, you pay only the 0.1x read rate. On a miss, you pay the 1.25x write rate — but that write was going to happen on the next real request anyway, so the net cost of keeping the cache warm is just the read-rate refresh.

The Keep-Alive Pattern

For a 5-minute TTL, send the keep-alive request every 4.5 minutes (leaving a 30-second buffer):

import time
import threading

def keep_cache_warm(client, system_prompt, interval_seconds=270):
    """Send a max_tokens=0 request every 4.5 minutes
    to keep the cache warm."""
    def _ping():
        while True:
            try:
                client.messages.create(
                    model="claude-sonnet-4-5-20250514",
                    max_tokens=0,
                    system=[{
                        "type": "text",
                        "text": system_prompt,
                        "cache_control": {"type": "ephemeral"}
                    }],
                    messages=[
                        {"role": "user", "content": "."}
                    ]
                )
            except Exception:
                pass  # Log but don't crash the keep-alive
            time.sleep(interval_seconds)

    thread = threading.Thread(target=_ping, daemon=True)
    thread.start()
    return thread
Enter fullscreen mode Exit fullscreen mode

The cost per keep-alive ping on a cache hit: 0.1x the base input rate on the cached prefix. For a 50K-token system prompt on Opus 5 ($5/MTok base), that is $0.025 per ping, or about $0.33/hour to keep the cache warm. Compare that to a full cache rebuild at $6.25/MTok = $0.3125 per 50K tokens — the keep-alive pays for itself if it prevents even one rebuild per hour.

⚠️ The contrarian view: The Show HN thread for claude-thermos (111 points, 86 comments) sparked a heated debate. Critics argue that keeping caches warm is a tragedy of the commons — cached prefixes consume GPU memory, and if everyone runs keep-alive loops, Anthropic's inference capacity suffers for everyone. Some commenters predicted that Anthropic would change the cache policy or suspend accounts. Neither has happened, and cache reads are a paid, documented feature — but the capacity argument is worth weighing if keep-alive adoption becomes widespread.

Hacker News thread about claude-thermos cache warming tool with 111 points and heated debate about cache economics

View the full discussion on Hacker News →

Community Tools: claude-thermos and Prompt Cache Warmer

The community has not waited for an official solution.

claude-thermos

claude-thermos (114 GitHub stars) acts as a local reverse proxy that detects when your main conversation goes idle while a subagent is still running. It sends periodic keep-alive requests at cache-read cost to prevent the main session's cache from expiring. The tool claims approximately 22% cost savings, though community discussion has questioned whether this figure applies to the 5-minute or 1-hour default.

Prompt Cache Warmer

Developer Mukunda Katta built a dedicated npm package for pre-warming and maintaining Anthropic prompt caches. The tool wraps the max_tokens=0 pattern with configurable intervals and monitoring.

DIY: Check Your Own Cache Health

Before implementing any fix, audit your current state. Check the usage block in your Claude Code transcripts:

# Parse cache metrics from Claude Code transcripts
cat ~/.claude/projects/**/*.jsonl | \
  python3 -c "
import sys, json
writes = reads = inputs = 0
for line in sys.stdin:
    try:
        msg = json.loads(line)
        u = msg.get('usage', {})
        writes += u.get('cache_creation_input_tokens', 0)
        reads += u.get('cache_read_input_tokens', 0)
        inputs += u.get('input_tokens', 0)
    except: pass
total = writes + reads + inputs
print(f'Cache writes: {writes:,} ({writes/total*100:.1f}%)')
print(f'Cache reads:  {reads:,} ({reads/total*100:.1f}%)')
print(f'Uncached:     {inputs:,} ({inputs/total*100:.1f}%)')
print(f'Write/Read ratio: {writes/max(reads,1):.2f}x')
print(f'Estimated waste: writes cost {1.25/0.1:.1f}x reads')
"
Enter fullscreen mode Exit fullscreen mode

If your cache-write-to-read ratio is above 0.5, you are rebuilding caches too often. A healthy ratio for a long session is below 0.1.

The broader cost conversation has been heating up across the community. A widely-discussed HN thread about Claude Code quota exhaustion drew hundreds of comments, with many users reporting that cache-related costs were a significant and poorly-understood portion of their bills.

Hacker News thread with over 300 comments discussing Claude Code Pro Max quota exhaustion and hidden cache costs

View the full discussion on Hacker News →

Hacker News thread debating whether the prompt cache TTL is 5 minutes or 1 hour depending on billing plan

View the TTL debate on Hacker News →

Five Rules to Cut Your Subagent Cache Bill

Based on the community measurements and Anthropic's own guidance, here is the actionable checklist:

1. Audit Before You Optimize

Run the transcript parser above. Know your numbers. Most teams never look at cache metrics, which means they cannot distinguish a caching problem from a model-routing problem.

2. Fewer Agents, More Work Per Agent

The jidonglab audit showed that batching 5-8 files per subagent instead of one-per-file cut subagent spawns by 75% while getting the same work done. Each spawn avoided is a cache-write avoided. Cap your workflows at 20 subagents maximum and require an explicit justification to exceed it.

3. Pin Subagents to Cheaper Models

Systima.ai's experiments showed that pinning subagents to Haiku instead of inheriting Opus reduced metered input tokens by 37% and halved wall time. The cache write still happens, but at Haiku's $0.125/MTok write rate instead of Opus's $6.25/MTok. That is a 50x price difference on the cache overhead.

For Claude Code users, this means configuring your agent cost stack so that mechanical collection and extraction tasks run on cheaper models.

4. Implement Keep-Alive for Long Sessions

If your workflow involves a main session that idles while subagents run (the "thermos" pattern), use the max_tokens=0 keep-alive to prevent the main session's cache from expiring. The cost of one keep-alive ping is negligible compared to a full cache rebuild.

This is especially important for workflows that bill while they wait — the idle time that is already costing you money is also expiring your cache, compounding the cost.

5. Stagger Fan-Out Spawns

When launching multiple subagents, stagger the first spawn by a few seconds before launching the rest. This gives the first subagent time to write its cache prefix, allowing subsequent subagents on the same model to read from it instead of each writing their own. The Systima.ai data showed that five Opus subagents spawned within 20 seconds against a warm prefix all achieved cache reads, while two subagents spawned simultaneously both wrote full 50K+ token prefixes.

ℹ️ Quick reference — the cost math in one table:

Scenario Token Cost (Opus 5) Per 50K Tokens
Cache read (hit) $0.50/MTok $0.025
Uncached input $5.00/MTok $0.250
5-min cache write $6.25/MTok $0.3125
1-hour cache write $10.00/MTok $0.500
Miss vs hit ratio 12.5x —
Keep-alive ping (hit) $0.50/MTok $0.025

One keep-alive ping costs the same as one cache read. One missed cache costs 12.5x that. The break-even is preventing one rebuild per 12.5 pings — roughly one per hour at the 4.5-minute interval.

What Anthropic Should Fix

The 5-minute TTL on subagents while the main session gets 1 hour is a design choice, not a technical constraint. Three changes would eliminate most of the community workarounds:

  1. Cache inheritance. Let subagents read from the parent session's cache prefix. The system prompt and tool schemas are identical — there is no prefix-matching reason they should not share.
  2. Consistent TTL. If a subscription grants a 1-hour cache on the main session, subagents on the same billing plan should get the same TTL.
  3. Expose cache metrics in the dashboard. The API returns cache_creation_input_tokens and cache_read_input_tokens, but Claude Code's billing dashboard does not surface these. Without visibility, teams cannot optimize what they cannot measure.

These are feature requests already filed by the community. Until they ship, the keep-alive pattern and agent-count discipline are your best levers.

The Bottom Line

Prompt caching is not an optimization technique — it is the default billing mechanism for Claude Code. Anthropic's own engineering team treats cache-miss spikes as production incidents. The question is not whether caching matters for your bill. It is whether you know where your caches are expiring and what it costs when they do.

For teams running subagent-heavy workloads on the API's 5-minute default, the math is unforgiving: a cache miss costs 12.5x a hit, each subagent starts cold, and 89% of your bill may already be cache traffic. The keep-alive fix takes ten lines of code. The agent-count discipline takes a configuration change. Neither requires changing your model, your prompts, or your architecture.

Start with the audit. If your cache-write-to-read ratio surprises you, it is time to look at the token compression options for the overhead you can trim and the keep-alive pattern for the overhead you cannot.


Originally published at AgentConn

Top comments (1)

Collapse
 
sandscale profile image
Sandscale •

The isolated subagent cache is a useful finding. One practical follow-on: even a keep-alive will miss if the subagent's tool list or system prompt changes between spawns, because prefix cache is invalidated by any change earlier in the prompt. If you audit cache writes versus reads, it is worth checking whether fan-out agents are loading different tool subsets. For work that can wait, doing it in the parent session avoids the cold start entirely.