AI & Agents

Claude Code Cache TTL: Managing Prompt Cache Lifespans, Costs, and Context Drift

Claude Code cache TTL determines how long system instructions, MCP tools, and conversation history remain in Anthropic's prompt cache before expiring. Understanding the difference between default 5-minute and configurable 1-hour lifespans prevents costly prompt rewrites and subagent context drift.

Derek Labian 16 min read Updated
Prompt cache lifespans determine whether multi-turn coding sessions receive a 90% read discount or incur repetitive 25% write surcharges.

How Prompt Cache Lifespans Dictate Claude Code Token Costs

Anthropic prompt cache entries have a default lifetime of 5 minutes that refreshes at no additional cost upon reuse, measured from the moment a request begins processing. When a developer pauses to review a code diff, consult architectural diagrams, or answer a teammate, any idle gap exceeding 5 minutes invalidates the cached prefix. The next interaction then forces a complete re-read and re-write of the entire context window. Understanding how prompt cache lifespans interact with terminal workflows separates cost-controlled agentic engineering from runaway API bills. Detailed guidelines can be verified directly in the Anthropic prompt caching documentation.

Claude Code cache TTL defines how long cached conversation prefixes, system prompts, and tool schemas remain in Anthropic's prompt cache before expiring, defaulting to 5 minutes with a configurable 1-hour option. Large language models do not store conversational state between network calls. Each message sent through Claude Code constructs an API request containing the entire interaction state: the underlying system instructions, project configuration files, connected tool schemas, preceding conversation turns, and tool outputs. Without prompt caching, the API reprocesses every token from scratch on every turn, causing input costs to scale quadratically as sessions lengthen.

Prompt caching addresses this compounding overhead by allowing Anthropic's inference engine to reuse pre-computed Key-Value attention tensors across sequential API turns. Anthropic prompt cache reads provide up to a 90% discount on input token costs compared to standard uncached input pricing, reducing latency by up to 85% for long prompts. However, writing tokens to the cache is not free. Initial cache writes incur a 25% cost premium over standard input tokens for 5-minute entries, while 1-hour cache writes cost 2x base input tokens (double the standard input token rate). Consequently, prompt caching is not a passive discount; it is a financial tradeoff that requires enough subsequent cache reads within the TTL window to amortize the initial write surcharge.

Prefix Matching and Sequential Cache Breakpoints

Anthropic implements prompt caching through strict prefix matching against pre-computed Key-Value tensors stored in server memory. When Claude Code constructs an API payload, it organizes tokens into an ordered sequence designed to maximize prefix stability:

  1. Static system prompt: core assistant instructions and built-in CLI command schemas.
  2. Model Context Protocol (MCP) schemas and connected external tool specifications.
  3. Project context: CLAUDE.md, auto-memory files, and unscoped repository rules.
  4. Conversation history: past user prompts, Claude responses, and tool execution outputs.
  5. The latest user prompt.

The inference engine evaluates this token sequence from the very first token forward. If the initial tokens match a previously compiled prefix stored in memory, Anthropic reuses the existing Key-Value states directly from hardware caches. Tokens matching the cached prefix are billed at the discounted read rate. Processing only resumes for tokens appearing after the final cache breakpoint.

Because prefix matching is byte-for-byte sequential, any modification to an early token instantly invalidates all downstream cached data. Adding an MCP tool mid-session, editing a project rule in CLAUDE.md, or switching between Claude Sonnet and Claude Opus breaks prefix alignment. When that happens, the system discards the downstream cache and executes a full cache write on the rest of the payload, charging write premiums across the entire conversation history.

Context Limits and File Handling Across Claude Interfaces

File handling rules and capacity limits vary across Anthropic's product surface. According to Anthropic's documentation for uploading files to Claude, a standard chat accepts up to 20 files at up to 500MB each. In Claude Projects, files can be up to 30MB each with no fixed file-count cap, but the total volume must fit within Claude's context window. Claude Projects has no fixed file-count cap, meaning the context window itself is the practical ceiling. Reaching that ceiling forces teams with large codebases and reference corpuses to find another path.

