Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

KV Cache, Prefix Cache, Prompt Cache, and Semantic Cache: A Clear Breakdown of 4 Types of LLM Caching

Large language models use four main types of caching: KV Cache for attention tensors, Prefix Cache for server-side exact matching, Prompt Cache for billed exact lookups, and Semantic Cache for fuzzy matching based on embedding cosine similarity. This guide explains how each works, their trade-offs, common failure modes, and how developers can use them to reduce token usage and lower costs.

LLM cachingKV CachePrefix CachePrompt CacheSemantic Cache

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

🔗 Original link: KV, Prefix, Prompt and Semantic Caching in LLMs, clearly explained

Avi Chawla · X · @_avichawla · 2026-08-28 17:13

📌 This article is a repost. Copyright belongs to the original author. The original linked article is the authoritative version.

What you need to understand is where your input tokens are being recomputed and what you can do about it. Starting from first principles, this article covers four layers of caching and their trade-offs, what happens when they interact, and the five most common issues that prevent cache reuse.


In the LLM stack, four different mechanisms store four different kinds of objects, yet all of them are called caches.

  • KV caching stores attention tensors for a single request.

  • Prefix caching stores those same tensors on the server, keyed by a hash chain of token IDs.

  • Prompt caching is the provider’s billable version of that lookup: reads cost 0.1× the base input price, while writes carry a premium at 1.25× the base price.

  • Semantic caching stores complete response strings, using cosine similarity between embeddings for lookup.

The first three use exact matching and preserve correctness, so a cache miss costs you money and latency. The fourth uses fuzzy matching: it can return a wrong answer along with a 200 status code.

So today, let’s break down these four types of caching, what each one stores, and what silently breaks them.

Everything here runs on a single machine—even on a CPU—using a 360M-parameter model. There is also an Anthropic API example and a small semantic cache built with sentence-transformers. If a mechanism exists only inside a serving engine, we’ll explain its logic with pseudocode rather than pretend it can be reproduced on a laptop.

Also, the caching API changed in transformers v5, so the snippets below assume you are using v5 or later. In v4, the equivalent is to use DynamicCache() without the config argument, and torch_dtype= instead of dtype=.

bash
pip install "transformers>=5.0" torch


# only for the quantized cache example
pip install optimum-quanto


# only for the semantic cache example
pip install sentence-transformers 


# only for the prompt caching example
pip install anthropic

1) KV Caching

During prefill, the model computes key and value vectors for every prompt token at every layer and stores them.

Decoding then attends to these stored vectors and appends a new key-value pair for each generated token, without recomputing the entire sequence at every step.

Query vectors are not cached because of causal masking. A token’s query vector is used only once, during the step in which that token is processed, and is never read again. Its key and value are read by every subsequent token, making these the two vectors worth saving.

  • Without storing them, every decoding step requires matrix–matrix multiplications over the entire sequence generated so far.

  • With caching, that step becomes matrix–vector multiplications for a single new token, substantially reducing FLOPs (floating-point operations).

The video below shows LLM inference with and without KV caching:

Although this reduces computation per token, you still have to load the entire cache from HBM at every step, so decoding shifts from being compute-bound to being memory-bandwidth-bound.

The attention kernel finishes its computations faster than the cache can stream in, leaving the GPU waiting on memory for much of each decoding step.

KV Cache Growth per Token

The transformers library exposes the cache as a first-class object, so you can hold on to it, inspect it, and pass it back in.

Here is a minimal code example:

python
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache

model_id = "HuggingFaceTB/SmolLM2-360M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, dtype=torch.bfloat16, device_map="auto"
)

inputs = tokenizer("The capital of France is", return_tensors="pt")
inputs = inputs.to(model.device)

past_key_values = DynamicCache(config=model.config)

out = model.generate(
    **inputs,
    do_sample=False,
    max_new_tokens=20,
    past_key_values=past_key_values,
)

