Inference Engineering

Lesson 8: Prefix caching · Workbook

Prefix caching: the workbook

The full working behind lesson 8. Why only a prefix can be reused, what a cache hit saves in arithmetic and in time, how SGLang's radix tree and vLLM's chained block hashes find the match, the rules for laying out a prompt, and seven exercises to check yourself.

Why prefix caching exists

Many requests to an LLM server start with the same text. A support bot sends the same system prompt before every customer’s question. An agent sends the same tool definitions on every step. A chat app resends the whole conversation each turn, so turn ten begins with turns one through nine. Without help, the server runs prefill over all of that shared text again for every request.

Prefill is the phase that turns the prompt into a KV cache, the stored keys and values each later token attends to (see Prefill and decode and The KV cache). If two prompts begin with the same tokens, the KV cache for those tokens is identical, so the server can compute it once, keep it, and hand it to the next request that starts the same way. That is prefix caching. On Llama 3.1 8B on an H100, it cuts the prefill floor for a 2,100-token prompt whose first 2,000 tokens are cached from 30.8 ms to 4.59 ms.

The rule that makes it work is strict: the reused part must be a prefix, matching the new prompt token for token from the very first token. This lesson explains why, then shows the two data structures servers use to find the match.

Why only a prefix

Recall what a transformer layer stores for a token. The key and value of token ii in layer ℓ\ell are projections of that token’s hidden state coming into the layer:

Ki(ℓ)=RoPEi ⁣(WK(ℓ)hi(ℓ−1)),Vi(ℓ)=WV(ℓ)hi(ℓ−1)K_i^{(\ell)} = \mathrm{RoPE}_i\!\left(W_K^{(\ell)} h_i^{(\ell-1)}\right), \qquad V_i^{(\ell)} = W_V^{(\ell)} h_i^{(\ell-1)}

In the first layer, hi(0)h_i^{(0)} is just the embedding of token ii, so KK and VV depend on the token and on its position ii (the rotary position encoding, RoPE, rotates each key by an angle set by ii). From the second layer on, hi(ℓ−1)h_i^{(\ell-1)} is the output of attention and the MLP in the layer below, and attention mixed in every earlier token 1,…,i1, \dots, i. So for every layer after the first:

Ki(ℓ), Vi(ℓ)  =  f(x1,x2,…,xi)K_i^{(\ell)},\ V_i^{(\ell)} \;=\; f\big(x_1, x_2, \dots, x_i\big)

Three consequences follow, and they set the rules for everything else in this lesson.

So matching is a longest-common-prefix problem over token ids: walk both sequences from the start and stop at the first mismatch. Note “token ids”, not characters. Changing one space can change how the tokenizer splits the text around it, which can shift every later token.

What a hit saves

A prompt of nn tokens with the first cc cached only needs to run the n−cn - c new tokens through the model. Each new token still attends to all earlier tokens, cached or not, so attention reads the cached keys and values. What disappears is the work for the cached tokens themselves.

Prefill FLOPs come from two places (see What one token costs). The weight matrix multiplies cost 2P2P FLOPs per token, where PP is the number of weights in the layers. Attention costs 4LHdh4 L H d_h FLOPs per query-key pair, with LL layers, HH query heads and head size dhd_h; with causal masking, token ii forms ii pairs. Removing the first cc tokens removes

Fsaved  =  2 P c  +  4 L H dh⋅c (c+1)2F_{\text{saved}} \;=\; \htmlClass{c-compute}{2\,P\,c} \;+\; \htmlClass{c-compute}{4\,L\,H\,d_h \cdot \frac{c\,(c+1)}{2}}

For Llama 3.1 8B, PP is about 6.98 billion: the matmul weights in its 32 layers, not counting the embedding table or the LM head (the final matrix that turns a hidden state into scores over the vocabulary). The LM head’s 0.53 billion weights run only for the last prompt token, since only that token’s scores are needed.

The second term grows with the square of the cached length, so long shared prefixes save more than their length suggests.

