Skip to content
AI Engineering #prompt-caching#anthropic#openai#vllm#llm-optimization#cost-reduction

LLM Prompt Caching: Anthropic vs OpenAI vs vLLM Prefix Cache

S

S L Manikanta

Dec 1, 2026 • 9 min read

Key Takeaways

  • Prompt caching cuts multi-turn agent input token costs by 50% to 90% and reduces Time-To-First-Token (TTFT) by reusing precomputed KV states.
  • Anthropic requires explicit cache_control breakpoints (minimum 1,024 tokens), whereas OpenAI and vLLM Automatic Prefix Caching (APC) cache prefixes automatically.
  • Dynamic timestamps, unsorted JSON tool schemas, and per-request UUIDs in system prompts silently invalidate 100% of prefix cache hits.
  • Move all volatile context (current time, user session ID, retrieved RAG chunks) to the final user message to lock in 90%+ cache hit rates.

Quick Solution: Deterministic Prefix Layout + Cache Breakpoints

Multi-turn AI agents waste 75% to 90% of their input token budget re-evaluating identical system prompts, MCP tool definitions, and shared codebase context on every step. You can eliminate this redundant prefill compute immediately by enforcing a strict static-first message layout and attaching explicit cache_control breakpoints (anthropic>=0.49.0) or relying on automatic prefix matching (openai>=1.68.0, vllm>=0.11.0).

Install the pinned SDKs:

pip install "anthropic==0.49.0" "openai==1.68.0" "pydantic>=2.10.0"

Place all static instructions and sorted tool schemas before any volatile user or timestamp data:

# BAD: Dynamic timestamp in system prompt invalidates 100% of prefix cache
# system = f"Current UTC time: {datetime.now(timezone.utc).isoformat()}\n" + STATIC_INSTRUCTIONS

# GOOD: Static system + sorted tools cached; dynamic timestamp moved to user turn
system_blocks = [
    {
        "type": "text",
        "text": STATIC_SYSTEM_INSTRUCTIONS,  # >= 1,024 tokens
        "cache_control": {"type": "ephemeral"},
    }
]
flowchart TD
    Req["Incoming Agent Turn"] --> Prefix["1. Static System Prompt + Sorted Tool Schemas (Immutable)"]
    Prefix --> Docs["2. Shared Repo / Document Context (Session-Scoped)"]
    Docs --> BP["Cache Breakpoint / Prefix Boundary"]
    BP --> Volatile["3. Current Timestamp + Latest Tool Output + User Query (Volatile)"]
    Volatile --> Router{"Inference Provider"}
    Router -->|"Anthropic API"| Ant["cache_read_input_tokens (-90% cost)"]
    Router -->|"OpenAI API"| OAI["cached_tokens (-50% to -75% cost)"]
    Router -->|"vLLM (--enable-prefix-caching)"| VLLM["KV Block Reuse (-70% TTFT)"]

Why Multi-Turn Agents Silently Miss the Prompt Cache

LLM prompt caching is an inference optimization that persists the computed Key-Value (KV) attention tensors of an identical token prefix across requests, skipping redundant prefill matrix multiplication on subsequent turns.

Even when engineers enable caching flags, production telemetry often shows cache_read_input_tokens: 0. Three silent bugs cause almost every cache miss:

  1. Volatile System Prompts: Injecting Current time: 2026-12-01T22:15:03Z or a trace ID at the top of the system prompt changes token 5, which invalidates every subsequent token in the 10,000-token prompt.
  2. Non-Deterministic Tool Schema Serialization: When MCP servers or Python dicts emit tool parameters in arbitrary insertion order, json.dumps() produces different token sequences across worker restarts. Always sort tool names and JSON keys deterministically.
  3. Load Balancer Round-Robin Without Affinity (Self-Hosted vLLM): On multi-replica vLLM clusters, round-robin routing sends turn 1 to GPU Replica A and turn 2 to GPU Replica B, yielding a 0% KV hit rate. Use consistent hashing on session_id or conversation_id at your ingress proxy.