>>> print(tokenizer.decode(out[0], skip_special_tokens=True))
"""The capital of France is Paris. It is the largest city in
France and the second-largest city in the European Union."""

>>> print("prompt tokens: ", inputs["input_ids"].shape[1])
"prompt tokens: 5"

>>> print("total tokens: ", out.shape[1])
"total tokens:  25"

>>> print("cache length: ", past_key_values.get_seq_length())
"cache length:  24"

Normally, when you call the generate method, the cache is created and destroyed internally, hidden from view. Here, we construct a DynamicCache ourselves and pass it in, which means we still hold a reference to it after generation finishes.

Then, get_seq_length() reports the number of token positions in the cache. When you run this code, the reported length equals the prompt length plus the number of generated tokens, minus one.

The keys and values for the final token are computed, but no subsequent token uses them in an attention computation.

This code shows that the cache stores one entry for each token seen, and each decoding step adds exactly one entry.

DynamicCache is the default choice because it grows during generation rather than being preallocated, so short requests do not reserve memory they will never use.

The cache determines how many requests can fit on a GPU. Its size is determined by the model architecture and grows linearly with the number of tokens, because each layer stores a key tensor and a value tensor for each KV head.

For a 70B model in BF16 precision, a 128K context requires roughly 40 GB of cache—almost as much memory as the entire model with 4-bit weights.

There are several ways to reduce this footprint. For example, grouped-query attention shares a single key head and value head across a group of query heads, shrinking the cache and increasing the FLOPs per byte of data loaded.

Multi-head latent attention in the DeepSeek family compresses the entire cache into a latent vector.

Cache quantization trades a small amount of numerical precision for roughly twice the capacity. This feature is already implemented in transformers:

python

# requires: pip install optimum-quanto
out = model.generate(
    **inputs,
    do_sample=False,
    max_new_tokens=20,
    cache_implementation="quantized",
    cache_config={"nbits": 4, "backend": "quanto"},
)
print(tokenizer.decode(out[0], skip_special_tokens=True))

Just two parameters replace the default cache with a quantized version.

KV values are stored at reduced precision, lowering memory usage at the cost of quantization and dequantization on every access.

The backend also requires the group size to evenly divide the model's head dimension, so uncommon architectures may reject this configuration outright.

For short contexts, this overhead can slow things down rather than speed them up, so it is best used when memory is tight.

The Cache Is Freed When the Request Ends

Everything described above happens within a single call. The engine frees these blocks when the request ends, so on turn 20 of a 20-turn conversation, it performs prefill again for turns 1 through 19, incurring the full cost.

An alternative is to keep the cache alive yourself across turns, as shown below.

python
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache

model_id = "HuggingFaceTB/SmolLM2-360M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, dtype=torch.bfloat16, device_map="auto"
)

past_key_values = DynamicCache(config=model.config)
messages = []

questions = ["What is the capital of France?", "And its population?"]

for prompt in questions:
    # Add to the history
    messages.append({"role": "user", "content": prompt})

   # Tokenize
    inputs = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True,
        return_tensors="pt", return_dict=True
    ).to(model.device)

    # Generate
    input_length = inputs["input_ids"].shape[1]
    outputs = model.generate(
         **inputs, do_sample=False,
         max_new_tokens=64,
         past_key_values=past_key_values
    )

    # decode
    completion = tokenizer.decode(outputs[0, input_length:], skip_special_tokens=True)

    # Append to message history
    messages.append({"role": "assistant", "content": completion})
    print(f"turn tokens in: {input_length} | cache now: {past_key_values.get_seq_length()}")

# Output:
"turn tokens in: 42 | cache now: 55"
"turn tokens in: 71 | cache now: 92"
  • The past_key_values object is created once outside the loop and passed into each generation call. This prevents the cache from being released at the end of the first turn, leaving it fully populated when the second turn begins.

  • On each turn, we rebuild the full message list and render it again using apply_chat_template. The prompt sent on the second turn contains everything from the first turn plus the new question.

  • Because the cache already holds the tokens from the first turn, the model only prefills the new suffix. The printed input_length grows with each turn, but the actual prefill workload does not.

  • The completion is sliced from the generated IDs and appended back to the messages. This is what makes the next turn’s prompt a strict extension of the previous one.