For the 2,100-token prompt above, the hit removes 29.0 TFLOP of the 30.5 TFLOP a full prefill needs. The time saved is smaller in proportion, and the reason is the roofline from lesson 1. With 100 new tokens, the matmul intensity is about 93 FLOPs per byte (not 100, because the LM head’s weights are read but used by only one token), below the H100’s ridge, so the step is memory-bound: it still has to read all 15.0 GB of weights once, which takes at least 4.48 ms. The cached prefill sits just above that floor, at 4.59 ms. A short new suffix costs about one weight read plus one read of the cached KV. At 131,072 bytes per token, the KV read is small next to 15.0 GB of weights for a few thousand cached tokens. With 100,000 cached tokens it is 13.1 GB, about as large as the weights, and the same 100-token suffix takes 9.78 ms, roughly double the weight floor.

That is why the saving grows with the prefix. With 8,000 cached tokens and 100 new ones, the floor drops from 132 ms to 4.91 ms, about 27 times faster; with 32,000 cached, 726 ms becomes 6.18 ms. These are floors for one request on an idle GPU. Under load, prefill competes with other requests’ decode steps (covered later in Chunked prefill and disaggregation), and every FLOP not spent on a cached prefix is a FLOP available to someone else.

One detail: even when the whole prompt is cached, the last prompt token must still run through the model. The cache holds keys and values, not the final hidden state that produces the scores for the first output token.

Memory, too

Reuse saves memory as well as compute. With paged KV memory, several running requests can point at the same physical pages for their shared prefix. A 2,000-token prefix on Llama 3.1 8B in BF16 takes 262 MB of KV cache (131,072 bytes per token). Sixty-four concurrent requests holding their own copies would need 16.8 GB; sharing one copy frees 16.5 GB for more requests in the batch.

Multi-turn chat

Chat is where prefixes come for free. Each turn’s prompt is the previous turn’s prompt plus the model’s answer plus the new user message. Take a 2,000-token system prompt, 50-token user messages and 250-token answers. Over 10 turns, a server without prefix caching prefills 34,000 tokens. A server that keeps every turn’s cache, including the generated answers, prefills only the system prompt and the ten user messages: 2,500 tokens. The gap grows with the square of the number of turns, because each turn’s prompt is longer than the last.

A radix tree: SGLang’s RadixAttention

A server needs a structure that answers one question quickly: of everything I have cached, what is the longest prefix of this new prompt? SGLang’s answer, called RadixAttention in Zheng et al. (2024), is a radix tree.

A trie (prefix tree) stores sequences so that sequences sharing a prefix share the path from the root: one edge per token. A radix tree is a compressed trie: an edge holds a whole run of tokens, and a node splits only where stored sequences diverge. In SGLang, each edge’s tokens point at the KV cache for those tokens, stored in a paged layout where, in the paper’s words, the size of each page is one token. So a match can end at any token.

The operations are what you would expect:

The cache has no fixed size in SGLang: cached tokens and running requests share one memory pool, and the cache shrinks when the batch needs room.

Try it below. The buttons send requests, one after another, to a server running Llama 3.1 8B on an H100 that starts with an empty cache. A long block like “system prompt and tool definitions” stands for 2,000 tokens; ordinary words are one token each (real tokenizers split text differently, but the matching logic is the same). It sends “Capital of France”, then “Capital of Japan”, a follow-up, “One word edited” and “Date put first” by itself; press any request to take over.

A server's radix tree, request by request

reused: its cards were on the shelf run for this request cached, not used

The cache is empty. Send a request.

Each row is a node of the radix tree; indentation shows its parent. Rows marked reused (teal) were matched by the last request and their KV cache reused; rows marked run (amber) were computed for it. The timings are the prefill floor from the roofline model, the same lower bound as lesson 1. In this figure only prompts are inserted; a real server also inserts each generated answer.

The sequence above shows the rules in action. “Capital of France” fills the empty cache with 2,007 tokens. “Capital of Japan” matches 2,006 of them: the system prompt plus “User: What is the capital of”. The tree splits after “of” and adds one new token.

“One word edited” changes a single token at position 41 of the system prompt. The match stops after 40 tokens. From the edited token on, everything is new to the tree: 1,967 tokens, and all of them except the edited one are the same text as before. “Date put first” puts a changing value at the top, so it matches 0 tokens and stores a second full copy of the system prompt.

For image inputs, SGLang fills the image’s token positions with values derived from a hash of the image, so two prompts match through an image only if it is the same image.

