Skip to main content

Token Caching

Qwen Code supports prompt caching (also called context caching) to significantly reduce costs and latency when working with large, repetitive contexts like codebases, documentation, and long conversations.

Overview

Prompt caching allows LLM providers to store and reuse portions of the prompt context, reducing:
  • Costs: Cached tokens are charged at a fraction of the price (typically 10% of input token costs)
  • Latency: Cached content doesn’t need to be reprocessed
  • Token usage: Significantly reduces effective prompt token consumption

Supported Providers

  • Anthropic (Claude): Full support with ephemeral caching
  • OpenAI: Support for prompt caching via cached_tokens field
  • Google (Gemini): Limited support depending on model

How It Works

Anthropic Prompt Caching

Qwen Code implements Anthropic’s prompt caching by adding cache_control markers to specific parts of the prompt.

System Instruction Caching

From packages/core/src/core/anthropicContentGenerator/converter.ts:61:
The system prompt gets cache control markers:

Tool Definition Caching

From converter.ts:123:

Message History Caching

From converter.ts:549:

OpenAI Prompt Caching

OpenAI’s prompt caching is tracked via usage metadata. From packages/core/src/core/openaiContentGenerator/converter.ts:356:
From converter.ts:891:

Token Counting

Cached tokens are tracked separately in telemetry. From packages/core/src/telemetry/types.ts:320:
From packages/core/src/telemetry/uiTelemetry.ts:189:

Configuration

Enable Caching

Caching is typically enabled automatically for supported models. The configuration happens during content generator initialization.

Anthropic Configuration

Cache Behavior

From Anthropic’s documentation:
  • Cache Duration: 5 minutes of inactivity
  • Cache Key: Based on exact prompt content
  • Minimum Size: 1024 tokens for caching to activate
  • Cost: ~10% of input token cost for cache hits

Monitoring Cache Performance

Qwen Code tracks caching effectiveness through telemetry.

Cache Hit Rate

From packages/cli/src/ui/utils/computeStats.ts:31:

Total Cached Tokens

From computeStats.ts:50:

Viewing Cache Metrics

Optimizing for Cache Performance

1. Structure Prompts for Caching

Best Practice: Place stable context first, variable content last.

2. Maximize Cache Window

Keep sessions active to maintain cache:

3. Chat Compression with Caching

From packages/core/src/services/sessionService.ts:584:
Chat compression creates stable checkpoints that can be cached effectively:

4. Memory System Integration

From packages/core/src/utils/memoryDiscovery.ts, hierarchical memory files are loaded and can benefit from caching:
Memory content is stable and benefits from caching:
This content is included in system prompt and cached across sessions.

Resume and Token Restoration

When resuming sessions, token counts are restored from checkpoints. From sessionService.ts:670:
From sessionService.ts:676:

Cost Analysis

Example Savings

Typical Anthropic pricing (Claude 3.5 Sonnet):
For a 50,000 token codebase context:

JSON Output Format

From packages/cli/src/nonInteractive/io/BaseJsonOutputAdapter.ts:212:
JSON output includes cache metrics:

Advanced Topics

Cache Invalidation

Cache is invalidated when:
  1. Content changes: Any modification to cached portions
  2. 5-minute timeout: Inactivity exceeds cache duration
  3. Context length: Cache size limits reached
  4. Model changes: Switching to different model

Multi-Turn Caching Strategy

For long conversations:

Breakpoints

Anthropic supports up to 4 cache breakpoints:
  1. End of system instructions
  2. End of tool definitions
  3. End of most recent cached message
  4. Custom location (if needed)

Troubleshooting

Low Cache Hit Rate

Problem: Cache hit rate below 50% Causes:
  1. Prompt structure changes between requests
  2. Short session duration (cache expires)
  3. Dynamic content in system prompt
  4. Context size below 1024 token minimum
Solutions:

Cache Not Activating

Problem: cached_content_token_count always 0 Causes:
  1. Context size below 1024 tokens
  2. Caching not enabled for model
  3. Provider doesn’t support caching
Check:

Unexpected Cache Misses

Problem: Cache misses despite identical prompts Causes:
  1. Whitespace differences
  2. Tool order changes
  3. Hidden formatting differences
Solution: Log exact prompt content to debug:

Source Code References

  • Anthropic caching: packages/core/src/core/anthropicContentGenerator/converter.ts:61,123,529,549
  • OpenAI caching: packages/core/src/core/openaiContentGenerator/converter.ts:356,891
  • Telemetry: packages/core/src/telemetry/types.ts:320, uiTelemetry.ts:189
  • Stats computation: packages/cli/src/ui/utils/computeStats.ts:31,50
  • Session restore: packages/core/src/services/sessionService.ts:670,676