All guides

Why your LLM agent's prompt cache hit rate is 0%, and how to load 200 tools without busting it

You turn on prompt caching for a multi-turn LLM agent expecting an 80% drop in input token spend, then check usage logs and see cache_read_input_tokens = 0 (or watch your bill jump after adding dynamic MCP tool discovery or a messages[-10:] history cap). Because every cached KV block hashes its parent block's hash, one changed token near the top silently rewrites the entire prompt at 1.25x. By the end of this guide you can:

  • Model chained SHA-256 KV block caching in standard-library Python and pinpoint the exact 128-token block and section where two consecutive agent turns diverge.
  • Price four silent cache killers across 12-turn and 20-turn loops: unordered tool lists, system-prompt timestamps, mutating tools[] during MCP tool discovery, and per-turn messages[-10:] history trimming.
  • Load 5 specialist schemas out of 200 MCP tools inline at the tail of messages, cutting 12-turn input spend by 4.3x versus static tools and 40% versus mutating tools[].

You need Python 3.12 or newer. No API key, no GPU, no network, and no packages to install.

Two-row technical diagram comparing a mutated tools array breaking chained SHA-256 block hashes across system and message history against a frozen tools prefix that appends discovered tool schemas at the tail of messages.
Turn 5 of an agent loop serialized in API order (tools -> system -> messages): inserting a newly discovered tool into top-level tools[] breaks every downstream block hash (0% of prior history reused on that turn), whereas freezing core tools and appending tool_reference or tool_search_output at the tail keeps 87.2% of session tokens on 0.10x cache reads (rounded to 87% above).

Before you start

You should know Python dataclasses, JSON serialization, and how a multi-turn tool-calling loop appends messages. If any piece feels rusty, open these first. The first three links open a Topic Breakdown roadmap (sign in to generate one), and the rest open public guides here.

  1. Cryptographic hash chains and Merkle-style parent links. Each KV block hash takes the previous block's hash as input, so a 1-token change cascades right.
  2. JSON canonicalization and deterministic key ordering in Python. Prompt caching compares token sequences, not abstract JSON dictionaries or sets.
  3. Model Context Protocol (MCP) tool schemas and deferred discovery. Large tool catalogs bloat early prefix blocks unless schemas load on demand.
  4. Will 32 chats fit on one GPU? Size the KV cache in Python. What physical key-value tensors live inside each cached 16-token or 128-token block.
  5. A long prompt makes your chat wait before the first word. Why? Size prefill and decode in Python. Why skipping cached prefix blocks slashes prefill compute and first-token wait.
  6. Debug an LLM agent: find the first bad step in its trace. How consecutive model spans and tool results accumulate across an agent trace.

The question

Your agent runs 12 to 20 turns per task and connects to 200 MCP or internal RPC tools (~40,000 tokens of JSON schemas). Why does enabling prompt caching sometimes raise your bill by 25%, why is a 90.9% cache hit rate on 200 static tools still 4.3x overpriced, and why does trimming messages[-10:] every turn cost twice as much as compacting once every 8 turns?

Agent designInput tokCache hitWrite tokCost / 1k runsFirst divergence / bottleneck
12 turns, caching off90,4980.0%0$271.49Baseline at $3.00 / 1M tok
12 turns, shuffled 8 tools90,4980.0%89,728$338.79Diverges at block 3 (tools)
12 turns, UTC clock in system90,54318.7%72,832$280.63Diverges at block 12 (system)
12 turns, sorted + UTC in user90,81086.8%11,264$67.993,840-token prefix stays intact
12 turns, all 200 tools up front551,87490.9%49,536$338.3740k tool tokens re-read 11x
12 turns, mutate tools[] on search106,20873.2%27,776$129.68Busts system + history 3x
12 turns, frozen tools + inline tail106,43287.2%12,672$78.244.3x cheaper than 200 up front
20 turns, slide messages[-10:]130,34656.4%56,448$235.00Rewrites 26 msg blocks/turn
20 turns, compact every 8 turns136,86485.7%18,432$107.852.18x cheaper than sliding

Every row comes from prompt_cache_sim.py below (128-token blocks, 1,024-token minimum cacheable prefix, $3.00/MTok base input, 1.25x 5-minute write, 0.10x read).

Five words we use