SGLang also orders the waiting queue to raise the hit rate: requests with longer cached prefixes run first, so a shared prefix is reused before it can be evicted. The paper reports cache hit rates of 50% to 99% on its benchmarks, with this cache-aware scheduling reaching 96% of the optimal hit rate on average. In a month of serving on Chatbot Arena, it measured hit rates of 52.4% for LLaVA-Next-34B and 74.1% for Vicuna-33B, and an average 1.7× cut in first-token latency for Vicuna-33B. Across its workloads, which also exercise SGLang’s other optimizations, it reports up to 6.4× higher throughput than the systems it compares against.

Chained block hashes: vLLM’s automatic prefix caching

vLLM already stores the KV cache in fixed-size blocks of tokens (see Paged KV memory). The PagedAttention paper (Kwon et al., 2023, Section 4.4) described sharing a prefix by having the service provider reserve blocks for a set of predefined prefixes. On a translation workload with a shared few-shot prefix, it reported 1.67× higher throughput than Orca, an earlier serving system (in its “Oracle” variant, which is assumed to know each request’s output length in advance), with a one-example prefix and 3.58× with a five-example prefix. Automatic prefix caching removes the need to declare prefixes: vLLM finds them on its own, with a hash table instead of a tree.

The idea is to give each full block a name that identifies the whole prefix up to the end of that block. vLLM’s design docs list what goes into each block’s hash:

Because each hash includes the previous one, two blocks get the same hash only if their tokens match and everything before them matches. The prefix rule is built into the name. To serve a new request, vLLM computes its block hashes in order and looks each one up in a table of cached blocks. The first miss ends the match. Each block counts the running requests that use it. When the count drops to zero the block goes to a free queue but keeps its hash, so it still serves as cache until a new allocation reaches it; the queue is ordered so the least recently used block is evicted first. When a request finishes, its blocks join the free queue in reverse order, so the end of a sequence, the part least likely to be shared, is evicted first.

The docs state one more rule plainly: only full blocks are cached. The trailing partial block of a prompt has no hash, so it is never shared. That makes reuse block-granular. With a block size of 16, “Capital of Japan” after “Capital of France” shares 2,006 tokens, but a block cache reuses only 2,000, and the edited system prompt shares 40 but reuses 32. A few tokens are recomputed per request in exchange for a flat hash table instead of a tree.

The figure below uses real chained hashes on one-word tokens (with a small 53-bit hash; vLLM’s docs give SHA-256 as the default). Edit request B and watch the first changed word turn its block and every block after it pink. Then add or remove words at the end of B and watch its last block switch between full and partial.