Head-to-Head Comparison: Anthropic vs OpenAI vs vLLM APC

The matrix below compares prefix caching behavior across frontier APIs and self-hosted vllm==0.11.0 (tested with a 12,000-token system + tool + codebase prefix, 5-turn agent loop, Qwen2.5-32B-Instruct-AWQ on 1x H100 80GB for vLLM).

Feature / MetricAnthropic (Claude 3.7 / 4.x)OpenAI (GPT-4o / o3 / GPT-4.1)Self-Hosted vLLM (--enable-prefix-caching)
Activation ModeExplicit cache_control breakpointsAutomatic (zero config)Automatic (--enable-prefix-caching)
Minimum Prefix Threshold1,024 tokens (Sonnet/Opus), 2,048 (Haiku)1,024 tokens (128-token step blocks)16 or 32 tokens (PagedAttention block size)
Cache Write Surcharge+25% (5m TTL) / +100% (1h TTL)0% (Free)0% (Free)
Cache Read Discount90% off input token price50% to 75% off input token price100% prefill FLOP savings on hit blocks
Default Cache TTL5 minutes (refreshed on hit) or 1 hour5 to 10 minutes (up to 1h off-peak)Until HBM KV eviction (LRU policy)
12k-Token Turn 2 TTFT~420 ms (vs ~1,850 ms uncached)~380 ms (vs ~1,600 ms uncached)68 ms (vs 490 ms uncached on H100)

For self-hosted clusters experiencing high prefill load even with prefix caching, pair APC with vLLM disaggregated prefill and decode using NIXL or tune block sizing via our PagedAttention KV cache fragmentation guide.


Production Prompt Cache Client & Hit-Rate Telemetry

The runnable Python script below wraps both anthropic and openai clients with:

  • Deterministic JSON serialization (sort_keys=True) for tool definitions so schemas never drift.
  • Automatic placement of cache_control breakpoints on the static system prompt and tool array for Anthropic.
  • Real-time cache hit ratio calculation (cached_tokens / total_input_tokens) with structured error handling.

Save as prompt_cache_benchmark.py:

import json
import logging
import os
import time
from datetime import datetime, timezone
from typing import Any

import anthropic
import openai
from pydantic import BaseModel

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("prompt-cache")


class CacheMetrics(BaseModel):
    provider: str
    turn: int
    total_input_tokens: int
    cached_read_tokens: int
    cache_write_tokens: int
    hit_rate_pct: float
    latency_ms: float


# Generate a deterministic >1,200-token system + policy block
STATIC_SYSTEM_PROMPT = (
    "You are a Principal Reliability Engineer auditing Kubernetes and Terraform manifests.\n"
    "Follow these strict production compliance rules:\n"
    + "\n".join(
        f"Rule {i:03d}: Verify resource limits, non-root securityContext, and immutable image digests "
        f"for workload tier {i % 5} before approving deployment."
        for i in range(1, 65)
    )
)