Reuse works because the second turn’s token sequence begins with the first turn’s token sequence—an exact, token-for-token match. If you edit any earlier content in the history, the cache becomes invalid.​

In this code demo, the cache belongs to a single Python variable in one process. In a serving engine, it belongs to a shared pool that thousands of requests query. Let’s explore that next.


2) Prefix Caching

The shared pool described above comes from a change in behavior.

When a request finishes, the engine retains its KV blocks in memory rather than releasing them, and maintains an index so that later requests can find them. This is prefix caching.

The index must enforce the same rule as the chat loop: reuse is valid only when the preceding tokens are identical.

vLLM does this by storing the cache in blocks of 16 tokens by default and identifying each block using a hash that combines the parent block’s hash with the token IDs in the block.

Linking the parent hash into each child block turns a block lookup into a prefix lookup: a block matches only if everything before it also matches.

The scheduler walks through the incoming blocks in order and stops at the first cache miss. A hit increments the block’s reference count and pins it for as long as the request uses it, preventing eviction.

Everything from the first miss onward receives fresh allocations and a new prefill pass.

The Lookup Code

vLLM runs this process inside its scheduler, integrated with the memory management that handles the actual tensors.

The code below retains only the two parts that determine reuse: the function that converts a token sequence into block keys, and the function that walks through those keys to calculate how much prefix prefill can be skipped.

python
BLOCK_SIZE = 16

def block_hashes(token_ids, salt=None):
    """Chain-hash a token sequence into per-block keys."""

    hashes, parent = [], hash(salt)

    # Only complete blocks are hashed. A partial tail block is skipped.
    for start in range(0, len(token_ids) - BLOCK_SIZE + 1, BLOCK_SIZE):
        block = tuple(token_ids[start : start + BLOCK_SIZE])
        parent = hash((parent, block))
        hashes.append(parent)

    return hashes

def schedule(token_ids, cache):

    """Return how many tokens are reusable, and allocate the rest."""

    matched_blocks = 0

    for h in block_hashes(token_ids):
        if h not in cache:
            break                      # first miss ends all reuse
        cache[h].ref_count += 1        # pin it against eviction
        matched_blocks += 1

    reused_tokens = matched_blocks * BLOCK_SIZE
    to_prefill = token_ids[reused_tokens:]

    return reused_tokens, to_prefill
  • The block_hashes function splits the token sequence into fixed-size blocks of 16 tokens. Each block’s key incorporates the previous block’s key through hash ((parent, block)), so the fifth key encodes blocks one through five, not just the fifth block itself.

  • The range stops at len (token_ids) - BLOCK_SIZE + 1, leaving out any partial block at the end. Those tokens are never indexed and are recomputed for every request that ends at that position.

  • The schedule function walks through the keys in order and stops at the first missing key. It does not try to resume matching later in the sequence, because the keys for later blocks already depend on the earlier block that missed.

  • ref_count += 1 marks the block as in use. Eviction affects only blocks with a count of zero, preventing cached blocks from being removed while a running request is using them.

  • All matched tokens are counted in reused_tokens, and everything after them undergoes prefill from scratch.

There is one more important detail in the code we just discussed:

python
BLOCK_SIZE = 16

def block_hashes(token_ids, salt=None):
    """Chain-hash a token sequence into per-block keys."""

    hashes, parent = [], hash(salt)

    # Only complete blocks are hashed. A partial tail block is skipped.
    for start in range(0, len(token_ids) - BLOCK_SIZE + 1, BLOCK_SIZE):
        block = tuple(token_ids[start : start + BLOCK_SIZE])
        parent = hash((parent, block))
        hashes.append(parent)

    return hashes

Notice the salt parameter in the function above.