In Claude Code, the constraint shifts from file upload limits to token volume and cache retention. Loading reference documentation or large codebase files into the CLI session consumes prompt tokens that must either remain warm in the prompt cache or face repeated cache-write surcharges every time the session pauses beyond the cache TTL. Developers working across large repositories must manage cache lifespans intentionally or move reference documentation into external indexed storage.

Comparing 5-Minute and 1-Hour Cache TTL Settings

Claude Code provides two distinct cache durations: the standard 5-minute TTL (5m) and an extended 1-hour TTL (1h). Selecting the right setting requires balancing write surcharges against developer pause patterns and billing structures. Review the Claude Code prompt caching guide for release notes. The table below contrasts operational characteristics, cost formulas, and recommended settings for 5-minute and 1-hour cache TTL configurations:

Dimension 5-Minute TTL (5m) 1-Hour TTL (1h)
Cache Duration 5 minutes from request start 60 minutes from request start
Cache Write Cost Base input plus 25% write surcharge 2x base input tokens (double standard price)
Cache Read Cost Discounted input rate (up to 90% savings) Discounted input rate (up to 90% savings)
Break-Even Point 1 cache hit 2 cache hits
Idle Tolerance Pauses under 5 minutes Pauses up to 60 minutes
Default Application API keys, usage credits, cloud platforms Claude subscriptions (within plan usage)
CLI Settings Key "promptCacheTtl": "5m" "promptCacheTtl": "1h"
Environment Variable CLAUDE_CODE_PROMPT_CACHE_TTL=5m CLAUDE_CODE_PROMPT_CACHE_TTL=1h
Recommended Workflows Automated CI, headless scripts, rapid chat Interactive coding, complex debugging, code reviews

The cost arithmetic reveals the central tradeoff: an extended 1-hour TTL charges 2x the standard input token rate on initial cache creation.

To evaluate when the 1-hour TTL saves money versus when it increases token expenditure, consider the economic difference across two standard engineering patterns:

In an automated testing runner or headless script where Claude Code executes continuous commands with brief 30-second gaps, the default 5-minute TTL writes once with a 25% write surcharge and reads from cache across all subsequent turns. Under a 1-hour TTL, that same continuous run pays the higher one-hour write rate on turn one without gaining any retention benefit from the longer window, because no pause ever approaches the 5-minute expiration boundary. For rapid, continuous terminal sessions, the 5-minute TTL is consistently more economical.

In interactive human development, engineers pause regularly to review git diffs, run local unit tests, or consult architectural specifications. Pauses exceeding 5 minutes routinely cross the default expiration threshold. In a four-turn refactoring session with 10-minute pauses between prompts, a 5-minute cache expires after every pause:

  • Turn 1: Initial cache write establishing the prefix.
  • Turn 2 (after 10-minute pause): Cache expired. Full re-read and re-write of the context window.
  • Turn 3 (after 10-minute pause): Cache expired. Full re-read and re-write of the context window.
  • Turn 4 (after 10-minute pause): Cache expired. Full re-read and re-write of the context window.

In that interactive scenario, the session pays the full cache write penalty four separate times, recompiling the entire prompt context from scratch on every turn. Under the 1-hour TTL, the cached prefix remains warm throughout every 10-minute pause. Turn 1 establishes the cache at 2x base input tokens, while Turns 2, 3, and 4 hit the warm cache and receive the discounted read rate. The 1-hour TTL cuts total input expenditure across the session while eliminating turn latency caused by rebuilding Key-Value tensors.

Actions That Invalidate the Prompt Cache Mid-Session

Even within the active TTL window, specific actions force Claude Code to discard cached prefixes and pay full cache-write surcharges on the subsequent turn:

  • Switching models: Each model family maintains an isolated hardware cache. Running /model to switch between Claude Sonnet and Claude Opus invalidates the entire cache, even if conversation text is identical. Claude Code v2.1.238 and later prompts for confirmation only when the current cache is still warm.

  • Compacting conversation history: Running /compact replaces the message chain with a summary. The summary alters the conversation layer prefix, forcing an uncached write on the next request. Project context (CLAUDE.md) is reloaded from disk; if modified during the session, it also re-caches.

  • Adding or modifying tool definitions: Connecting a new Model Context Protocol (MCP) server or toggling plugins alters the system prompt layer, invalidating all downstream conversation tokens.

  • Changing thinking effort levels: On older models, altering reasoning effort mid-session invalidates the cache. On Opus 5.5, Sonnet 5.5, and Haiku 5.5, reasoning effort changes preserve cache validity by default when using an API key or subscription.

