Memory and the KV-cache
- Production
- 45 min
- Lesson 2 of 7 in Inference engineering
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
You will be able to
- Compute KV-cache bytes per token and per request from layers, KV heads, head dimension and precision, using KV heads rather than query heads.
- Turn a GPU memory budget (usable memory minus weights and overhead) into a number of concurrent sequences, explain why a model that fits does not necessarily serve, and say how cache reads limit decode speed at large batch.
- Explain how PagedAttention blocks and block tables remove waste, and say what it does not change.
- Explain how prefix caching reuses KV blocks, what makes a prefix reusable, and how it differs from a response cache.
- Compare grouped-query attention, latent attention and KV quantization by effect and cost, and describe what a server does when the cache pool is full.
Every customer being answered keeps a set of notes in the server’s memory, and each set grows with every word of the conversation.
Ananya looks at the memory gauge, then at the queue, then at Latency the cat, who has chosen the warm server rack for a nap.
“How many fit?” she asks nobody in particular. Latency does not move.
Concept
The notes in the story are the KV-cacheKV cacheStored key and value vectors of earlier tokens, reused at each decode step so they are not recomputed. It saves compute but its memory grows with context length and concurrent requests. It is not a response cache.Open the glossary entry: for every token already in a conversation, the model keeps the keys and values its attention layers computed, so each new token only has to compute its own and read the rest. How LLMs work introduced the idea, and LLM inference and serving gave a first capacity estimate. This lesson makes the estimate precise and then covers the tools engines use to stretch it: paging, prefix caching, and architectures that need fewer bookmarks.
The cache trades compute for memory. It saves redoing the projections for the whole history at every step, and it costs memory that grows with context length, batch size, layers and KV heads. On a serving GPU that memory, not arithmetic, usually decides how many requests fit.
Why It Matters
“How many users does one GPU serve?” is a memory question, and getting it wrong in either direction costs money: overestimate and the server thrashes, underestimate and you buy GPUs you do not need. The cache also adds bytes to every decode step, so it limits speed as well as count. Interviewers like this topic because it needs a formula, an assumption list and a judgment about trade-offs, all in a few minutes.
Mental Model
The shelf is the GPU’s free memory after the model has taken its share. Each customer’s notes take shelf space in proportion to how long their conversation is. Paging means the shelf is divided into small fixed bays that notes can occupy in any order, instead of every conversation reserving a plank long enough for the longest conversation. Prefix cachingPrefix cachingReusing the KV cache of a prompt prefix shared by requests, so the shared part is not recomputed. The serving-engine counterpart of a provider's prompt caching.Open the glossary entry means that if forty customers begin with the same page, you keep one copy of it and let them all point at it. Fewer notes per word, through a better-designed model, matters more than any shelving trick.
Sizing the cache
Per token, the cache stores one key vector and one value vector for each KV head in each layer:
The is key plus value. Use KV heads, not attention heads. A model with grouped-query attention has fewer KV heads than query heads, and sizing with the query-head count overstates the cache several times over.
Real configurations (accessed 2026-10-21): the Llama 3 paper’s architecture table lists 32 layers, 32 attention heads and 8 KV heads for the 8B model; 80 layers, 64 attention heads and 8 KV heads for the 70B model; and 126 layers, 128 attention heads and 8 KV heads for the 405B model. Head dimension is model dimension divided by attention heads, which is 128 for all three. In 16-bit values:
| Model | Layers | KV heads | Head dim | KV per token | One 8,192-token sequence |
|---|---|---|---|---|---|
| Llama 3 8B | 32 | 8 | 128 | 128 KiB | 1.0 GiB |
| Llama 3 70B | 80 | 8 | 128 | 320 KiB | 2.5 GiB |
| Llama 3 405B | 126 | 8 | 128 | 504 KiB | 3.9 GiB |
| A 7B-class model with full multi-head attention (32 KV heads, hypothetical) | 32 | 32 | 128 | 512 KiB | 4.0 GiB |
The last row is a contrast case, not a specific model: with the same layers and head size, full multi-head attention costs four times the 8-KV-head design.
For scale, the PagedAttention paper (Kwon et al., 2023) works out 800 KB per token for OPT-13B ().
From memory to concurrency
A GPU’s memory holds four things: the weights, the KV pool, activation workspace, and engine overhead. Engines let you set the fraction of memory they may use (vLLM calls it gpu_memory_utilization). The KV budget is what is left:
Worked example, with stated assumptions: Llama 3 70B in BF16 (140 GB of weights) on four 80 GB GPUs, utilization 0.9, and an assumed 4 GB of overhead per GPU (illustrative; real overhead depends on the engine and settings).
- Usable: . Minus weights 140 GB, minus overhead 16 GB: 132 GB for the cache.
- At 320 KiB (327,680 bytes) per token: tokens of cache.
- At 8,192 tokens per sequence: about 49 sequences. At 2,048 tokens: about 196.
- Storing the cache in FP8 halves the bytes per token and doubles those counts.
The same arithmetic on two such GPUs: usable 144 GB, minus 140 GB of weights, minus 8 GB of overhead is negative. The model’s weights fit in memory, and the server cannot hold a single long sequence. Fits is not serves. The fixes are fewer weight bytes (quantize to FP8, 70 GB, which leaves 66 GB and roughly 24 sequences of 8,192 tokens), more GPUs, or shorter contexts.
This is also why long-context traffic is expensive. One 128,000-token sequence on the 70B model needs , about 39 GiB of cache for a single user.
The cache also costs speed
Every decode step reads the weights once for the whole batch, and it also reads each sequence’s own cache. Lesson 1’s bound ignored the second term. Take the 8B model on an H100 (3.35 TB/s), 16 GB of weights and 8,192-token sequences, where each sequence’s cache is 1.0 GiB (about 1.07 GB):
| Batch | Cache bytes read per step | Step time at least | Aggregate tokens per second at most |
|---|---|---|---|
| 1 | 1.07 GB | 5.1 ms | about 196 |
| 8 | 8.6 GB | 7.3 ms | about 1,090 |
| 32 | 34.4 GB | 15.0 ms | about 2,130 |
At batch 32 the cache is more than twice the weights, and the weights-only ceiling of about 6,700 tokens per second from lesson 1 drops to about 2,100. This is the second limit on batching promised there: the weights are shared across the batch, but each cache is not. It also explains why per-token latency degrades as context grows.
The fragmentation problem and PagedAttention
The simple way to store a sequence’s cache is one contiguous slab sized for the longest sequence the server allows. Most requests never get that long, so most of the slab sits empty, and gaps between slabs go unusable. The PagedAttention paper reports that in existing systems only 20.4 to 38.2 percent of KV-cache memory held actual token states.
PagedAttentionPagedAttentionStoring the KV cache in on-demand blocks to avoid fragmentation, which allows larger batches and prefix sharing.Open the glossary entry borrows virtual memory from operating systems. The pool is divided into fixed-size blocks (vLLM’s default is 16 tokens). Each sequence has a block table that maps its logical blocks to whichever physical blocks are free. Blocks are allocated as the sequence grows, so the waste per sequence is at most part of one block.
Worked example: a 1,000-token sequence needs 63 blocks of 16 tokens, which is 1,008 slots, so 8 are wasted (0.8 percent). Reserving a contiguous 8,192-token slab for it would leave 88 percent of the slab empty.
| Storage scheme | Slots reserved for a 1,000-token sequence | Slots wasted |
|---|---|---|
| Contiguous slab for an 8,192-token maximum | 8,192 | 7,192 (88%) |
| PagedAttention, 16-token blocks | 1,008 | 8 (0.8%) |
What PagedAttention changes: memory utilization, and therefore the batch size you can reach. Because blocks are addressable, it also enables sharing between sequences (parallel sampling and shared prefixes) and lets an engine preempt a sequence and bring it back later. What it does not change: the real bytes of a token’s keys and values, and it does not make the attention arithmetic faster. The paper reports 2 to 4 times higher throughput than FasterTransformer and Orca at the same latency; those gains come from the larger batches that the freed memory allows.
Prefix caching
Many requests start with the same tokens: a system prompt, tool definitions, few-shot examples, a shared document. If the KV blocks for that prefix are already computed, a new request skips prefill for the shared part.
vLLM’s design documentation (accessed 2026-10-21) describes the mechanism. Each full block gets a hash built from the parent block’s hash, the block’s own tokens, and extra values that make it unique, such as a LoRA adapter ID. Only full blocks are cached. A new request’s blocks are hashed and looked up. Blocks are reference-counted, so a block in use by any request stays; when memory is needed, the least recently used free blocks are evicted. SGLang’s RadixAttention (Zheng et al., 2023) pursues the same goal of KV-cache reuse across requests, organising cached prefixes in a radix tree, which suits branching conversations and agent runs.
Worked example: an 8B model serves a support bot whose every request begins with the same 6,000-token policy prompt followed by about 500 unique tokens.
- Prefill: 6,000 of 6,500 tokens (92 percent) need no recomputation once the prefix is cached.
- Memory: one copy of the prefix is , about 0.79 GB. Fifty concurrent requests with private copies would hold 39 GB for it. Shared, they hold 0.79 GB.
Rules that decide whether it works:
- The prefix must be identical and at the start. Put static content first and per-request content last. A timestamp or user name at the top of the prompt makes every request different from byte one.
- Anything that changes the KV values changes the cache key: another LoRA adapter. A different model version runs on its own engine, so its cache is separate. vLLM can also mix a cache salt into the first block’s hash, so only requests with the same salt share blocks, which is a way to keep tenants apart.
- Requests have to reach the same engine. A cache on replica A does nothing for a request routed to replica B, so a load balancer that spreads related requests randomly wastes it. Lesson 6 returns to routing.
Prefix caching saves prefill work and memory, so it improves TTFT and capacity. It does not speed up decode. And it is not a response cache, which stores whole answers and returns them without running the model. Provider “prompt caching” discounts, covered in Cost and latency optimization, apply the same idea at the API.
Shrinking the cache by design
The cache per token is set when the model is designed. For a model you plan to self-host, read its KV bytes per token before you read its benchmark scores.
| Technique | Idea | Effect | Cost |
|---|---|---|---|
| Multi-query attention (MQA) | all query heads share one KV head | smallest cache | the GQA paper notes it can degrade quality |
| Grouped-query attention (GQAGQAShort for grouped-query attention: query heads share key and value heads, which shrinks the KV cache.Open the glossary entry) | groups of query heads share a KV head | cache shrinks by the ratio of query heads to KV heads (4 times for 32 versus 8) | built into the model; the paper shows multi-head checkpoints can be converted with about 5 percent of the original pre-training compute |
| Multi-head latent attention (MLA) | cache a compressed latent vector and expand it when needed | DeepSeek-V2 reports a 93.3 percent smaller KV cache than DeepSeek 67B (a model-to-model comparison that also changes other things) | more complex attention kernels |
| KV-cache quantization | store keys and values in 8 bits or fewer | capacity roughly doubles at 8 bits | accuracy risk that depends on the model and the context length, so test your own long inputs; vLLM’s documentation says dataset calibration of scales is recommended and gives no accuracy figures, so validate on your own evaluation set |
Other families exist (sliding-window attention, state-space layers, evicting low-importance tokens). They trade away exact long-range recall, which is why they are model-design decisions rather than serving switches.
An interview line that holds up: choices made at pretraining time, such as GQA or MLA, matter more for serving cost than most runtime tricks.
When the pool is full
Eventually every sequence wants another block and none is free. An engine can do one of three things.
- Queue new requests until space frees up. TTFT rises.
- Preempt a running sequence. Its cache is either recomputed when it resumes (spends compute) or swapped to CPU memory (spends transfer time). The vLLM documentation says preempted requests are recomputed and that this can hurt end-to-end latency; in its current engine the default mode is recompute.
- Shed load: reject requests rather than serve everyone badly.
A preemption storm is the failure to watch for. The engine keeps evicting and recomputing, GPU utilization looks high, and goodput collapses. vLLM exposes a preemption count in its metrics. Fixes, from its optimization guide: lower the number of concurrent sequences or batched tokens, raise memory utilization, or add tensor parallelism to free memory per GPU (at the price of synchronization). Adding replicas is the usual operational answer outside that guide. Quantizing the KV-cache and capping context length per customer tier also reduce pressure.
Real-World Application
Before you deploy, compute the KV bytes per token from the model’s configuration, subtract weights and overhead from usable memory, and write down how many sequences of your real context length fit. Compare that with the concurrency your traffic needs. Then decide the levers in order of cost: shorter contexts, prefix caching with static content first, FP8 cache validated on your evaluation set, a model with fewer KV heads, more GPUs. Alert on preemption count, not only on GPU utilization.
Interview Perspective
Expect: “How big is the KV-cache for this model?”, “How many concurrent users fit on this GPU?”, “What is PagedAttention?”, “Why is my TTFT high when long and short users mix?”. A strong answer uses the formula with KV heads, subtracts weights and overhead, states the assumptions, and names two or three levers with their costs.
Common mistakes: sizing with attention heads instead of KV heads; saying PagedAttention makes attention faster or the cache smaller; confusing the KV-cache with a response cache; forgetting activation and overhead memory; expecting prefix caching to work when the prompt starts with dynamic content.
Provenance: Common industry pattern and Generated practice. These are standard serving topics for ML-infrastructure and GenAI roles; none is verified for a named company.
Practice Questions
- Basic: What is the KV-cache, and what makes it grow?
- Intermediate: Compute KV bytes per token for 40 layers, 8 KV heads and head dimension 128 in FP8. How many 4,096-token sequences fit in 40 GB?
- Advanced: p95 TTFT triples whenever long-document users and chat users share a server. Diagnose it (prefill blocking, cache pressure, preemption) and propose fixes with their costs.
- Product-Company: Design caching for a support bot where every request starts with a 6,000-token policy prompt followed by the user’s history.
Activity
Choose an open-weight model and read its config.json for layers, attention heads, KV heads and hidden size. Compute KV bytes per token and per sequence at the context length you would serve. Then compute the concurrency on one GPU of your choice, stating the utilization fraction, the overhead you assume and the precision. If the config is not available, say so rather than guessing.
Homework
Write a one-page cache plan for a service with a 4,000-token static system prompt and 1,000-token conversations: bytes per token, concurrency before and after prefix caching, what you would alert on, and the two levers you would pull first when the pool fills, each with its cost.
Quick Revision
- . Use KV heads.
- . Divide by bytes per sequence for concurrency.
- Fits is not serves: weights that fit can leave no room for a cache.
- Each decode step also reads every sequence’s cache, so it limits speed as well as count.
- PagedAttention reduces waste and raises batch size; it does not shrink the bytes or speed up attention.
- Prefix caching needs an identical prefix at the start, the same adapter and the same engine. It saves prefill and memory, not decode.
- GQA, MLA and KV quantization shrink the cache; each has a quality or complexity cost to validate.
- A full pool means queueing, preemption or shedding. Watch the preemption count.
Check yourself
- Walk-through: A 70B model with 8 KV heads and 80 layers serves 8,192-token chats on four 80 GB GPUs. State the formula, the budget, the concurrency, and the three cheapest ways to raise it.
- Variation: Repeat for a 14B model with full multi-head attention on a single 80 GB GPU. What changes first?
- Common misconception: “PagedAttention shrinks the KV-cache.” It shrinks waste, not the bytes a real token needs.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Cache strategies (opens in a new tab)
Shows how cache strategies appear in a widely used library, for a view outside vLLM.
Production Metrics (opens in a new tab)
Lists the metrics to alert on, including the preemption signal.
Further reading
vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttention (opens in a new tab)Essential
The short, readable introduction to PagedAttention from its authors, before the full paper.
LLM Inference Handbook (opens in a new tab)
A broader treatment of cache management and serving trade-offs.
More for this module: Inference engineering resources
Practice
Test what you just read. Quizzes and cards are grouped by module: Inference engineering.
Check yourself14 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.