Prefix hierarchy
Hosted LLM APIs serialize requests in strict prefix order: tools -> system -> messages. Editing one tool definition sits upstream of system and messages, so it invalidates both downstream sections.
Chained block hash
In vLLM v1 Automatic Prefix Caching, full fixed-size KV blocks are addressed by sha256(parent_hash, block_tokens, extra_hashes). Do not confuse this with SGLang's RadixAttention tree: vLLM uses a flat hash table over fixed-size full blocks, while OpenAI reports hits in 128-token increments after 1,024 tokens.
Cache write multiplier
On Claude and OpenAI, reading cached tokens costs 0.10x base input price (or less on newer tiers), while writing new 5-minute or 30-minute cache blocks costs 1.25x (and 1-hour writes cost 2.00x on Claude). A 0% hit rate with caching turned on bills up to 25% more than turning caching off.
Deferred inline tool loading
Freezing top-level tools[] to a small core set plus tool_search, then appending discovered tool schemas at the end of messages[] (tool_reference on Claude, tool_search_output on OpenAI) so cached prefix blocks never change.
cache_salt
An optional tenant string mixed into block 0's hash in vLLM Automatic Prefix Caching. Two tenants with identical system prompts get separate block-0 hashes so neither can probe the other's prompt cache via first-token timing.

Worked example

Follow one standard-library script through six checks: building a chained-block diff inspector, catching unordered tools and system timestamps, loading 200 MCP tools via tail injection, replacing per-turn sliding windows with 8-turn compaction, sizing 5-minute vs 1-hour TTL across approval pauses, and isolating multi-tenant pools with cache_salt.