Request A

    Request B

      hash found in cache hash not found partial block, no hash

      Each box is one block. Its hash covers the previous block's hash and its own tokens, so a block can only match if every block before it matched. The last block of a prompt is not cached unless it is full.

      The two designs side by side

      Both designs compute the same thing: the longest cached prefix of the new prompt. They differ in bookkeeping.

      SGLang RadixAttentionvLLM automatic prefix caching
      StructureRadix tree of token sequencesHash table keyed by chained block hashes
      Match granularityAny token (one-token pages)Whole blocks; partial blocks not cached
      EvictionLeast recently used leafLeast recently used free block, sequence ends first
      ImagesImage hash stands in for the image’s tokens in the treeImage hash mixed into each block’s hash

      Practical rules

      These follow from the prefix rule, and they apply to any server that does prefix caching.

      Prefix caching does not change the model’s output. vLLM’s docs describe it as almost a free lunch for that reason: the reused keys and values are the ones the server would have computed anyway.

      Check yourself

      Every answer below uses Llama 3.1 8B in BF16 on one H100, with the same formulas as the figures.

      Exercise 1. A new 3,000-token prompt matches a cached one except at token 500, where one word differs. How many tokens can a radix tree with one-token pages reuse? How many can a block cache with 16-token blocks reuse? Enter the block-cache figure.

      tokens
      Show the worked answer

      The match covers tokens 1 to 499, so the radix tree reuses 499. The block cache reuses only whole blocks before the mismatch: 496. Tokens 501 to 3,000 are recomputed in both cases, even though they match the cached text, because their history differs.

      Exercise 2. A template puts a 10-token timestamp at the top of a 4,000-token system prompt, followed by a 100-token user message. What is the prefill floor? What if the timestamp moves to just before the user message? Enter the timestamp-first floor in ms.

      ms
      Show the worked answer

      With the timestamp first, every request differs at token 1, so nothing is reused. The full prefill is 2 × 6.98 billion × 4,110 FLOPs for the layer matmuls, plus the LM head for the last token and attention, which comes to 61.8 TFLOP. At 989 TFLOP/s the floor is 62.5 ms. With the timestamp after the system prompt, the first 4,000 tokens are shared and only 110 are new: 4.72 ms. Same tokens, same information, about 13 times faster.

      Exercise 3. A 20-turn chat has a 1,000-token system prompt, 100-token user messages and 400-token answers. How many tokens are prefilled in total without prefix caching, and with an ideal cache that keeps every answer? Enter the total without prefix caching.

      tokens
      Show the worked answer

      Without the cache, turn kk prefills 1000+500(k−1)+1001000 + 500(k - 1) + 100 tokens, which sums to 117,000. With the cache, only the system prompt and the 20 user messages are prefilled: 3,000, about 39 times fewer.

      Exercise 4. Thirty-two requests run at once, all starting with the same 3,000-token prefix. How much KV memory does the prefix take with and without sharing? Enter the total without sharing, in GB.

      GB
      Show the worked answer

      One copy is 3,000 × 131,072 bytes = 393 MB. Thirty-two private copies take 12.6 GB, so sharing frees 12.2 GB, room for many more requests’ own tokens.

      Exercise 5. A 2,100-token prompt has its first 2,000 tokens cached, so only 1/21 of the tokens are new. Why is prefill not 21 times faster?

      Show the answer

      The floor drops from 30.8 ms to 4.59 ms, about 6.7 times. One hundred tokens per weight matrix is below the H100’s ridge point, so the step is memory-bound: it must still read all 15.0 GB of weights once, at least 4.48 ms. On an idle GPU, the FLOPs saved can’t all turn into time, because the weight read sets a floor. In a busy server the same weight read also serves other requests in the batch, so the FLOPs the hit skipped are freed for them.

      Exercise 6. From lesson 1: the H100 does 989 TFLOP/s in BF16 and reads 3.35 TB/s from memory. What is its ridge point, the arithmetic intensity below which a step waits on memory?

      FLOPs per byte
      Show the worked answer

      About 295 FLOPs per byte: 989 × 10¹² ÷ 3.35 × 10¹². A cache hit that leaves 100 new tokens runs its matmuls at about 93 FLOPs per byte, far below the ridge, which is why the hit in this lesson lands just above the 4.48 ms weight-read floor instead of being 21 times faster.

      Exercise 7. From lesson 7: with vLLM's 16-token blocks, how many KV blocks does one 2,100-token prompt occupy?

      blocks
      Show the worked answer

      132: 2,100 ÷ 16 = 131.25, rounded up, because a block is allocated whole. 131 blocks are full and the last holds 4 tokens. In vLLM’s prefix cache only full blocks get a hash, so at most 2,096 of these tokens can be shared with a later request. If it starts at token 0, Parrot’s 2,000-token system prompt is exactly 125 whole blocks, so all of it can be shared.

      Sources

      1. Zheng, Yin, Xie, Sun, Huang, Yu, Cao, Kozyrakis, Stoica, Gonzalez, Barrett, Sheng (2024). SGLang: Efficient Execution of Structured Language Model Programs. NeurIPS 2024. arXiv:2312.07104. Section 3 introduces RadixAttention; Section 6.2 reports cache hit rates and the Chatbot Arena deployment
      2. vLLM documentation. Automatic Prefix Caching (design). Block hashing, the full-blocks-only rule, extra keys and LRU eviction
      3. Kwon, Li, Zhuang, Sheng, Zheng, Yu, Gonzalez, Zhang, Stoica (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. SOSP 2023. arXiv:2309.06180. Section 4.4 (shared prefix) and Section 6.4 (shared-prefix evaluation)
      4. Llama 3.1 8B model card (Meta). The model used for every timing in this lesson
      5. NVIDIA H100 product page, specifications table. 989 TFLOP/s BF16 dense, 3.35 TB/s

      Back to lesson 8: Prefix caching