When two requests send the same text, they produce the same block keys, so they end up pointing to the same physical KV blocks in GPU memory. There is only one copy of these tensors, and both requests read from it.

When both requests come from the same application, this is exactly the behavior you want.

But when they come from different customers, you may need to make a choice. Passing a tenant-specific value as the salt changes the initial parent hash, so identical text now produces different keys for each tenant, and their requests never map to the same blocks.

This gives each tenant its own copy, at the cost of higher memory usage and a lower cache hit rate, but provides isolation.

Implementation in transformers

transformers lets you prefill a prompt once and reuse the resulting cache across multiple different continuations.

python
import copy
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, StaticCache

model_id = "HuggingFaceTB/SmolLM2-360M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, dtype=torch.bfloat16, device_map="auto"
)

SHARED_PREFIX = """You are a careful assistant. 
                   Answer in one short sentence."""

prompt_cache = StaticCache(config=model.config, max_cache_len=1024)

prefix_inputs = tokenizer(SHARED_PREFIX, return_tensors="pt")
prefix_inputs = prefix_inputs.to(model.device)


# Prefill the shared prefix exactly once. No token is sampled here.
with torch.no_grad():
    prompt_cache = model(**prefix_inputs, past_key_values=prompt_cache)
    prompt_cache = prompt_cache.past_key_values

questions = ["What is the capital of France?", "Name one ocean."]

for question in questions:
    inputs = tokenizer(SHARED_PREFIX + question, return_tensors="pt")
    inputs = inputs.to(model.device)

    # each request gets its own copy
    past_key_values = copy.deepcopy(prompt_cache)   

    outputs = model.generate(
        **inputs, past_key_values=past_key_values, do_sample=False
    )
    print(tokenizer.decode(outputs[0], skip_special_tokens=True))
  • Use StaticCache rather than DynamicCache because we need a fixed allocation that can be copied and passed along.

  • The model (...) call performs the prefill. No tokens are sampled here. We run the shared prefix through the model solely to populate the cache, then retain the returned past_key_values.

  • Inside the loop, each question is appended to the same prefix. The entire string is tokenized, so the token IDs for the prefix are identical every time—exactly the condition the engine’s hash chain checks for.

  • copy.deepcopy gives each request its own copy of the prefilled cache. Generation modifies the cache in place by appending to it, so without a copy, the first question would corrupt the prefix cache for the second. Production engines do not copy tensors. Instead, they share physical blocks and track reference counts, making reuse almost free rather than incurring a cost proportional to the prefix length.

The impact of eviction on hit rate

As noted above, only complete blocks are indexed, so partial blocks at the tail are recomputed every time.

This means the block size needs to be tuned appropriately.

  • Larger blocks mean fewer table lookups and better memory locality.

  • Smaller blocks mean finer-grained sharing and less waste at the tail.

Eviction reduces the hit rate, as expected.

The cache and active batches share the same GPU memory pool, so a larger cache means fewer concurrent sequences. Under memory pressure, vLLM evicts unreferenced blocks on a least-recently-used basis.

Mixed traffic makes this worse because long shared prefixes occupy the most blocks, and losing those blocks has the greatest impact.

Before enabling this feature, you should understand two things.

  • It only saves work during prefill, so decoding time remains unchanged. Attributing the entire speedup to caching overstates its benefits.

  • Hash computation also has overhead, so benchmarks on traffic with entirely different prompts often show a drop in throughput rather than an improvement.

There is also a third, workload-dependent issue that affects RAG the most.

RAG prompts contain system instructions, followed by retrieved chunks, and finally the query. Those chunks change with each request, and their order varies across requests. With chained hashing, two requests that retrieve the same documents in different orders share nothing at all.

Prefilling each chunk separately and stitching the caches together does not work.

The concatenated tensors carry incorrect positional encodings. None of the chunks has ever attended to the others. And each chunk contributes its own attention sink at what the model considers position zero. Making this work requires partial recomputation at the boundaries, not simple concatenation.

Incidentally, a solution already exists in the open-source community.