Fastio features

Eliminate Repetitive Prompt Cache Rewrites with Intelligent Workspaces

Keep your Claude Code prompt cache clean and fast. Offload large codebase docs, API specifications, and multi-agent context to Fast.io workspaces with built-in hybrid search over MCP. Start a 14-day free trial on any monthly plan.

How to Configure promptCacheTtl and subagentPromptCacheTtl

Claude Code evaluates prompt cache retention through two dedicated settings introduced in version 2.1.242: promptCacheTtl and subagentPromptCacheTtl. These settings give developers granular control over the main interactive conversation and background tasks.

Global configurations belong in ~/.claude/settings.json, while project-specific configurations belong in .claude/settings.json within your repository root. A complete configuration declaring 1-hour lifespans for both interactive coding and background tasks takes this shape:

{
  "promptCacheTtl": "1h",
  "subagentPromptCacheTtl": "1h"
}

Both keys strictly accept "5m" or "1h". Any other string value is ignored, causing Claude Code to fall back to default bucket rules. You can also export environment variables in your shell configuration or CI pipeline:

export CLAUDE_CODE_PROMPT_CACHE_TTL=1h
export CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL=1h

When multiple configuration mechanisms coexist, Claude Code resolves the active TTL using a strict six-tier priority ladder:

  1. FORCE_PROMPT_CACHING_5M=1: An environment variable that immediately forces the 5-minute TTL across all requests, overriding all other settings.
  2. The bucket environment variable: CLAUDE_CODE_PROMPT_CACHE_TTL for main conversations or CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL for subagents and helper tasks.
  3. The bucket configuration setting: promptCacheTtl or subagentPromptCacheTtl read from the merged project or user settings.json.
  4. Subagent frontmatter configuration: The cacheTtl property defined under the experimental block in a subagent definition file (supported in Claude Code v2.1.248 and later).
  5. ENABLE_PROMPT_CACHING_1H=1: An environment variable that requests the 1-hour TTL across all requests unless overridden by higher-priority bucket settings.
  6. The request bucket default: Resolves based on billing type. Claude subscriptions within plan limits grant 1 hour to the main conversation and 5 minutes to everything else. API keys, usage credits, and cloud platforms grant 5 minutes across the board.

Managing Subagent Delegation and Isolated Cache Buckets

A critical area often omitted in discussions of Claude Code caching is how background subagents interact with prompt cache lifespans. When Claude Code delegates a task to a subagent, such as running a test suite, researching an issue, or refactoring an isolated module, the subagent starts an entirely separate conversation with its own system prompt and tool definitions.

Because Anthropic requires strict byte-for-byte prefix identity from token zero, a subagent cannot read the parent conversation's cached prefix. The subagent must warm its own independent cache from scratch.

Furthermore, subagents fall into the "everything else" bucket. By default, subagents receive a 5-minute cache TTL regardless of whether you hold an active Claude subscription. If a parent agent dispatches a subagent to investigate an issue, waits 8 minutes while running other terminal commands, and then invokes that same subagent to apply fixes, the subagent's compiled cache has already expired. The second subagent turn pays the full cache write surcharge on its entire system prompt and tool schemas.

In multi-agent architectures, this failure mode causes compounding token churn. Setting "subagentPromptCacheTtl": "1h" in .claude/settings.json keeps subagent caches warm between intermittent delegations, ensuring that auxiliary agents reuse their compiled Key-Value states throughout extended development cycles.

Why Large Static Files Cause Repetitive Cache-Write Penalties