20-turn history management: per-turn sliding window vs periodic compaction every 8 turns (128-token blocks from Step 4)
20-turn cached read vs rewrite block bars comparing per-turn messages[-10:] sliding against 8-turn periodic compactionLeft panel shows slide_every_turn reading 28 blocks and rewriting 26 message blocks on every turn from Turn 6 to Turn 20 ($235.00 per 1,000 runs, 56.4% hit rate). Right panel shows compact_every_8 growing green cached blocks across 7 of every 8 turns and rewriting 13 compacted blocks only on Turn 9 and Turn 17 ($107.85 per 1,000 runs, 85.7% hit rate).Slide messages[-10:] every turn130,346 tok | 56.4% hit | $235.00 / 1k runsT01 0r/31wT0231r/ 5wT0336r/ 5wT0441r/ 5wT0546r/ 5wT0628r/26wT0728r/26wT0828r/26wT0928r/26wT1028r/26wT1128r/26wT1228r/26wT1328r/26wT1428r/26wT1528r/26wT1628r/26wT1728r/26wT1828r/26wT1928r/26wT2028r/26wTurns 6 to 20 rewrite all 26 message blocks (1.25x) every turnCompact once every 8 turns136,864 tok | 85.7% hit | $107.85 / 1k runsT01 0r/31wT0231r/ 5wT0336r/ 5wT0441r/ 5wT0546r/ 5wT0651r/ 5wT0756r/ 5wT0861r/ 5wT0928r/13wT1041r/ 6wT1147r/ 5wT1252r/ 5wT1357r/ 5wT1462r/ 5wT1567r/ 5wT1672r/ 5wT1728r/13wT1841r/ 6wT1947r/ 5wT2052r/ 5wAppend-only for 7 of 8 turns; resets message blocks only at T09 and T17Cached 128-token prefix blocks read at 0.10x (r)New or shifted 128-token blocks written at 1.25x (w)

  1. Hash chained 128-token prefix blocks and build a 15-line diff inspector

    Serialize each turn in canonical API order: tools, then system, then messages[0..n]. Split the token stream into fixed 128-token blocks (matching OpenAI's cached_tokens reporting increment and a 1,024-token minimum prefix) and hash every full block as sha256(parent_hash, block_tokens), the same chained construction documented in vLLM v1 Automatic Prefix Caching.

    Pair that hash chain with first_diverging_block(prev, curr). Instead of guessing why cached_tokens dropped to zero from billing dashboards, the helper walks block by block across two consecutive turns and prints the exact block index, token offset, and owning section (tools, system, or messages[i]) where the first mismatch occurred.

  2. Catch two 0%-to-19% hit-rate bugs that cost more than turning caching off

    Run a 12-turn agent loop with 8 core tools (~1,603 tokens) and a 2,048-token system policy at a $3.00/MTok base input price (1.25x 5-minute write, 0.10x read). With caching off, 12 turns process 90,498 tokens for $271.49 per 1,000 runs. If an unordered Python set or async MCP discovery gather shuffles those 8 tools between turns, Turn 2 diverges at block 3 (token 399, in tools). Because only 3 blocks (384 tokens) match before the mismatch, the prefix misses the 1,024-token minimum, hit rate drops to 0.0%, and 89,728 tokens pay the 1.25x write rate for $338.79 per 1,000 runs: 24.8% more expensive than no cache at all.

    Next, fix tool sorting and prepend a live UTC clock (UTC: 06:00:01Z) at the top of system. Turn 2 now diverges at block 12 (token 1605, in system): tools stay cached (18.7% hit rate), yet system and every message block rewrite on every turn for $280.63 per 1,000 runs, still worse than no cache. Keeping tools sorted and moving [utc=...] into the latest user message lifts hits to 86.8% and drops the bill to $67.99 per 1,000 runs (5.0x cheaper than shuffled tools).

  3. Load 5 specialist tools out of 200 MCP schemas without busting your history

    Scale the catalog to 200 MCP tools at 200 tokens each (40,000 schema tokens), where the agent discovers 5 specialist tools across turns 2, 5, and 9. Notice why cache hit percentage alone is a vanity metric: stuffing all 200 tools into tools[] on every turn achieves a 90.9% cache hit rate over 12 turns, yet still costs $338.37 per 1,000 runs ($189.59 on 3-turn runs) because writing 40,000 tool tokens once and re-reading them 11 times at 0.10x dwarfs the conversation itself, while crowding past the 30-to-50-tool accuracy cliff noted in Claude's tool-search docs.

    What if tool_search appends newly found schemas into top-level tools[]? Raw tokens fall from 551,874 to 106,208, but mutating tools[] invalidates system and all prior messages on turns 2, 5, and 9, dropping hits to 73.2% ($129.68 per 1,000 runs). Freezing tools[] to 8 core tools plus tool_search (with a 480-token namespace index in system) and appending discovered schemas as inline tool_search_output / tool_reference messages at the tail hits 87.2% of tokens and cuts 12-turn cost to $78.24 per 1,000 runs (4.3x cheaper than 200 tools up front, 40% cheaper than mutating tools[], and 7.0x cheaper on 3-turn sessions at $26.92 vs $189.59).

  4. Avoid the messages[-10:] sliding-window history trap on 20-turn runs

    Long agent runs eventually trim history. Keeping all 20 turns append-only processes 204,050 tokens at a 91.4% hit rate for $120.90 per 1,000 runs. Trimming every turn with messages = messages[-10:] cuts raw input tokens by 36% (down to 130,346), yet nearly doubles the bill to $235.00 per 1,000 runs! Why? Look at the per-turn block trace: turns 1 to 5 grow cleanly (0r/31w up to 46r/5w), then from turn 6 through turn 20 every single call logs 28r/26w. Dropping messages[0] shifts every surviving message into an earlier token offset, breaking all 26 message blocks while only the 28 blocks of tools + system survive.

    Instead, let messages grow append-only for 8 turns and compact once on turns 9 and 17 into a 400-token checkpoint plus the 4 newest messages. Raw tokens stay almost identical (136,864), 7 of every 8 turns append cleanly onto cached message blocks (85.7% hit rate), and cost drops to $107.85 per 1,000 runs: 2.18x cheaper than per-turn sliding and cheaper than keeping all 20 turns.

  5. Price 5-minute vs 1-hour cache TTL across human approval or CI pauses

    Agent loops often pause while waiting on a pull-request check or a human approval click. Inject two 6-minute (360-second) pauses before turns 5 and 9 of the 12-turn loop. Under a 5-minute (300-second, 1.25x write) TTL, both pauses expire the cached prefix and force full rewrites, dropping hits to 71.1% ($117.02 per 1,000 runs). Paying 2.00x up front for a 1-hour (3,600-second) TTL keeps the prefix warm across both pauses, preserves an 86.9% hit rate, and lowers total cost to $92.62 per 1,000 runs (21% cheaper).

  6. Verify multi-tenant cache_salt isolation in block 0 (self-hosted vLLM)

    If you self-host vLLM v1 with Automatic Prefix Caching across multiple customer organizations that share your system prompt and core tools, an attacker could time first-token latency to infer whether another tenant recently asked the same prefix. Passing a per-tenant cache_salt mixes that salt into block 0's SHA-256 hash. Step 6 verifies both sides on one shared PrefixCacheSim pool: tenant_b's first turn with identical tools, system, and question diverges at block 0 (read = 0, write = 3,968), then tenant_b's second turn reads all 3,968 tokens from its own salted chain.

Run it yourself

Save the script below as prompt_cache_sim.py. The output shown here was captured on 24 November 2026 on Windows with Python 3.12.16. It uses only the Python standard library (dataclasses, hashlib, json, and random), needs no API key or GPU, and finishes in under a second.

To test your own agent harness, pass two consecutive serialized payloads into first_diverging_block(prev, curr), or adjust USD_PER_MTOK, BLOCK_TOKENS, and MIN_CACHE_TOKENS to match your model provider.

prompt_cache_sim.py
"""Local prefix-cache simulator and diff inspector for multi-turn LLM agent loops.

Standard library only (dataclasses, hashlib, json, random). No API key, no GPU, no network.
Models chained block hashing sha256(parent_hash, block_tokens), optional block-0 cache_salt,
a 1,024-token minimum cacheable prefix, 128-token blocks, and 1.25x / 2.00x write vs 0.10x read rates.
"""

from dataclasses import dataclass
import hashlib
import json
import random

BLOCK_TOKENS = 128
MIN_CACHE_TOKENS = 1024
WRITE_5M_MULT = 1.25
WRITE_1H_MULT = 2.00
READ_MULT = 0.10
USD_PER_MTOK = 3.00  # Reference base input price: $3.00 / 1M tokens ($3.75 5m write, $0.30 read)


def make_pad(label: str, target_tokens: int) -> str:
    seed = f"[{label}] "
    repeats = (target_tokens * 4) // len(seed) + 1
    return (seed * repeats)[: target_tokens * 4]


@dataclass(frozen=True)
class Section:
    name: str
    text: str


def serialize_sections(tools: list[dict], system: str, messages: list[dict]) -> list[Section]:
    """Serialize in canonical prefix order: tools -> system -> messages."""
    sections = [
        Section("tools", json.dumps(tools, sort_keys=True, separators=(",", ":"))),
        Section("system", system),
    ]
    for idx, msg in enumerate(messages):
        sections.append(Section(f"messages[{idx}]", json.dumps(msg, sort_keys=True, separators=(",", ":"))))
    return sections


def to_token_chunks(sections: list[Section]) -> tuple[list[str], list[str]]:
    """Split serialized prompt into deterministic 4-char pseudo-tokens and section owners."""
    full_chars = "".join(s.text for s in sections)
    spans: list[tuple[int, int, str]] = []
    pos = 0
    for s in sections:
        spans.append((pos, pos + len(s.text), s.name))
        pos += len(s.text)

    n_toks = (len(full_chars) + 3) // 4
    tokens: list[str] = []
    owners: list[str] = []
    for i in range(n_toks):
        c = i * 4
        tokens.append(full_chars[c : c + 4])
        owner = sections[-1].name
        for start, end, name in spans:
            if start <= c < end:
                owner = name
                break
        owners.append(owner)
    return tokens, owners


def chained_block_hashes(tokens: list[str], cache_salt: str = "") -> list[str]:
    """Hash each full 128-token block from (parent_hash, block_tokens), with optional block-0 salt."""
    hashes: list[str] = []
    parent = f"GENESIS:{cache_salt}" if cache_salt else "GENESIS"
    for b in range(len(tokens) // BLOCK_TOKENS):
        chunk = "|".join(tokens[b * BLOCK_TOKENS : (b + 1) * BLOCK_TOKENS])
        h = hashlib.sha256(f"{parent}:{chunk}".encode("utf-8")).hexdigest()[:16]
        hashes.append(h)
        parent = h
    return hashes


def first_diverging_block(
    prev_sections: list[Section],
    curr_sections: list[Section],
    prev_salt: str = "",
    curr_salt: str = "",
) -> str:
    """Pinpoint the first 128-token block and section where two requests diverge."""
    prev_toks, _ = to_token_chunks(prev_sections)
    curr_toks, curr_own = to_token_chunks(curr_sections)
    prev_h = chained_block_hashes(prev_toks, prev_salt)
    curr_h = chained_block_hashes(curr_toks, curr_salt)
    limit = min(len(prev_h), len(curr_h))
    for b in range(limit):
        if prev_h[b] != curr_h[b]:
            for offset in range(BLOCK_TOKENS):
                idx = b * BLOCK_TOKENS + offset
                if prev_toks[idx] != curr_toks[idx]:
                    return f"block {b} (token {idx}, in {curr_own[idx]})"
            return f"block {b} (cache_salt mismatch in block 0)"
    return f"none ({limit * BLOCK_TOKENS} shared prefix tokens matched)"


class PrefixCacheSim:
    def __init__(self, ttl_seconds: int = 300, write_mult: float = WRITE_5M_MULT) -> None:
        self.ttl_seconds = ttl_seconds
        self.write_mult = write_mult
        self.store: dict[str, int] = {}

    def send(
        self,
        sections: list[Section],
        now_s: int,
        use_cache: bool = True,
        cache_salt: str = "",
    ) -> dict[str, float | int]:
        tokens, _ = to_token_chunks(sections)
        total_tokens = len(tokens)
        if not use_cache or total_tokens < MIN_CACHE_TOKENS:
            return {
                "total": total_tokens,
                "read": 0,
                "write": 0,
                "uncached": total_tokens,
                "cost_units": float(total_tokens),
            }

        hashes = chained_block_hashes(tokens, cache_salt)
        hit_blocks = 0
        for h in hashes:
            last_ts = self.store.get(h)
            if last_ts is not None and (now_s - last_ts) <= self.ttl_seconds:
                hit_blocks += 1
            else:
                break

        full_block_tokens = len(hashes) * BLOCK_TOKENS
        tail_uncached = total_tokens - full_block_tokens
        read_tokens = hit_blocks * BLOCK_TOKENS

        if read_tokens < MIN_CACHE_TOKENS:
            read_tokens = 0
            write_tokens = full_block_tokens
            for h in hashes:
                self.store[h] = now_s
        else:
            for b in range(hit_blocks):
                self.store[hashes[b]] = now_s
            write_tokens = full_block_tokens - read_tokens
            for h in hashes[hit_blocks:]:
                self.store[h] = now_s

        cost_units = read_tokens * READ_MULT + write_tokens * self.write_mult + tail_uncached * 1.0
        return {
            "total": total_tokens,
            "read": read_tokens,
            "write": write_tokens,
            "uncached": tail_uncached,
            "cost_units": cost_units,
        }


def make_tool(i: int, target_tokens: int = 200) -> dict:
    base = {"name": f"mcp_tool_{i:03d}", "description": "", "input_schema": {"type": "object", "required": ["id"]}}
    overhead = len(json.dumps(base, sort_keys=True, separators=(",", ":")))
    base["description"] = "x" * max(4, target_tokens * 4 - overhead)
    return base


def format_row(label: str, tot: dict[str, float | int], extra: str = "") -> str:
    hit_pct = 100.0 * float(tot["read"]) / float(tot["total"]) if tot["total"] else 0.0
    usd_1k = (float(tot["cost_units"]) * 1000.0 / 1_000_000.0) * USD_PER_MTOK
    suffix = f" | {extra}" if extra else ""
    return (
        f"  {label:20s} | in={int(tot['total']):7d} | read={int(tot['read']):7d} ({hit_pct:5.1f}%) "
        f"| write={int(tot['write']):7d} | $/1k_runs=${usd_1k:6.2f}{suffix}"
    )


def main() -> None:
    all_200_tools = [make_tool(i, 200) for i in range(200)]
    core_8_tools = all_200_tools[:8]  # ~1,600 tokens
    search_tool = make_tool(999, 128)
    static_sys = make_pad("system_policy", 2048)

    rng = random.Random(42)
    shuffled_per_turn = [rng.sample(core_8_tools, len(core_8_tools)) for _ in range(12)]

    print("Step 1 & 2: Catch prefix-busting bugs across a 12-turn agent loop")
    for mode in ("no_cache", "shuffled_tools", "system_timestamp", "stable_prefix"):
        sim = PrefixCacheSim(ttl_seconds=300)
        msgs: list[dict] = []
        tot: dict[str, float | int] = {"total": 0, "read": 0, "write": 0, "cost_units": 0.0}
        prev_sec: list[Section] | None = None
        diff_msg = ""
        for t in range(12):
            user_body = make_pad(f"turn_{t}_obs", 280)
            if mode == "stable_prefix":
                user_body = f"[utc=06:00:{t:02d}Z] " + user_body
            msgs.append({"role": "user", "content": user_body})
            if mode == "no_cache":
                sec = serialize_sections(core_8_tools, static_sys, msgs)
                res = sim.send(sec, t * 15, use_cache=False)
            elif mode == "shuffled_tools":
                sec = serialize_sections(shuffled_per_turn[t], static_sys, msgs)
                res = sim.send(sec, t * 15, use_cache=True)
            elif mode == "system_timestamp":
                sec = serialize_sections(core_8_tools, f"UTC: 06:00:{t:02d}Z\n" + static_sys, msgs)
                res = sim.send(sec, t * 15, use_cache=True)
            else:
                sec = serialize_sections(core_8_tools, static_sys, msgs)
                res = sim.send(sec, t * 15, use_cache=True)
            if t == 1 and prev_sec is not None:
                diff_msg = first_diverging_block(prev_sec, sec)
            prev_sec = sec
            msgs.append({"role": "assistant", "content": make_pad(f"turn_{t}_act", 360)})
            for k in tot:
                tot[k] = float(tot[k]) + float(res[k])
        print(format_row(mode, tot, f"turn2_diff={diff_msg}"))

    print("\nStep 3: Scale to 200 MCP tools (40,000 schema tokens), discovering 5 tools on turns 2, 5, 9")
    discover_map = {1: [20, 21], 4: [55, 56], 8: [130]}
    sys_with_catalog = static_sys + make_pad("namespace_catalog_index", 480)
    for n_turns in (3, 12):
        print(f"  -- Session length: {n_turns} turns --")
        for strat in ("all_200_upfront", "mutate_tools_array", "defer_inline_tail"):
            sim = PrefixCacheSim(ttl_seconds=300)
            msgs = []
            active_tools = list(core_8_tools) + [search_tool]
            tot = {"total": 0, "read": 0, "write": 0, "cost_units": 0.0}
            for t in range(n_turns):
                msgs.append({"role": "user", "content": make_pad(f"u_{t}", 280)})
                if t in discover_map:
                    found = [all_200_tools[idx] for idx in discover_map[t]]
                    if strat == "mutate_tools_array":
                        active_tools = active_tools + found
                    elif strat == "defer_inline_tail":
                        msgs.append({"role": "tool_search_output", "tools": found})
                if strat == "all_200_upfront":
                    sec = serialize_sections(all_200_tools, static_sys, msgs)
                else:
                    sec = serialize_sections(active_tools, sys_with_catalog, msgs)
                res = sim.send(sec, t * 15, use_cache=True)
                msgs.append({"role": "assistant", "content": make_pad(f"a_{t}", 360)})
                for k in tot:
                    tot[k] = float(tot[k]) + float(res[k])
            print(format_row(strat, tot))

    print("\nStep 4: 20-turn history trimming (sliding every turn vs periodic compaction every 8 turns)")
    turn_traces: dict[str, list[str]] = {}
    for hist_mode in ("append_all", "slide_every_turn", "compact_every_8"):
        sim = PrefixCacheSim(ttl_seconds=300)
        msgs = []
        tot = {"total": 0, "read": 0, "write": 0, "cost_units": 0.0}
        trace: list[str] = []
        for t in range(20):
            msgs.append({"role": "user", "content": make_pad(f"u_{t}", 320)})
            if hist_mode == "slide_every_turn" and len(msgs) > 10:
                msgs = msgs[-10:]
            elif hist_mode == "compact_every_8" and t in (8, 16):
                msgs = [{"role": "user", "content": make_pad(f"checkpoint_{t}", 400)}] + msgs[-4:]
            sec = serialize_sections(core_8_tools, static_sys, msgs)
            res = sim.send(sec, t * 15, use_cache=True)
            trace.append(f"{int(res['read']) // BLOCK_TOKENS}r/{int(res['write']) // BLOCK_TOKENS}w")
            msgs.append({"role": "assistant", "content": make_pad(f"a_{t}", 320)})
            for k in tot:
                tot[k] = float(tot[k]) + float(res[k])
        turn_traces[hist_mode] = trace
        print(format_row(hist_mode, tot))
    print("  slide_every_turn blocks  :", " ".join(turn_traces["slide_every_turn"]))
    print("  compact_every_8 blocks   :", " ".join(turn_traces["compact_every_8"]))

    print("\nStep 5: Two 6-minute approval or CI pauses on turns 4 and 8 (5m TTL vs 1h TTL)")
    for label, ttl_s, w_mult in (
        ("5m_ttl_with_pauses", 300, WRITE_5M_MULT),
        ("1h_ttl_with_pauses", 3600, WRITE_1H_MULT),
    ):
        sim = PrefixCacheSim(ttl_seconds=ttl_s, write_mult=w_mult)
        msgs = []
        tot = {"total": 0, "read": 0, "write": 0, "cost_units": 0.0}
        clock = 0
        for t in range(12):
            clock += 360 if t in (4, 8) else 15
            msgs.append({"role": "user", "content": f"[utc={clock}s] " + make_pad(f"turn_{t}_obs", 280)})
            sec = serialize_sections(core_8_tools, static_sys, msgs)
            res = sim.send(sec, clock, use_cache=True)
            msgs.append({"role": "assistant", "content": make_pad(f"turn_{t}_act", 360)})
            for k in tot:
                tot[k] = float(tot[k]) + float(res[k])
        print(format_row(label, tot))

    print("\nStep 6: Multi-tenant cache_salt isolation in block 0 (vLLM Automatic Prefix Caching)")
    shared_pool = PrefixCacheSim(ttl_seconds=300)
    base_msgs = [{"role": "user", "content": make_pad("shared_question", 320)}]
    sec_t1 = serialize_sections(core_8_tools, static_sys, base_msgs)
    sec_t2 = serialize_sections(
        core_8_tools,
        static_sys,
        base_msgs + [{"role": "assistant", "content": make_pad("a_0", 320)}, {"role": "user", "content": make_pad("u_1", 320)}],
    )
    r_a1 = shared_pool.send(sec_t1, 0, cache_salt="tenant_a")
    r_b1 = shared_pool.send(sec_t1, 5, cache_salt="tenant_b")
    r_b2 = shared_pool.send(sec_t2, 10, cache_salt="tenant_b")
    salt_diff = first_diverging_block(sec_t1, sec_t1, "tenant_a", "tenant_b")
    print(f"  tenant_a turn 1 (salt='tenant_a') | read={int(r_a1['read']):4d} | write={int(r_a1['write']):4d}")
    print(f"  tenant_b turn 1 (salt='tenant_b') | read={int(r_b1['read']):4d} | write={int(r_b1['write']):4d} | diff={salt_diff}")
    print(f"  tenant_b turn 2 (salt='tenant_b') | read={int(r_b2['read']):4d} | write={int(r_b2['write']):4d} | reuses own salted prefix")


if __name__ == "__main__":
    main()
Terminal
uv run --no-project --python 3.12 python prompt_cache_sim.py
Output on Python 3.12.16
Step 1 & 2: Catch prefix-busting bugs across a 12-turn agent loop
  no_cache             | in=  90498 | read=      0 (  0.0%) | write=      0 | $/1k_runs=$271.49 | turn2_diff=none (3840 shared prefix tokens matched)
  shuffled_tools       | in=  90498 | read=      0 (  0.0%) | write=  89728 | $/1k_runs=$338.79 | turn2_diff=block 3 (token 399, in tools)
  system_timestamp     | in=  90543 | read=  16896 ( 18.7%) | write=  72832 | $/1k_runs=$280.63 | turn2_diff=block 12 (token 1605, in system)
  stable_prefix        | in=  90810 | read=  78848 ( 86.8%) | write=  11264 | $/1k_runs=$ 67.99 | turn2_diff=none (3840 shared prefix tokens matched)

Step 3: Scale to 200 MCP tools (40,000 schema tokens), discovering 5 tools on turns 2, 5, 9
  -- Session length: 3 turns --
  all_200_upfront      | in= 129123 | read=  85376 ( 66.1%) | write=  43648 | $/1k_runs=$189.59
  mutate_tools_array   | in=  16405 | read=   7168 ( 43.7%) | write=   8960 | $/1k_runs=$ 36.58
  defer_inline_tail    | in=  16424 | read=   9984 ( 60.8%) | write=   6144 | $/1k_runs=$ 26.92
  -- Session length: 12 turns --
  all_200_upfront      | in= 551874 | read= 501632 ( 90.9%) | write=  49536 | $/1k_runs=$338.37
  mutate_tools_array   | in= 106208 | read=  77696 ( 73.2%) | write=  27776 | $/1k_runs=$129.68
  defer_inline_tail    | in= 106432 | read=  92800 ( 87.2%) | write=  12672 | $/1k_runs=$ 78.24

Step 4: 20-turn history trimming (sliding every turn vs periodic compaction every 8 turns)
  append_all           | in= 204050 | read= 186496 ( 91.4%) | write=  16384 | $/1k_runs=$120.90
  slide_every_turn     | in= 130346 | read=  73472 ( 56.4%) | write=  56448 | $/1k_runs=$235.00
  compact_every_8      | in= 136864 | read= 117248 ( 85.7%) | write=  18432 | $/1k_runs=$107.85
  slide_every_turn blocks  : 0r/31w 31r/5w 36r/5w 41r/5w 46r/5w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w 28r/26w
  compact_every_8 blocks   : 0r/31w 31r/5w 36r/5w 41r/5w 46r/5w 51r/5w 56r/5w 61r/5w 28r/13w 41r/6w 47r/5w 52r/5w 57r/5w 62r/5w 67r/5w 72r/5w 28r/13w 41r/6w 47r/5w 52r/5w

Step 5: Two 6-minute approval or CI pauses on turns 4 and 8 (5m TTL vs 1h TTL)
  5m_ttl_with_pauses   | in=  90699 | read=  64512 ( 71.1%) | write=  25472 | $/1k_runs=$117.02
  1h_ttl_with_pauses   | in=  90699 | read=  78848 ( 86.9%) | write=  11136 | $/1k_runs=$ 92.62

Step 6: Multi-tenant cache_salt isolation in block 0 (vLLM Automatic Prefix Caching)
  tenant_a turn 1 (salt='tenant_a') | read=   0 | write=3968
  tenant_b turn 1 (salt='tenant_b') | read=   0 | write=3968 | diff=block 0 (cache_salt mismatch in block 0)
  tenant_b turn 2 (salt='tenant_b') | read=3968 | write= 640 | reuses own salted prefix

Where you will see this

Every failure mode in prompt_cache_sim.py maps directly to production serving engines and hosted agent SDKs, checked on 24 November 2026. Anthropic's tool use with prompt caching guide and tool search documentation show why multiserver MCP catalogs (~55,000 tokens) belong behind defer_loading: true so discovered schemas land as inline tool_reference blocks instead of mutating tools[], and OpenAI's tool search guide plus prompt caching guide document the same tail injection via tool_search_output alongside 1,024-token minimums and 128-token hit increments.

Under the hood, the vLLM v1 Automatic Prefix Caching design doc shows why prefixes are brittle: full KV blocks are indexed in a hash table keyed by sha256(parent_hash, block_tokens, extra_hashes) with optional cache_salt in block 0, append-only block tables, and reverse-order free-queue eviction (unlike SGLang's RadixAttention tree, which several local-LLM blog tutorials conflate with vLLM). In production harnesses, HubSpot Engineering's Aviator write-up explains why managing 3,000+ internal RPC tools requires centralized tool discovery and prompt-cache discipline, and openai-agents-python Issue #5085 shows how easily a nested subagent wrapper can drop a 78% to 90% parent hit rate straight to 0%.

What this does not do

  • Our simulator splits text into deterministic 4-character chunks so it runs in standard-library Python with zero downloads. Real BPE tokenizers (such as cl100k_base, o200k_base, or Claude's tokenizer) split JSON punctuation and identifiers at token boundaries that can shift block edges by a few tokens; plug in tiktoken or your provider's token counter if you need exact token-boundary alignment.
  • We price input tokens at one reference rate ($3.00 per 1M base input tokens, 1.25x 5-minute write, 2.00x 1-hour write, 0.10x read). OpenAI charges no explicit write premium on automatic 5-to-10-minute caches on several models while charging write multipliers or offering 0.05x/0.10x reads depending on tier and extended retention; edit USD_PER_MTOK, WRITE_5M_MULT, and READ_MULT to match your exact model pricing page.
  • Anthropic's manual cache_control breakpoints also include a 20-block backward lookback window that can still match unmodified message prefixes within 20 content blocks when only recent messages stay static, whereas automatic prefix caching and top-level tools[] edits invalidate strictly from the first changed token onward.
  • Self-hosted vLLM uses 16-token physical KV blocks by default (configurable via --block-size) and evicts unreferenced blocks from a finite GPU memory pool tail-first (deepest sequence blocks first) when VRAM fills up. Combine this script with our KV cache sizing guide when your GPU block pool is near capacity.

This guide connects our LLM serving series with our Python agent reliability series. To size the GPU memory inside those cached blocks and the first-token latency they save, read how to size the KV cache for concurrent chats and why prefill makes the first token slow. To harden the rest of your tool loop, read how to find the first bad step in an agent trace, how to retry timed-out tool calls with an idempotency key, and how to keep raw API keys out of a coding agent with a ticket broker. Browse every tutorial on the guides page.

Explore this topic in the workspace

Topic Breakdown builds a structured learning roadmap with a concise chapter guide and lets you highlight any phrase or formula to open side-by-side chats without losing your place. Sign in to create your own breakdown.

Open breakdown

Or type Prompt caching, KV block hashes and tool search for LLM agents into the topic box on the home page. Want to try the Horizon workspace before signing in? Open the sample breakdown on Machine Learning.

Sources

All sources were checked on 24 November 2026. Read each primary page for full API and engine specifications.

  • Claude Platform Docs: Tool use with prompt caching

    Checked 24 November 2026. Documents the tools -> system -> messages prefix hierarchy, why changing tool definitions invalidates system and messages caches, and how defer_loading appends discovered tools as inline tool_reference blocks in messages to keep the prefix cached.

  • Claude Platform Docs: Prompt caching

    Checked 24 November 2026. Gives 1.25x 5-minute cache write, 2.0x 1-hour cache write, and 0.10x standard cache read multipliers, minimum cacheable prompt lengths (1,024 to 4,096 tokens by model), cumulative prefix hashing, and the 20-block lookback window.

  • Claude Platform Docs: Tool search tool

    Checked 24 November 2026. Reports ~55,000-token multiserver MCP tool overhead, degraded tool-selection accuracy past 30 to 50 tools, and >85% token reduction from loading 3 to 5 tools on demand via regex or BM25 search.

  • OpenAI API Docs: Prompt caching

    Checked 24 November 2026. Documents the 1,024-token minimum cacheable prefix, 128-token cached_tokens increments, cache retention windows, and why modifying tools or compacting earlier turns prevents cache reuse from the first altered token onward.

  • OpenAI API Docs: Tool search

    Checked 24 November 2026. Documents hosted and client-executed defer_loading with tool_search, injecting discovered schemas as tool_search_output items at the end of the context window to preserve prompt cache hits.

  • vLLM Design Docs: Automatic Prefix Caching

    Checked 24 November 2026. Details vLLM v1 full-block-only KV caching via sha256(parent_hash, block_tokens, extra_hashes), block-0 cache_salt tenant isolation, append-only block tables, and reverse-order doubly linked free-queue LRU eviction.

  • HubSpot Engineering: Aviator, HubSpot's Agent Harness

    Published 19 November 2026, checked 24 November 2026. Describes operating multi-turn agents across 3,000+ internal RPC tools and why deferred tool search, skill manifests, and strict prompt-cache discipline belong in a shared harness.

  • openai/openai-agents-python Issue #5085: Nested subagent runs returning 0% cached_tokens

    Checked 24 November 2026. Production bug report contrasting 78% to 90% parent-agent cache hit rates with flat 0% hits when nested session serialization alters the request prefix.

  • Our LLM serving and agent reliability guides: KV cache concurrency, first-token prefill, trace debugging, and idempotent retries

    Checked 24 November 2026. Cover physical BF16 KV cache bytes per token, prefill TTFT floors, first-bad-step trace inspection, and safe tool-call retries.