LMCache (open source) implements CacheBlend. Rather than concatenating chunk caches end to end, it reuses them at arbitrary positions and recomputes only a small fraction of tokens, selecting the positions where precomputed values deviate most from what full attention would have produced.

That small fraction restores cross-chunk attention and corrects positional encodings, preserving the output quality of full prefill.

Compared with recomputing everything, this reduces time to first token by roughly a factor of two to three, with recomputation pipelined alongside fetching cached chunks from slower storage.

It integrates with vLLM and reads chunk boundaries from your prompts, enabling cache reuse for retrieval workloads even when the retrieved documents appear in a different order each time.

Repository: https://github.com/LMCache/LMCache


3) Prompt caching

With hosted models, you do not have access to block tables or eviction policies. Instead, you get a pricing schedule based on the provider’s own prefix reuse, plus two control knobs.

The cached objects are still KV tensors, not your prompt text, and caching still requires an exact prefix match on the fully rendered context.

The rendered context includes provider-side system content you never wrote, which is one reason minimum-length requirements and invalidation rules can seem arbitrary from the outside.

Here is a code example demonstrating prompt caching:

python
import anthropic

client = anthropic.Anthropic()   # reads ANTHROPIC_API_KEY from the environment

# Must clear the model's minimum cacheable length or nothing is cached at all.
LONG_INSTRUCTIONS = "You are a precise technical editor. " * 400

def ask(question: str):
    return client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=512,
        system=[
            {
                "type": "text",
                "text": LONG_INSTRUCTIONS,
                "cache_control": {"type": "ephemeral"},   # everything above is cacheable
            }
        ],
        messages=[{"role": "user", "content": question}],
    )

for question in ["Summarize section 3.", "Now rewrite it for a beginner."]:
    resp = ask(question)
    u = resp.usage
    print(
        f"write={u.cache_creation_input_tokens} "
        f"read={u.cache_read_input_tokens} "
        f"uncached={u.input_tokens}"
    )


# Output:
"write=2823  read=0     uncached=14"
"write=0     read=2823  uncached=17"

Only one line in that code deals with caching.

Where you place cache_control determines which part of the request is written to a cache entry, and the usage counters tell you whether subsequent calls read that entry back.

  • The marker is attached to the last block you want to include, rather than to a range. It writes a cache entry covering everything from the start of the request through that block, inclusive.

  • The user message sits below the marker, keeping it outside the cached region. Because it changes with each call, it cannot be part of that region.

  • The usage counters tell you what happened internally. The first call reports nonzero cache_creation_input_tokens and zero reads. The second shows the reverse, with the instructions billed at one-tenth of the input rate.

  • If both counters return zero, the prefix is below the model's minimum cacheable length, and the request is processed without caching. This does not trigger an error.

Intuitively, as discussed above, if we move cache_control down to the user message, the read counter will always be zero because the marked block changes with every call.

The economics of prompt caching

Anthropic charges 1.25 times the base input rate to write an entry and 0.1 times that rate to read it. If you want the entry to persist longer, the write multiplier is higher. OpenAI uses the same two multipliers on its current models.

The premium is recouped on subsequent requests, because anything reused within the TTL avoids recomputation.

A read can only find an entry written by a previous request, and writes occur only at the breakpoints you place.

Each call checks your breakpoint. If there is no cache hit, it searches backward through a limited number of blocks for an earlier write.

Anthropic limits this lookback to 20 blocks, so adding more than 20 blocks to a conversation between calls puts the last write out of range, and cache hits stop.​


4) Semantic caching

The three techniques above save prefill work but still run the model.

Semantic caching embeds the incoming prompt, performs a nearest-neighbor search against stored prompts, and returns the stored response directly when the similarity exceeds a threshold.

This is why it saves both output tokens and input tokens. It is also why every request requires an embedding round trip, including every cache miss.

Here is a runnable semantic caching demo implemented in just a few lines of code:

python