A frequent source of runaway token bills in Claude Code is the habit of feeding large static files directly into the prompt context. Developers routinely use @docs, file-read commands, or clipboard pastes to provide Claude with comprehensive OpenAPI specifications, database schemas, framework documentation, or system logs.

While this approach gives Claude immediate visibility, it severely damages prompt cache economics. When a 40,000-token API specification is pulled into the conversation history, it becomes an immutable part of the prompt prefix for all subsequent turns. Under the default 5-minute TTL, every pause that exceeds 5 minutes invalidates the entire cache. On the next prompt, Anthropic bills the re-read of that 40,000-token file at the full cache write rate rather than the discounted read rate, repeatedly billing write surcharges on every expired turn.

When multiple subagents are spawned, the penalty multiplies. Each subagent reads the file into its own isolated context, writing identical 40,000-token prefixes into independent cache slots. A session with four subagent invocations can easily consume hundreds of thousands of tokens purely in redundant cache-write overhead for static documentation that never changed.

Beyond financial waste, large static files trigger severe context drift. Filling the context window with reference documentation forces Claude Code to initiate early compaction. During compaction, detailed architectural instructions and nuances from earlier user prompts are condensed into lossy summaries. Critical constraints are forgotten, and the model begins producing hallucinations or contradictory code edits.

Offloading Heavy Documentation to Indexed Remote Workspaces

The architectural solution to cache churn and context drift is separating static reference knowledge from active conversational prompt context. Instead of forcing Claude Code to read large reference documents into its local context window, teams can store documentation corpuses in an intelligent, searchable workspace.

Fast.io workspaces provide organization-owned cloud storage designed for agentic teams. When documentation, API schemas, and architectural guidelines are stored in a Fast.io workspace, Intelligence Mode automatically indexes the files for hybrid search (combining full-text keyword indexing and semantic vector retrieval). Fast.io leaves every vendor's own upload limit exactly where it is; what it adds is a searchable place for the files that do not fit into prompt context.

Claude Code connects directly to the workspace using Model Context Protocol over Streamable HTTP. To connect your terminal session, run:

claude mcp add --transport http fast-io https://mcp.fast.io/mcp/code

Sign in by typing /mcp inside Claude Code to complete OAuth authorization in your browser. For project-level persistence, add the server definition to .mcp.json:

{
  "mcpServers": {
    "fast-io": {
      "type": "http",
      "url": "https://mcp.fast.io/mcp/code"
    }
  }
}

Once connected, Claude Code and its subagents no longer pull 40,000-token static files into the prompt prefix. Instead, the agent executes targeted search queries against the Fast.io MCP endpoint, retrieving only the 300-token paragraph or endpoint schema needed for the current edit. The local prompt cache stays small and fast, repetitive cache-write billing drops to zero, and context drift is avoided.

Workspaces support Cloud Sync for Google Drive, Dropbox, Box, and OneDrive (one-way or two-way, on a schedule or on demand, never continuous, live or real-time), ensuring team documentation stays updated automatically. Monthly plans start with a 14-day free trial (credit card required), with tiers spanning Starter at $9.99/mo, Business at $49.99/mo, and Enterprise at $199.99/mo.

Best Practices for Cache Retention and Multi-Agent Coordination

Maximizing prompt cache efficiency in Claude Code requires treating prompt structure as a carefully managed hardware cache. Applying these five operational practices prevents unnecessary cache invalidations and keeps token bills predictable:

  1. Match cache TTL to operational cadence: Use 1-hour TTL ("promptCacheTtl": "1h", "subagentPromptCacheTtl": "1h") on developer workstations where human interruptions, code testing, and architecture reviews create pauses between 5 and 60 minutes. Use 5-minute TTL (FORCE_PROMPT_CACHING_5M=1) in automated CI/CD runners where turns execute in rapid, unbroken succession.

  2. Freeze the prompt prefix during active tasks: Treat system prompts, MCP tool definitions, and repository guidelines as immutable while working on a feature. Avoid connecting or disconnecting MCP servers mid-task, avoid modifying plugins, and refrain from editing CLAUDE.md in the middle of a refactoring session. Configure your tooling environment before opening Claude Code.

  3. Extend subagent retention during multi-stage tasks: When designing workflows that invoke subagents intermittently, configure "subagentPromptCacheTtl": "1h". This ensures auxiliary agents retain their compiled Key-Value caches across tasks, avoiding repeated write fees on their tool definitions and instructions.

  4. Schedule compaction at logical project boundaries: Compaction wipes conversation history and rebuilds the prompt cache. Avoid running /compact in the middle of diagnosing a complex bug where recent compiler outputs and error traces are needed. Run /compact when completing a discrete milestone or switching to a new ticket.

  5. Monitor cache hit rates and token expenditure: Regularly inspect cache performance using Claude Code's /usage command (or /cost on earlier releases). For organization-wide observability, configure the OpenTelemetry exporter to stream cache read and cache creation metrics to your monitoring dashboard, identifying subagents and repositories suffering from chronic cache invalidation.

