aiagent.org logo aiagent.org
⚡ Token Cost & Latency Engineering

LLM Context Caching: KV Cache Architecture

Multi-turn AI agents re-send thousands of tokens (system prompts, MCP tool definitions, repository context) on every turn. Master KV cache re-use across Gemini, Anthropic, and OpenAI to slash operational bills by up to 90% and accelerate responses by 80%.

Anthropic Claude: 90% discount on cached tokens
Google Gemini: 75% discount + explicit hourly TTLs
OpenAI: 50% automatic discount on 1024+ prefixes
01

The Turn 10 Explosion

A 10-turn coding agent loop without caching re-processes the 15,000-token system prompt and tool definitions 10 times, paying for 150,000 input tokens instead of 15,000.

02

How KV Caches Work

Transformer attention computes Key and Value matrices for each token. Providers keep the KV activations pinned in GPU HBM memory so subsequent requests bypass matrix multiplications.

03

80% TTFT Reduction

Time-to-first-token drops from 2,800ms down to 400ms because the model only computes attention over the brand new user message and the latest tool execution observation.

1. Provider Code Implementations

Production Code

Anthropic Claude — Ephemeral Breakpoints

Up to 4 cache breakpoints per request

Add cache_control: {"type": "ephemeral"} to large tools, system instructions, or documents. Claude caches blocks exceeding 1,024 tokens for 5 minutes (refreshed on each read).

import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-3-7-sonnet-20250219",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": "You are a senior codebase architect with access to our entire internal API docs...",
            # Pinned system prompt cache breakpoint
            "cache_control": {"type": "ephemeral"}
        }
    ],
    tools=[
        {
            "name": "large_mcp_toolkit",
            "description": "Enterprise tool suite",
            "input_schema": {...},
            # Tool definition cache breakpoint
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[
        {"role": "user", "content": "Analyze performance bottleneck in auth/middleware.go"}
    ]
)

# Inspect Cache Performance
usage = response.usage
print(f"Cached tokens read: {usage.cache_read_input_tokens} (Billed at 10% rate!)")
print(f"New tokens written: {usage.cache_creation_input_tokens}")

Google Gemini — Explicit Cached Content API

Configurable TTL (hours / days)

Gemini allows creating explicit, named cache objects with precise TTL durations. Ideal for indexing large PDFs or enterprise codebases (>32,768 tokens).

from google import genai
from google.genai import types

client = genai.Client()

# 1. Create durable cache for 100,000 tokens of documentation
cache = client.cached_contents.create(
    model="gemini-2.0-flash-exp",
    config=types.CreateCachedContentConfig(
        contents=[large_codebase_documents],
        system_instruction="You are an enterprise code assistant.",
        ttl="3600s" # Cache remains active for 1 hour
    )
)

# 2. Query using the cached content reference
response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    contents="Where is the rate limiter implemented?",
    config=types.GenerateContentConfig(
        cached_content=cache.name
    )
)
print("Gemini response retrieved with 75% cached discount!")

2. Golden Rules for Cache Hit Rates

Rule of Fixed Prefixes

KV caches are strict prefix trees. If even a single token at the beginning of the prompt changes, the entire downstream cache is invalidated.

Recommended Sequence:
1. Static System Instructions
2. Static Tool / MCP Definitions
3. Few-shot Demonstrations
4. Dynamic User Messages

Deadly Cache Anti-Patterns

  • Dynamic Timestamps in System Prompt: Putting Current Time: {datetime.now()} inside your system prompt invalidates the cache on every single request.
  • Changing Session UUIDs at Top: Keep conversation IDs in metadata headers, never in the prompt prefix.
  • Shuffling Tool Order: Always sort your tool schemas alphabetically by name before serialization.

Cache Performance Across Models

Provider Min. Threshold Cache Discount TTL Lifetime Cache Mechanism
Anthropic Claude 1,024 tokens 90% off 5 min (auto-refresh) Explicit Breakpoint
Google Gemini 32,768 tokens 75% off Custom (1h to days) Explicit Cache Object
OpenAI GPT-4o 1,024 tokens 50% off 5 to 10 min Automatic Prefix Match

Frequently Asked Questions

Does context caching alter model reasoning or output quality? →

No. Context caching is bit-for-bit mathematically identical to re-computing the full prompt from scratch. Attention activation tensors are identical, ensuring zero degradation in reasoning quality.

How can I monitor my production cache hit rates? →

Every response object from Claude, Gemini, and OpenAI includes token usage breakdowns. Log cache_read_input_tokens / total_input_tokens to Datadog or Prometheus. A well-architected agent fleet achieves an 85% to 92% cache hit ratio.