Skip to content
All patterns
Performance

Prompt caching and KV cache prefix alignment

Problem

LLM inference recomputes Key-Value (KV) activations for the entire prompt on every turn, driving up time-to-first-token (TTFT) and input token bills. Prepending dynamic elements (timestamps, session UUIDs, or un-anchored variables) breaks the shared prefix, causing a 0% KV cache hit rate and forcing full prefill recomputation.

Pattern

Structure prompts in monotonically increasing order of dynamism: static system instructions -> tool definitions -> static reference documents -> conversation history -> dynamic user query. Keep prefixes bit-identical across requests and avoid dynamic variables before the cache breakpoint.

Implementation
prompt_caching.py
from anthropic import Anthropic

client = Anthropic()

# Prefix discipline: static instructions and docs come first, marked for caching.
# Dynamic elements (timestamps, user inputs) are kept strictly at the very end.
STATIC_SYSTEM_PROMPT = """You are an enterprise technical support specialist for CloudFlow.
Follow these operating rules strictly:
1. Base answers only on provided technical documentation.
2. Emit structured error codes when triage procedures fail.
3. Never run shell commands without confirming blast radius."""

SYSTEM_KNOWLEDGE_BASE = """[CloudFlow Docs v3.4]
- Error 502: Upstream proxy connection timeout. Check ingress controller logs.
- Error 504: Gateway timeout. Validate database connection pool exhaustion.
- Failover procedure: Run active health check on standby region before routing traffic.
... (detailed system docs exceeding provider 1024 token minimum) ..."""

def call_support_agent(session_history: list[dict], user_query: str) -> str:
    response = client.messages.create(
        model="<large-model>",  # Model names change often; check your provider's model list (as of 28 October 2026). Replace <...-model> with a model id from that list.
        max_tokens=1024,
        system=[
            {"type": "text", "text": STATIC_SYSTEM_PROMPT},
            {
                "type": "text",
                "text": SYSTEM_KNOWLEDGE_BASE,
                # Set cache breakpoint on the static prefix (renewed on hit)
                "cache_control": {"type": "ephemeral"},
            },
        ],
        # Conversation history and dynamic query append strictly AFTER the cached prefix
        messages=[
            *session_history,
            {"role": "user", "content": user_query},
        ],
    )

    # Telemetry: track cache efficiency
    usage = response.usage
    cache_read = getattr(usage, "cache_read_input_tokens", 0)
    cache_write = getattr(usage, "cache_creation_input_tokens", 0)
    print(f"Tokens - Input: {usage.input_tokens}, Cache Read: {cache_read}, Cache Write: {cache_write}")

    return response.content[0].text
Trade-offs
  • Cache reads save 80-90% on input token costs and cut TTFT substantially
  • First invocation incurs a small write-overhead latency penalty to populate the KV cache
  • Cache invalidation occurs if even a single character changes within the prefix
  • Providers maintain ephemeral cache TTLs (typically 5 minutes without hits)
Production checklist
  • Order prompt components strictly: static instructions -> tool schemas -> static docs -> history -> query
  • Remove dynamic timestamps, request IDs, and random seeds from cached prefixes
  • Verify prompt length meets provider minimum cacheable token count (e.g. 1,024 tokens)
  • Log and monitor cache_read_input_tokens vs cache_creation_input_tokens in telemetry
  • Implement keep-alive pings for critical low-frequency workloads to prevent cache eviction