Sources

References used to verify factual claims in this guide.

  1. Anthropic prompt cache entries have a default lifetime of 5 minutes, where 5-minute cache writes cost 25% more than base input tokens and 1-hour cache writes cost 2x base input tokens.

  2. Anthropic limits Claude chat uploads to 20 files at up to 500MB each and Claude Projects files to 30MB, bounded by total context window capacity.

Frequently Asked Questions

What is the default cache TTL for Claude Code?

The default cache TTL in Claude Code depends on your billing method and the type of request. For users on API keys, usage credits, or third-party cloud providers like Amazon Bedrock and Microsoft Foundry, the default cache TTL is 5 minutes for all requests. On a paid Claude subscription operating within included plan limits, the main interactive conversation receives a 1-hour TTL, while background subagents, workflows, and compaction requests default to 5 minutes.

How do I configure promptCacheTtl in Claude Code?

You can configure promptCacheTtl by adding the key to your global settings file (~/.claude/settings.json) or your project-level settings file (.claude/settings.json). Set the value to "1h" for a 1-hour cache or "5m" for a 5-minute cache. Alternatively, export the CLAUDE_CODE_PROMPT_CACHE_TTL environment variable in your terminal session before launching Claude Code.

Why are my Claude Code token costs high after pausing work?

If you use an API key or pay-as-you-go usage credits, Claude Code defaults to a 5-minute cache TTL. When you pause work for longer than 5 minutes to test code, read documentation, or step away from your computer, the server-side prompt cache expires. Your next prompt forces Anthropic to re-read and re-write the entire conversation context from scratch, incurring a 25% cache write surcharge on the full token history.

Does switching models in Claude Code invalidate the prompt cache?

Yes. Each model family, such as Claude Sonnet and Claude Opus, maintains an independent server-side Key-Value cache. When you use the /model command to switch models mid-session, the new model cannot read the previous model's cache prefix. Claude Code must send the entire conversation history as an uncached request, re-writing the prompt cache from the first token.

How does subagentPromptCacheTtl differ from promptCacheTtl?

promptCacheTtl controls the cache duration for the primary interactive conversation, non-interactive script runs, and Agent SDK turns. subagentPromptCacheTtl specifically governs background subagents, multi-agent workflows, forks, and automated helper tasks. Because subagents use distinct system prompts and tools, they run in isolated cache buckets and default to 5 minutes unless explicitly configured.

How can I prevent large reference files from driving up prompt cache costs?

Instead of loading multi-megabyte documentation, database schemas, or API definitions directly into Claude Code context, store them in a persistent workspace like Fast.io. By indexing files with Intelligence Mode and connecting Claude Code through the remote MCP server (see the [Fast.io agent storage guide](/storage-for-agents/)), your agent can perform targeted semantic searches to pull only relevant snippets into context, preserving prompt cache space and avoiding repetitive cache-write fees.

Related Resources

Fastio features

Eliminate Repetitive Prompt Cache Rewrites with Intelligent Workspaces

Keep your Claude Code prompt cache clean and fast. Offload large codebase docs, API specifications, and multi-agent context to Fast.io workspaces with built-in hybrid search over MCP. Start a 14-day free trial on any monthly plan.