def canonicalize_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Sort tools and nested schema keys deterministically to prevent silent cache misses."""
    serialized = [json.loads(json.dumps(tool, sort_keys=True)) for tool in tools]
    return sorted(serialized, key=lambda item: item.get("name", item.get("function", {}).get("name", "")))


def run_anthropic_cached_turn(
    client: anthropic.Anthropic,
    tools: list[dict[str, Any]],
    user_query: str,
    turn: int,
) -> CacheMetrics:
    sorted_tools = canonicalize_tools(tools)
    if sorted_tools:
        sorted_tools[-1] = {**sorted_tools[-1], "cache_control": {"type": "ephemeral"}}

    timestamp_utc = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    start = time.perf_counter()

    try:
        resp = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=128,
            temperature=0.0,
            system=[
                {
                    "type": "text",
                    "text": STATIC_SYSTEM_PROMPT,
                    "cache_control": {"type": "ephemeral"},
                }
            ],
            tools=sorted_tools,
            messages=[
                {
                    "role": "user",
                    "content": f"[Request UTC: {timestamp_utc}]\n{user_query}",
                }
            ],
        )
    except anthropic.APIError as exc:
        logger.error("Anthropic API error on turn %d: %s", turn, exc)
        raise

    latency_ms = (time.perf_counter() - start) * 1000.0
    usage = resp.usage
    cache_read = getattr(usage, "cache_read_input_tokens", 0) or 0
    cache_write = getattr(usage, "cache_creation_input_tokens", 0) or 0
    total_in = usage.input_tokens + cache_read + cache_write
    hit_rate = (cache_read / total_in * 100.0) if total_in > 0 else 0.0

    return CacheMetrics(
        provider="anthropic",
        turn=turn,
        total_input_tokens=total_in,
        cached_read_tokens=cache_read,
        cache_write_tokens=cache_write,
        hit_rate_pct=round(hit_rate, 2),
        latency_ms=round(latency_ms, 1),
    )


def run_openai_cached_turn(
    client: openai.OpenAI,
    user_query: str,
    turn: int,
    base_url_label: str = "openai",
) -> CacheMetrics:
    timestamp_utc = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    start = time.perf_counter()

    try:
        resp = client.chat.completions.create(
            model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"),
            max_tokens=128,
            temperature=0.0,
            messages=[
                {"role": "system", "content": STATIC_SYSTEM_PROMPT},
                {"role": "user", "content": f"[Request UTC: {timestamp_utc}]\n{user_query}"},
            ],
        )
    except openai.OpenAIError as exc:
        logger.error("%s API error on turn %d: %s", base_url_label, turn, exc)
        raise

    latency_ms = (time.perf_counter() - start) * 1000.0
    usage = resp.usage
    if usage is None:
        raise RuntimeError("Missing usage payload in chat completion response")

    details = getattr(usage, "prompt_tokens_details", None)
    cached_tokens = getattr(details, "cached_tokens", 0) or 0
    total_in = usage.prompt_tokens
    hit_rate = (cached_tokens / total_in * 100.0) if total_in > 0 else 0.0

    return CacheMetrics(
        provider=base_url_label,
        turn=turn,
        total_input_tokens=total_in,
        cached_read_tokens=cached_tokens,
        cache_write_tokens=0,
        hit_rate_pct=round(hit_rate, 2),
        latency_ms=round(latency_ms, 1),
    )


def main() -> None:
    sample_tools = [
        {
            "name": "check_k8s_manifest",
            "description": "Validate Kubernetes deployment YAML against security policy.",
            "input_schema": {
                "type": "object",
                "properties": {"namespace": {"type": "string"}, "yaml_body": {"type": "string"}},
                "required": ["namespace", "yaml_body"],
            },
        }
    ]

    queries = [
        "Audit Deployment api-gateway in namespace prod for root user violations.",
        "Audit Deployment worker-billing in namespace prod for missing memory limits.",
    ]

    if os.getenv("ANTHROPIC_API_KEY"):
        ant_client = anthropic.Anthropic()
        for idx, query in enumerate(queries, start=1):
            metrics = run_anthropic_cached_turn(ant_client, sample_tools, query, idx)
            print(metrics.model_dump_json())

    if os.getenv("OPENAI_API_KEY"):
        oai_client = openai.OpenAI()
        for idx, query in enumerate(queries, start=1):
            metrics = run_openai_cached_turn(oai_client, query, idx, "openai")
            print(metrics.model_dump_json())

    if not os.getenv("ANTHROPIC_API_KEY") and not os.getenv("OPENAI_API_KEY"):
        logger.info("Set ANTHROPIC_API_KEY or OPENAI_API_KEY (or point OPENAI_BASE_URL to vLLM) to run.")


if __name__ == "__main__":
    main()

Architectural Guardrails for Multi-Tenant & Agentic Pipelines

  1. Never Cache Raw User PII Across Tenants: In shared self-hosted vLLM deployments, prefix hashes are computed over exact token IDs. Always keep tenant-specific context after your shared system prompt, and redact sensitive fields before external API calls with PriviPaste.
  2. Pair Caching with Structured Output Enforcement: Static JSON schemas placed in the cached prefix pair cleanly with OpenAI-compatible Pydantic structured outputs and SGLang Jump-Forward JSON decoding.
  3. Persist Multi-Turn Checkpoints Without Mutating History: In LangGraph async Postgres checkpointing and hybrid agents like StoxFlow, append new tool messages to the end of messages rather than editing or summarizing earlier turns mid-loop, which preserves 90%+ prefix hits across 10+ step agent runs.

Frequently Asked Questions

What is the minimum token length for LLM prompt caching?

OpenAI activates automatic prompt caching at 1,024 tokens and bills cached tokens in 128-token increments. Anthropic requires a minimum of 1,024 tokens per cache breakpoint on Claude Sonnet and Opus models (2,048 tokens on Haiku). vLLM APC caches fixed 16-token or 32-token KV blocks immediately.

Why am I getting zero cache_read_input_tokens in Anthropic or OpenAI?

The most common cause is a non-deterministic prefix before your cache breakpoint. Injecting datetime.utcnow(), unsorted dictionary keys in MCP tool definitions, or changing few-shot examples on every turn shifts token boundaries and forces a full cache miss.

Does Anthropic prompt caching cost extra on cache writes?

Yes. Anthropic charges a 25% surcharge on the first write (cache_creation_input_tokens) for the standard 5-minute TTL, then discounts subsequent reads (cache_read_input_tokens) by 90%. If a prefix is read at least twice within 5 minutes, you save money.

How do you enable Automatic Prefix Caching in vLLM?

Pass —enable-prefix-caching to vllm serve (enabled by default in vLLM V1). Pair it with consistent request routing (such as session-affinity hashing at your load balancer) so multi-turn conversations land on the same GPU replica.


Production Checklist & Verification

  1. Audit your system prompt for dynamic variables: Search your prompt templates for datetime, uuid, random, and request IDs, and relocate them to the final user message.
  2. Canonicalize MCP and function tool schemas: Sort tools alphabetically by name and serialize JSON schemas with sort_keys=True at startup.
  3. Alert on cache hit-rate regressions: Log cached_read_tokens / total_input_tokens per agent run in Prometheus or OpenTelemetry and alert if multi-turn hit rates drop below 60%.
  4. Enable session affinity on vLLM replicas: Configure NGINX or Envoy consistent hashing on X-Session-Id when running multiple --enable-prefix-caching workers.
INTERACTIVE TOOL

Size Your GPU VRAM & KV Cache Footprint

Test Llama 3, DeepSeek R1, and Qwen quantization & concurrency setups across vLLM, SGLang, and Ollama.

Open GPU VRAM Calculator →
✉ Newsletter

Want to build production-ready AI?

Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.

S

Written by S L Manikanta

AI Engineer specializing in agentic workflows, multi-step LLM validation pipelines, and secure cloud environments. Sharing practical lessons from building software.

Related Articles

AI Engineering
Streaming Structured JSON Outputs with Pydantic and vLLM

Stream partial structured JSON outputs without Pydantic ValidationError. Parse incremental LLM token chunks using jiter, OpenAI SDK, and vLLM guided_json.

AI Engineering
vLLM vs SGLang Benchmark: TTFT, Throughput & Prefill (2026)

SGLang hits 3.1x faster TTFT on multi-turn agents while vLLM cuts p99 jitter by 68%. Full RTX 4090 & A100 benchmarks for chunked prefill & FlashInfer.

AI Engineering
Fast LLM Serving in Production: vLLM, SGLang, and TensorRT-LLM

A practical guide to making LLM inference fast and cheap in production. Learn how memory management, batching, and quantization work in vLLM, SGLang, and TensorRT-LLM.

LLM Serving & Inference
vLLM Disaggregated Prefill and Decode with NIXL KV Transfer

Eliminate tail-latency spikes in vLLM by splitting prefill and decode nodes using NixlConnector over RDMA or NVLink. Includes configs and benchmarks.