# requires: pip install sentence-transformers
import numpy as np
from sentence_transformers import SentenceTransformer

encoder = SentenceTransformer("all-MiniLM-L6-v2")

class SemanticCache:
    def __init__(self, threshold=0.95):
        self.threshold = threshold
        self.vectors = np.empty((0, encoder.get_sentence_embedding_dimension()))
        self.prompts, self.responses = [], []

    def _embed(self, text):
        return encoder.encode([text], normalize_embeddings=True)[0]

    def lookup(self, prompt):
        vec = self._embed(prompt)
        if len(self.prompts) == 0:
            return None, 0.0, vec
        scores = self.vectors @ vec           # cosine sim, vectors are unit length
        best = int(np.argmax(scores))
        if scores[best] >= self.threshold:
            return self.responses[best], float(scores[best]), vec
        return None, float(scores[best]), vec

    def store(self, prompt, response, vec):
        self.vectors = np.vstack([self.vectors, vec])
        self.prompts.append(prompt)
        self.responses.append(response)

cache = SemanticCache(threshold=0.95)

def answer(prompt, call_model):
    hit, score, vec = cache.lookup(prompt)
    if hit is not None:
        return hit, f"HIT  (score {score:.3f})"
    response = call_model(prompt)             # the expensive path
    cache.store(prompt, response, vec)
    return response, f"MISS (best {score:.3f})"


# Stand in for the model so this runs without an API key.
fake_model = lambda p: f"<answer for {p!r}>"

for q in ["How do I reset my password?",
          "How can I reset my password?",
          "Is the API rate limited?"]:
    _, status = answer(q, fake_model)
    print(f"{status}  {q}")

# Output:
"MISS (best 0.000)  How do I reset my password?"
"HIT  (score 0.961)  How can I reset my password?"
"MISS (best 0.112)  Is the API rate limited?"

Each method in the class above corresponds to a decision you must make in production:

  • normalize_embeddings=True makes every vector unit length, allowing self.vectors @ vec to compute cosine similarity as a simple dot product. If you skip normalization, scores cannot be compared across prompts of different lengths.

  • The lookup returns the embedding vector along with the result, so it can be stored with the answer later without recomputing the embedding. This matters because you pay for embeddings on every request, whether it is a hit or a miss. Computing them twice doubles the cache's baseline cost.

  • A brute-force argmax is fine for a demo, but it is the wrong approach at scale. Once you exceed a few thousand entries, you need an approximate nearest-neighbor index, which introduces its own recall settings in addition to the similarity threshold.

  • store is called only on the miss path, after the model answers. There is no validation before that answer becomes the response to every future prompt whose similarity exceeds the threshold. This highlights the technique's biggest risk. The cache does not know whether the stored response is correct; it only knows whether the new prompt resembles an old one.

The following code illustrates that last point:

python
pairs = [
    ("How do I reset my password?", "How can I reset my password?"),
    ("Is the API rate limited?",     "Is the API not rate limited?"),
    ("Refund policy for annual plans", "Refund policy for monthly plans"),
]

for a, b in pairs:
    va, vb = encoder.encode([a, b], normalize_embeddings=True)
    print(f"{float(va @ vb):.3f}   {a!r}  vs  {b!r}")

Here is the output we get:

python
0.961   'How do I reset my password?'  vs  'How can I reset my password?'
0.952   'Is the API rate limited?'  vs  'Is the API not rate limited?'
0.887   'Refund policy for annual plans'  vs  'Refund policy for monthly plans'
  • The first pair consists of genuine paraphrases and should share an answer.

  • The second pair differs by a single negation and requires opposite answers.

  • The third pair differs in one operational parameter and requires different answers.

Despite these mismatches, all three pairs score very similarly. The gap between the paraphrase pair and the negation pair is less than one hundredth of a point—too narrow to hold up reliably under real-world traffic.

  • If you raise the threshold, the hit rate drops, yet you still pay for embeddings on every call.

  • If you lower the threshold, the hit rate rises, along with the rate of confidently delivered wrong answers.

  • Published defaults range from 0.75 to 0.97 depending on the source, which tells you that the right threshold is a property of your own traffic, not a value you can simply copy.

