AI Coding Agents
KV cache prefix caching explained for LLM workloads
A KV cache stores the key and value tensors that a model computes for previous tokens at each attention layer. In a causal transformer, later tokens can use those tensors, and a separate request can reuse them for an identical starting sequence when the engine still has a matching entry. The memory cost scales with the number of tokens retained.
What prefill writes and decode reads
During prefill, the model makes a forward pass over the input tokens. In an attention layer, the token representations are projected into queries, keys, and values. A query participates in choosing which earlier positions to attend to. Keys supply the representations the query is compared against, and values supply the information that gets combined into the attention result. The model performs this work in successive attention layers, so the stored state includes keys and values for those layers.
During decode, the model generates subsequent tokens one at a time. Its current token can attend to the keys and values from prior positions without recreating those projections for every step. The stored tensors also include keys and values produced during generation, since a later output token can attend to the ones generated before it. For the relationship between these two phases, see what is LLM inference.
Prefix caching uses that same kind of state across requests. Imagine an agent whose next inference call includes a long set of instructions, earlier messages, and a new tool result. If the engine can reuse state for those instructions and messages, the new result still has to be processed and the model still has to generate its answer. At a hosted API the exact billing boundary depends on the product. OpenAI’s guide, as of November 30, 2026, identifies its stored cache state as KV tensors and distinguishes billed cache reads from writes on supported models.
Why the matching span starts at the beginning
The SGLang paper explains that KV cache computation depends only on prefix tokens, a consequence of causal attention. While processing a position, the model uses the tokens up to that position. It can process the same prefix with different continuations because nothing in a continuation feeds backward into the earlier positions. That makes a prefix a reusable piece of forward-pass state. A matching fragment farther into two otherwise different requests can have different prior context, so equality of that fragment alone gives the engine insufficient grounds to reuse its precomputed state.
Consider two agent requests assembled from the same instructions, project summary, and conversation history. Both append the exact same test log. One updates a line in the project summary first. When the summary changes, the subsequent copies of the conversation history and test log now follow different tokens. An engine that does exact prefix matching can retain a match through the unchanged beginning. Everything after the divergence is evaluated with the new context.
For a second example, leave the project summary in place and append a new message describing the requested change. If the token sequence through the previous endpoint stays identical, it is still a candidate for reuse. This is why the placement of a timestamp or branch name can have a disproportionate effect. A change near the front can shorten the candidate prefix across every later turn. A change at the end leaves a longer candidate. Actual reuse still depends on the engine’s lookup boundaries and the entries available when the request arrives.
How much memory each retained token takes
For standard multi-head or grouped-query attention, use this formula to estimate the raw KV payload per token.
KV bytes per token = 2 × layers × KV heads × head dimension × bytes per element
The leading factor counts the key and the value. Meta’s Llama 3.1 model card identifies grouped-query attention, where multiple query heads share each KV head. The Llama 3.1 8B example counts eight KV heads for the stored tensors. Multiply by the number of retained token positions to estimate the payload for a sequence. The arithmetic models the tensors in that layout and precision. For device sizing, leave room for the rest of the model and runtime, as described in what is VRAM for LLMs.
| Quantity | Llama 3.1 8B example | Role in the estimate |
|---|---|---|
| Tensors per layer | 2 | One key and one value |
| Layers | 32 | Each layer contributes its share of the state |
| KV heads | 8 | Counts the heads represented in the cached tensors |
| Head dimension | 128 | Elements per head |
| Bytes per element | 2 in bf16 | Storage for each element |
| Payload per token | 131,072 bytes, or 128 KiB | Product of the factors above |
Together AI’s Llama 3.1 8B example gives 128 KiB per token. At that rate, an illustrative retained prefix of 8,192 tokens occupies 1 GiB of raw KV payload. If several agent branches share that entire prefix and the engine retains one common copy, they can share that 1 GiB. Each branch still needs storage for its own divergent positions. A set of unrelated sessions of the same length needs a separate payload for each distinct prefix. The useful capacity question is how many distinct token positions stay resident under the traffic you actually serve.
Use the formula to compare two versions of the same workload by multiplying each version’s retained token count by the same per-token footprint. Models using multi-head latent attention (MLA), sliding-window attention, or quantized KV need their own estimates. With a sliding window, check how many positions the engine retains per layer before multiplying by the full history length. With quantized KV, use the cache’s storage format, including any quantization metadata, when estimating the footprint. For MLA, size the cache from the shapes the runtime actually stores. On a multi-GPU run, also check how storage is distributed. The SGLang paper describes a tensor-parallel configuration in which each GPU stores a shard of the KV cache, so the sequence-level estimate describes the combined payload in that configuration.
How engines find and reclaim the state
While requests are running, the engine needs memory for active sequences. It can also keep state from finished work available for the next matching request. Retained entries compete for memory when new requests arrive. That competition explains why an unchanged prefix can miss in a self-hosted system even when it hit earlier in the same run.
vLLM looks up full blocks by hash, while the SGLang paper describes following token sequences through a radix tree. The vLLM and SGLang comparison explains how those designs affect branching workloads and eviction.
Eviction and divergence lead to different fixes. A divergence introduced at request assembly can repeat every time the same prefix is constructed with a changing field. An eviction can depend on what else the server processed in the interim. To separate them in a controlled run, verify the prompt representation first, then repeat the same request with and without competing traffic and compare the cached token counts. For a vLLM run, divide the increase in vllm:prefix_cache_hits by the increase in vllm:prefix_cache_queries. For individual chat or completion requests, start vLLM with --enable-prompt-tokens-details to get usage.prompt_tokens_details.cached_tokens. In streaming tests on those endpoints, also request usage with stream_options.include_usage. The Responses endpoint reports usage.input_tokens_details.cached_tokens directly.
Why you should check token IDs near a split
NVIDIA documents a separate optimization in TensorRT-LLM called the prefix-tokenization cache. It reuses previously computed token IDs in order to do less tokenization work. The documentation explains that byte-pair encoding merges can cross the split between a cached beginning and a newly tokenized ending. Tokenizing the ending by itself can therefore produce different IDs from tokenizing the full prompt.
TensorRT-LLM backs up from the candidate split and tokenizes again around the join. It checks the token IDs where the pieces overlap and uses full tokenization when the splice fails validation. This is behavior documented for TensorRT-LLM’s tokenization cache. For an engine you control, the practical diagnostic step is to tokenize each complete input, then compare the resulting IDs when a text diff shows only a suffix edit. Treat any conclusion about a hosted provider’s cache as specific to what that provider documents or what its response reports.
What changes when KV moves off the GPU
A cache can keep more state by storing it outside GPU memory. LMCache describes a hierarchy spanning CPU memory, local storage, and remote backends. Such a tier can serve a matching prefix that is no longer resident on the GPU. Mooncake describes a disaggregated serving design that separates prefill and decode, with a KV pool that draws on CPU, DRAM, and SSD resources. Its transfer infrastructure moves tensors between workers, and Mooncake Store provides distributed storage.
The raw payload estimate helps size a transfer as well as a cache. If a worker needs to fetch the entire illustrative 8,192-token prefix, each such fetch moves 1 GiB of tensor data at the example precision before accounting for any transport overhead or compression. Several workers fetching different prefixes at once can contend for bandwidth even when the storage layer can retain every entry. When sizing an offload tier, estimate how much KV data workers need to fetch during the busiest part of a replay and compare that with the transfer volume the tier can sustain.
Check the match before adding capacity
- Start with two consecutive requests and locate their longest shared prefix. For your own engine, compare token IDs across the entire inputs. Use the prefix diff guide to trace an early divergence to the component building the request.
- Estimate the raw payload of that prefix and the distinct suffixes of concurrent branches. Compare it with your available KV capacity under representative load.
- Repeat a known matching request while changing the volume of unrelated work. That isolates pressure on retained entries from changes to prompt assembly.
- When testing another engine or storage tier, record cached input tokens and time to first token together. Use the cache hit rate guide to make the denominator consistent across runs.
For a hosted API, use the provider’s usage counters for the invoice and use the memory calculation to understand the serving constraint. The model’s tensor footprint explains why the server has to make room for new work. The usage record tells you whether the service billed a read, a write, or ordinary input for your request.
Sources
- SGLang paper, §3 and Appendix A (Zheng et al., accessed 2026-11-30)
- Prompt Caching 201 (archived) (OpenAI, accessed 2026-11-30)
- KV cache explained (Together AI, accessed 2026-11-30)
- Automatic Prefix Caching feature guide (vLLM, accessed 2026-11-30)
- Prefix caching design (vLLM, accessed 2026-11-30)
- Prefix-tokenization cache (NVIDIA, accessed 2026-11-30)
- Mooncake architecture and integrations (Mooncake, accessed 2026-11-30)
- LMCache storage tiers and transfer (LMCache, accessed 2026-11-30)
- Prompt caching guide (OpenAI, accessed 2026-11-30)
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
KV cache prefix caching explained for LLM workloads. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/kv-cache-prefix-caching-explained/