Claude Code Tool Result Caching in 2026: Reducing Redundant File Reads and Shell Calls in Long Agent Sessions
Disclosure: jsmanifest has a financial interest in NoCensor AI and may earn from signups through links in this article.
Most agent performance problems stem from repeated tool calls in long sessions. Here's how Claude's prompt caching actually works, what breaks a cache hit, and how to structure long Claude Code sessions so fewer tokens go to redundant file reads and shell output.
Correction (2026-10-28): an earlier version of this post described a "tool result cache", a server-side cache keyed by a hash of tool name, parameters, and result, with file reads cached until the file changed and shell output cached for the "session lifetime, typically 8-12 hours." That mechanism doesn't exist. What actually happens is Anthropic's prompt caching: the API caches a prefix of the request (tools, then system, then messages) and reuses it on the next turn instead of reprocessing it. The default cache lifetime is 5 minutes, refreshed for free every time it's read, and an optional 1-hour TTL exists at a higher write cost. There's no per-tool cache key, no "until the file changes" invalidation rule, and no manual invalidation endpoint. A tool result stays cheap only as long as it's still inside that cached prefix. This version is rewritten to describe what Claude Code actually does, checked against the official prompt-caching docs and Claude Code's prompt-caching reference.
Claude Code Tool Result Caching in 2026: Reducing Redundant File Reads and Shell Calls in Long Agent Sessions
Introduction: The Hidden Cost of Repeated Tool Calls in Long Agent Sessions
Most agent performance problems stem from the same file being read dozens of times across a multi-hour session. A typical refactoring workflow hits package.json fifteen times, tsconfig.json twelve times, and core utility files every time Claude needs to verify a type signature or import path. Each read burns tokens on the turn it happens, and once that content is in the conversation, it never leaves. Every later turn still carries it.
The problem compounds because developers treat agents as stateless: every new task triggers a fresh batch of reads even when the underlying files have not changed. Claude reads the same 200-line config file at 10:00am, 10:15am, 10:30am, and 11:00am because nothing is telling it "you already know this." The agent cannot distinguish between "I need this file because I have never seen it" and "I need this file again to confirm something I already know," so it defaults to reading.
flowchart LR
A("Agent task starts") --> B("Read package.json")
B --> C("Read tsconfig.json")
C --> D("Read utils/types.ts")
D --> E("Tokens consumed")
E --> F("Agent task ends")
F --> G("Session continues")
G --> A
style E stroke:#ef4444,fill:#450a0a,color:#fca5a5
Claude Code doesn't fix this with a tool-result cache keyed to each file read. What actually helps is Anthropic's prompt caching. Claude Code resends your entire conversation on every turn, because the model has no memory between requests, but the API caches the start of that request (the prefix) and only fully reprocesses what's new. Identical tool calls aren't deduplicated: Claude will call read_file on the same path twice if it decides it needs to, and that second call is still brand-new content that has to be processed. What's cheap is everything that came before it, including the first read, because by the time of the second read that history is already sitting inside a cached prefix.
flowchart LR
A("Turn 1: read package.json and tsconfig.json") --> B("Full prefix cached")
B --> C("Turn 2: new question, same files still in context")
C --> D("Cached prefix reused, only turn 2 is new")
D --> E("Turn 3: read utils/types.ts (new file)")
E --> F("Prefix grows, still mostly cached")
style B stroke:#34d399,fill:#0b3b2e,color:#d1fae5
style D stroke:#34d399,fill:#0b3b2e,color:#d1fae5
The practical implication is that well-structured long sessions, where the system prompt and CLAUDE.md stay stable and the agent doesn't re-read files it has already seen, get the most out of prompt caching. The failure mode is sessions that keep invalidating their own cache: switching models mid-task, toggling settings, or re-reading the same files for no reason.
Key Takeaways
- Claude Code resends the whole conversation on every turn. Prompt caching lets the API skip reprocessing the part that hasn't changed instead of running a separate cache keyed to each tool call.
- The cache is prefix-based, built in order from tool definitions, to the system prompt and CLAUDE.md, to the conversation, not keyed by individual tool name and parameters. A change anywhere in the prefix invalidates everything after it.
- The default cache lifetime is 5 minutes and resets for free every time it's read. Claude Code can request a 1-hour TTL at a higher write cost, automatically on a Claude subscription within plan usage, or by setting it yourself.
- Compaction replaces the conversation history with a summary, so it always costs a rebuild of that layer, but the system prompt and CLAUDE.md layers can stay cached if they haven't changed.
- Fork subagents, on by default in interactive sessions, inherit the parent's full conversation and prompt cache. Ordinary subagents start a separate conversation with a separate cache of their own.
How Claude Code's Prompt Caching Actually Works
Prompt caching happens at the API level, inside whichever infrastructure serves the model, not something Claude Code reads or writes directly. Every message you send becomes a brand-new API request that carries the whole conversation: the system prompt and tool definitions, your CLAUDE.md and project memory, and every prior message and tool result. New content is appended at the end, so most of each request is identical to the one before it. The API matches the start of the request (the prefix) against what it already processed, and reuses that part instead of reprocessing it. The match is exact: change anything in the prefix and everything after that point gets reprocessed.
Claude Code orders each request so the content that changes least comes first: the system prompt and tool definitions, then CLAUDE.md and project memory, then the conversation itself. A change to your messages only, a new question or a new tool result, leaves the first two layers cached. A change to the system prompt, such as an MCP server connecting or a plugin toggle that adds tool definitions, invalidates everything behind it, because all later content now sits behind a different prefix.
There's no per-file or per-command cache key. Reading /src/utils/types.ts twice in the same session doesn't make the second read a "cache hit" on that specific file. It's just new conversation content, the same as any other message. What's cached is the unchanged earlier part of the conversation, which by that point already includes the first read.
flowchart TD
A("New turn starts") --> B("Build full request: tools, system, CLAUDE.md, messages")
B --> C{"Does the prefix match what was cached last turn?"}
C -->|Yes| D("Reuse cached prefix, process only the new turn")
C -->|No| E("Reprocess the whole request, write a new cache entry")
D --> F("Response returned")
E --> F
style D stroke:#34d399,fill:#0b3b2e,color:#d1fae5
style E stroke:#fbbf24,fill:#3a2f0b,color:#fef3c7
The pricing is what makes this worth it. Per Anthropic's prompt-caching docs, cache reads are billed around a tenth of the normal input price on most models (less on a few, the exact fraction varies by model), while writing a new cache entry costs more than a plain input token: about 1.25x the base rate for a 5-minute entry, about 2x for the 1-hour option. That asymmetry is the whole mechanism: the first time a long conversation gets processed is the expensive part, and every turn after that, as long as the prefix survives, is comparatively cheap.
Reading Your Cache Hit Rate from Session Transcripts and /usage
The Anthropic API returns two real token counts on every response: cache_creation_input_tokens, what got written to the cache this turn and billed at the write rate, and cache_read_input_tokens, what got served from the cache at the cheap read rate. A high ratio of cache reads to cache creation means the cache is doing its job. If creation stays high turn after turn, something in your prefix keeps changing.
Claude Code surfaces this without needing to dig into raw API responses. Run /usage and, after the first response in a conversation, the Session block adds a Prompt cache (main) line. Claude Code's own documentation shows what that line looks like in practice:
Prompt cache (main): 14 requests · 91% of input tokens from cache · 2 misses (last 6m 10s ago, 310.2k tokens re-cached) · 1 expected rebuild (compaction or tool-result clearing) · warm (1h TTL, last activity 40s ago)That line names the request count, the percentage of input tokens served from cache, how many misses happened and when, and whether the cache is currently warm or has gone cold. When Claude Code can tell what caused the last miss, it says so directly, for example likely cause: tool definitions changed. /context gives a live breakdown of what's actually sitting in the window right now, which is the first place to look when a session feels slower than it should.
flowchart LR
A("Turn 1: full prefix processed and cached") --> B("Turn 2: prefix reused, only new content processed")
B --> C("Turn 3: same cached prefix, a bit more new content")
C --> D("/usage shows the ratio: cache reads vs cache writes")
style D stroke:#34d399,fill:#0b3b2e,color:#d1fae5
A miss doesn't come from a shell command being "non-deterministic." It comes from something changing in the prefix: you switched models or effort level, an MCP server connected, you denied a whole tool, the conversation got compacted, or you came back after the cache's TTL expired. The next section covers the full list of what actually triggers a miss.
Code Example: Reading Cache Performance from the Anthropic API
Claude Code manages prompt caching for you automatically. If you're calling the Messages API directly, for an MCP server or a custom agent built on the Claude Agent SDK, you control cache breakpoints yourself with cache_control, and you can read the real usage fields back to check how well it's working.
// api/check-cache-performance.ts
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
interface CachePerformance {
inputTokens: number;
cacheWriteTokens: number;
cacheReadTokens: number;
hitRatio: number;
}
async function sendCachedRequest(
systemPrompt: string,
userMessage: string
): Promise<CachePerformance> {
const response = await client.messages.create({
model: 'claude-sonnet-5',
max_tokens: 1024,
system: [
{
type: 'text',
text: systemPrompt,
// Marks everything up to and including this block as a cache breakpoint.
cache_control: { type: 'ephemeral' },
},
],
messages: [{ role: 'user', content: userMessage }],
});
const usage = response.usage;
const cacheWriteTokens = usage.cache_creation_input_tokens ?? 0;
const cacheReadTokens = usage.cache_read_input_tokens ?? 0;
const totalCacheable = cacheWriteTokens + cacheReadTokens;
const hitRatio = totalCacheable > 0 ? cacheReadTokens / totalCacheable : 0;
return {
inputTokens: usage.input_tokens,
cacheWriteTokens,
cacheReadTokens,
hitRatio,
};
}The ephemeral cache_control block is what marks the breakpoint. By default it gets the 5-minute lifetime that resets every time it's read; passing cache_control: { type: 'ephemeral', ttl: '1h' } asks for the longer, costlier option instead. Claude Code sets these breakpoints for you automatically across the system prompt, project memory, and conversation layers, in that order. You only need to think about cache_control directly when you're building your own agent loop on top of the Messages API, not when you're using Claude Code itself.
Combining Prompt Caching with /compact and CLAUDE.md for Maximum Efficiency
Prompt caching, conversation compaction, and CLAUDE.md or project memory serve different purposes, and it's worth being precise about which one does what.
Caching means an unchanged prefix doesn't get reprocessed from scratch on the next turn. Compaction means Claude Code replaces your message history with a shorter summary once the conversation gets large, which by design breaks the conversation layer's cache: the new, shorter history doesn't share a prefix with the old one. CLAUDE.md and project memory sit in a separate layer that's read once at session start and held in memory; editing those files mid-session doesn't invalidate anything, but the edit also doesn't take effect until the next /clear, /compact, or restart.
flowchart LR
subgraph Unstable["Churning session"]
A1("Model switches") --> B1("Full cache rebuilds") --> C1("High token cost per turn")
end
subgraph Stable["Steady session"]
A2("One model, stable CLAUDE.md") --> B2("Cache stays warm") --> C2("Low token cost per turn")
end
style C1 stroke:#ef4444,fill:#450a0a,color:#fca5a5
style C2 stroke:#34d399,fill:#0b3b2e,color:#d1fae5
Here's the part that's easy to miss: compaction's own summarization request is not fully uncached. It repeats your system prompt, tools, and the history being summarized, and if the cache is still warm, that request reads your prefix from the cache the same as any other turn. So a mid-session /compact run at a natural break costs a fraction of what the context size alone would suggest. Running it after the cache has already expired, resuming an old session after a long break, for instance, is the expensive case, because there's no cache left to read and the whole history gets reprocessed as plain input.
The practical workflow:
- Pick your model and effort level at the start of a session and stick with them. Each switch invalidates the whole cache.
- Let CLAUDE.md and project memory stay stable for the session. Edit them between sessions, not mid-task.
- Run
/compactat a natural break, between tasks, rather than waiting for the automatic pass to trigger mid-task, so you control when the one-time rebuild cost happens. - Delegate large, disposable reads to a subagent so the content never has to live in your main conversation's growing prefix at all.
Treating caching, compaction, and memory as interchangeable is the mistake. A session that compacts often but never holds a model steady still pays for a cache rebuild on every switch. A session that never compacts eventually runs out of context window regardless of how well it caches.
What a Healthy Cache Hit Rate Looks Like
There's no published benchmark for exactly how much a given Claude Code session saves from caching. It depends on the model, how stable your context stays, and how often you compact or switch models. What you can check is your own session's ratio.
The clearest real example comes from Claude Code's own documentation of the /usage output: a session fourteen requests in, reporting "91% of input tokens from cache" with two misses, one of them attributed to a likely cause. A ratio like that means the session kept its prefix stable: same model, same effort level, no mid-session plugin or MCP changes, and compaction, if it happened, landed at a natural break rather than mid-task.
flowchart LR
A("Session starts") --> B("Model and effort picked once")
B --> C("CLAUDE.md unchanged all session")
C --> D("No mid-session MCP or plugin churn")
D --> E("High cache-read ratio in /usage")
style E stroke:#34d399,fill:#0b3b2e,color:#d1fae5
The ratio drops for predictable reasons, not because a shell command happened to be "non-deterministic." Anything that rewrites the prefix costs a miss: switching models or effort level, toggling fast mode, connecting or disconnecting an MCP server when tool definitions load upfront rather than through deferred tool search, denying an entire tool, accumulating enough images that Claude Code has to drop old ones, upgrading Claude Code itself, or simply coming back to the session after the cache's TTL has expired. A write-heavy session that triggers several of these in an hour will show more misses than a read-heavy one that doesn't touch any of them, and that difference shows up in the /usage ratio, not in some separate "cacheable vs. non-cacheable" classification of individual tool calls.
The practical read on your own sessions: watch the Prompt cache (main) line, and when the ratio drops, check it against the list of what actually invalidates a cache, covered next, instead of guessing.
What Breaks a Cache Hit (and What Doesn't)
Cache invalidation in Claude Code follows a short, documented list (see the full reference), not a "deterministic vs. non-deterministic command" heuristic.
flowchart TD
A("Mid-session change") --> B{"Does it change tools, system prompt, or project memory?"}
B -->|Yes: model switch, MCP connect, plugin toggle| C("Cache invalidated, next request reprocesses from there")
B -->|No: file edit, permission mode, running a skill| D("Prefix stays cached, change applies as new conversation content")
style C stroke:#fbbf24,fill:#3a2f0b,color:#fef3c7
style D stroke:#34d399,fill:#0b3b2e,color:#d1fae5
Actions that invalidate part or all of the cache:
- Switching models with
/model. Each model has its own cache, so the next request reprocesses the whole conversation even though nothing else changed. - Changing effort level, on most models. On Opus 5.5, Sonnet 5.5, Haiku 5.5, and Fable 5.1 with an API key or a Claude subscription, effort changes keep the cache instead.
- Turning fast mode on or off, since standard speed and fast mode keep separate caches.
- Connecting or removing an MCP server, when tool definitions load upfront instead of through deferred tool search (the default on supported models, where a server change doesn't disturb anything already cached).
- Denying an entire tool by name, a bare
BashorWebFetchdeny rule, when tool search is unavailable. - Compacting the conversation. By design: the new summary doesn't share a prefix with the old history.
- Accumulating enough images or PDFs that Claude Code has to drop the oldest batch to stay under the API's per-request limits.
- Upgrading Claude Code, since a new version usually changes the system prompt or tool definitions.
- Simply waiting past the cache's TTL. Idle too long and the next request finds nothing left to reuse.
Actions that keep the cache, which is where the old "file write invalidates the cache" idea actually gets it backwards:
- Editing a file in your repository. File contents only enter the conversation when Claude reads them, so editing a file Claude already read doesn't retroactively change that earlier read. Claude Code appends a note that the file changed, and Claude re-reads it if it needs to, but the earlier turns stay cached.
- Editing CLAUDE.md mid-session. This doesn't invalidate anything, but it also doesn't apply. CLAUDE.md loads once at session start and stays in memory until the next
/clear,/compact, or restart. - Changing permission mode, output style, or running a skill or slash command. These append to the conversation rather than rewriting anything earlier in it.
/rewind. It truncates back to an earlier point in the conversation that was already cached, so the next request can hit that earlier entry directly.
The one that matters most for a long session: an external edit to a file Claude already read, someone else's commit, a formatter running in the background, isn't a "stale cache" problem, because there's no separate file cache holding that content. It's a "Claude's conversation still contains the old version and nothing is watching the filesystem for it" problem. The fix is the same either way: ask Claude to re-read the file, or structure the session so the agent, not an external process, owns the files it's working on for that duration.
Frequently Asked Questions
Does prompt caching work with the /compact command?
Compaction replaces your message history with a summary, which by design breaks the conversation layer's cache: the new, shorter history doesn't share a prefix with the old one. The system prompt and CLAUDE.md layers can still be served from cache if they haven't changed, and the summarization request itself reads your old prefix from the cache if it's still warm, so a /compact run at a natural break is cheaper than the context size alone would suggest.
How long does a cached prefix remain valid?
There's no 8-12 hour "session lifetime" and no per-tool cache. The default TTL is 5 minutes, and it resets for free every time the cache is read, so an active session effectively stays warm. Claude Code can request an optional 1-hour TTL, automatically on a Claude subscription within plan usage, or by setting it yourself, at a higher write cost, for sessions with longer idle gaps.
Can I manually invalidate a specific cache entry?
No, and the question doesn't quite apply the way it would for a per-file cache. There's no manual invalidation endpoint, and no individual "entries" to clear one at a time. What actually happens is that certain actions give the next request a different prefix (switching models, compacting, connecting an MCP server), and the old cache entry simply ages out after its TTL.
Does caching apply to tool calls in subagent sessions?
It depends on the subagent type. A regular subagent starts its own conversation with its own system prompt and tool set, so its first request doesn't read the parent's cache at all; it warms a separate cache of its own. Fork subagents are the exception: on by default in interactive sessions, they inherit the parent's full conversation and prompt cache instead of starting fresh, so the parent's cached context carries straight over.
What happens if a file Claude already read gets deleted or changed outside the session?
There's no separate cache holding that file's content independent of the conversation. Whatever Claude already read is just part of the conversation history, the same as any other message, and it stays there until the conversation is compacted or cleared. If you delete or edit the file outside Claude's own tools, the session doesn't detect that automatically, so Claude keeps reasoning from whatever it last read until it tries to touch that file again. The fix is the same as for any stale context: ask it to re-read the file, or avoid editing files outside the agent during an active session.
Conclusion: Building Sessions That Actually Get the Cache's Benefit
Prompt caching isn't something you configure per file or per shell command. It's a property of how stable your request's prefix stays from one turn to the next. The sessions that benefit most are the ones that pick a model and effort level and stick with them, keep CLAUDE.md and project memory unchanged mid-task, avoid needless MCP or plugin churn, and run /compact at natural breaks instead of waiting for an automatic pass to land mid-task.
The sessions that struggle are the ones that keep rewriting their own prefix: switching models to try something, toggling fast mode back and forth, connecting and disconnecting MCP servers, or letting a conversation sit long enough to go cold between turns. None of that is a bug in a "tool result cache," because there isn't one to break. It's the ordinary cost of an exact-prefix-match cache meeting a session that keeps changing its own prefix.
The practical takeaway is to check /usage and read the Prompt cache (main) line instead of guessing. If the ratio of cache reads to cache writes is high, the session is already getting most of what caching has to offer. If it's low, work backwards through the list of what actually invalidates a cache, model switches, effort changes, MCP and plugin changes, compaction, TTL expiry, rather than trying to make individual tool calls "cacheable." That's the mechanism that's actually there, and it's the one worth understanding.