This technique is inherently less than fully reliable: some failures, such as those shown above, can slip past any threshold because they stem from what the embeddings represent.


Recap of all four techniques

Three of the four techniques above are correctness-neutral: their misses affect only cost and latency, not anything else.

Semantic caching works differently, so hit rate is not the right metric to report here.

There is also a fifth, less commonly used layer: exact-match response caching, which returns a stored answer when the request is byte-for-byte identical. Like semantic caching, it saves on both input and output, but without the risk of false positives because it does no similarity matching at all. Before considering embeddings, simply measure the rate of byte-for-byte identical requests. Of course, there are some caveats, which you may already be thinking of. Share them in the replies.


Takeaways for production

Every technique has failure modes you should be aware of before using it in production:

  • Any variable at the start of a prompt—such as a timestamp, request ID, or username in the system prompt—invalidates all subsequent blocks. Always put stable content first and variable content last, with a marker at the boundary.

  • Tool schemas are typically placed before the system prompt, so reordering them invalidates the entire cache.

  • Check which settings are rendered into the prompt. On Anthropic, changing web search, citations, thinking configuration, or tool_choice rewrites the prompt text and invalidates downstream blocks. A/B testing two reasoning effort levels splits your cache in two.

  • Summarizing the conversation history rewrites the prefix, so the next call is charged at the full uncached token rate. Truncating tool outputs in place keeps the prefix bytes identical, preserving cache validity.

  • Cache entries are tied to a model, so routing to a cheaper model still requires prefilling the entire accumulated history at the uncached rate.

To pinpoint exactly where two prompts stop matching, compare their token IDs directly rather than comparing the text you logged. Here is an example:

python
messages_turn_1 = [{"role": "user", "content": "What is the capital of France?"}]
messages_turn_2 = [{"role": "system", "content": "Today is Tuesday."},
                   {"role": "user", "content": "What is the capital of France?"}]


# tokenize=True is the default and returns a plain list of token ids
a = tokenizer.apply_chat_template(messages_turn_1)
b = tokenizer.apply_chat_template(messages_turn_2)

shared = 0
for x, y in zip(a, b):
    if x != y:
        break
    shared += 1

print(f"shared prefix: {shared} tokens of {len(a)} and {len(b)}")
print(f"first divergence at index {shared}: {a[shared:shared+8]} vs {b[shared:shared+8]}")

# Output:
"""
shared prefix: 3 tokens of 35 and 26
diverges at index 3
  turn 1: [2683, 418, 253, 11173, 9042, 14260] You are a helpful AI assistant
  turn 2: [11814, 314, 27758, 30, 2, 198] Today is Tuesday.<|im_end|>
"""

Two prompts that look identical in your logs may differ because of a beginning-of-sequence (BOS) token, a trailing newline, or a reserialized tool schema.

Comparing token IDs rather than rendered text reveals the exact index where reuse stops, and decoding a few IDs on either side usually reveals the exact text responsible.

The run above illustrates a common case.

Turn one specified no system message, so the chat template filled in the model’s default. The two prompts diverged at index 3, preventing reuse.


The first three layers apply one idea at three different scopes.

  • KV caching preserves attention state only for the duration of a single request.

  • Prefix caching preserves that state after the request ends so subsequent requests can look it up.

  • Prompt caching is prefix caching run by a provider on its own hardware, with a separate rate for the portion you reuse.

Semantic caching works differently. It stores response text keyed by embedding similarity, so a cache hit bypasses the model entirely, saving output tokens as well as input tokens. A hit can also be wrong—and when it is, it still returns a normal success status.

Your turn: Which of these four layers has cost you the most debugging time?


That’s it!

If you enjoyed this tutorial:

Find me → @_avichawla

Every day, I share tutorials and insights on DS, ML, LLMs, and RAG.