Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 5/ 160
01. LLM Fundamentals

KV Cache

Key/value caching for autoregressive decoding, memory growth with sequence length, and serving impact.

AdvancedAutoregressive Decode · GPU Memory3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The model remembers what it already worked out about earlier words, so it doesn't redo that work for every new word. That memory takes up GPU space.

Think of it like…

Taking notes in a meeting: instead of re-reading the whole transcript before writing each new sentence, you keep running notes (the cache) and just add one line per turn. The notes save work, but a very long meeting fills a lot of notebook pages.

Where you’ve seen it

Serving a 70B model with 80 layers, 8 KV heads of dimension 128 in 16-bit: each token needs 2 (K and V) × 80 layers × 8 heads × 128 × 2 bytes ≈ 328 KB. A 32,000-token conversation therefore holds about 10.5 GB of cache for one user. On an 80 GB GPU after loading the weights, that's why only a handful of long conversations fit at once.

Words you’ll hear

KV cache
Stored key and value vectors for all previous tokens, per layer and per KV head.
Prefill vs decode
Prefill builds the cache for the prompt in parallel; decode appends one token per step.
Prefix caching
Reusing cached K/V for an identical prompt prefix across requests.
Paged attention
Storing the cache in fixed-size blocks to avoid fragmentation and waste (as in vLLM).

Visual diagram

Loading interactive diagram

Theory & deep dive

Why caching works and what it costs

In self-attention, a token's key and value depend only on that token and the layers beneath it, so once computed for a prefix they never change as generation continues. Caching them turns each decode step from a pass over n tokens into a pass over one, with attention reading the stored K and V. Without it, generating n tokens would cost O(n²) forward passes' worth of work; with it, it's linear in generated tokens (attention still reads the cache, which is why per-token latency creeps up with length).

The price is memory: bytes per token = 2 × layers × KV heads × head dimension × bytes per element. That is why grouped-query attention (fewer KV heads), multi-query attention, 8-bit or 4-bit KV quantisation and sliding-window attention are used in modern models: they shrink the cache directly. Serving engines also need an allocator, because naive pre-allocation for the maximum length wastes most of the memory.

Estimating cache memory

Memory ≈ tokens × bytes_per_token × concurrent_sequences. At 160 KB per token (a GQA model), 20 users with 8,000-token contexts need about 20 × 8,000 × 160 KB ≈ 25.6 GB for the cache alone, on top of the weights.

Key takeaway: The cache trades memory for compute; estimate it per token, then multiply by length and concurrency.

Serving optimisations built on the cache

Paged attention (vLLM) splits the cache into small blocks allocated on demand, like virtual memory, removing fragmentation and letting far more sequences share a GPU. Prefix caching keeps the cached blocks of a shared prefix, such as a long system prompt or document, so later requests skip prefill for it, cutting time-to-first-token and, with provider prompt caching, cost. Continuous batching adds and removes sequences from the running batch at each step instead of waiting for a whole batch to finish.

Other levers: quantise the KV cache to 8-bit with little quality loss, offload cold caches to CPU memory or disk for long idle conversations, evict or compress old tokens, and limit maximum context per tenant. When capacity planning, remember that weights are a fixed cost but the cache scales with traffic, so it's the cache that limits concurrency.

A shared prefix across requests

A support bot's 6,000-token policy prompt is identical in every request. With prefix caching, only the first request pays prefill for it; later requests reuse the cached K/V and only prefill the user's short question, so first-token latency drops sharply.

Key takeaway: Paged attention, prefix caching and continuous batching all manage the cache better.

How it works, step by step

Step 1 of 4
GPU

1. Prefill the prompt

Process all prompt tokens in parallel and store each layer's keys and values in the cache.

2,000 tokens → K, V per layer
Key numbers at this step
Compute-bound
high throughput

When to use it & trade-offs

What it is

During generation a transformer produces one token at a time, and each new token's attention needs the keys and values of every earlier token. The KV cache stores those keys and values after they're first computed, so each decode step only computes K and V for the single new token instead of recomputing the whole sequence. It makes generation fast, but the cache grows linearly with sequence length and batch size and often becomes the main consumer of GPU memory.

Why it matters: KV cache size decides how many users a GPU can serve at once, how long contexts can be, and why long conversations slow down or hit memory limits. It also underpins optimisations you'll meet in production: prefix caching (reusing the cache for a shared prompt prefix), paged attention, grouped-query attention and KV quantisation. Serving-focused interviews ask you to estimate it.

When to reach for it

  • Capacity planning for GPU memory and concurrency
  • Explaining why long conversations get slower and costlier
  • Designing prompts so a long prefix stays identical for caching

When to avoid or be careful

  • Estimating GPU capacity from model weights alone
  • Changing the start of a long prompt each request, which defeats prefix reuse
  • Pre-allocating maximum-length caches for every sequence

Ways to reduce KV cache pressure

Grouped-query / multi-query attention
Best for: Model design for serving efficiency

Strengths: Smaller cache per token with little quality loss.

Watch out: Built in at training time; can't be added later cheaply.

KV cache quantisation (8-bit, 4-bit)
Best for: Fitting more sequences on existing GPUs

Strengths: Halves or quarters cache memory.

Watch out: Possible small accuracy loss at lower precision.

Paged attention + prefix caching
Best for: Multi-tenant serving with shared prompts

Strengths: Less waste; faster first token for repeated prefixes.

Watch out: More complex serving stack.

Interview signals & numbers to know

When this topic comes up

  • “How many users can one GPU serve?”
  • “Why does latency grow in long chats?”
  • “What's prefix caching?”
  • vLLM and paged attention
  • GQA

Benchmarks & rules of thumb

≈ 328 KB -
per token: 80 layers, 8 KV heads, head dim 128, 16-bit (worked example)
2 × layers × kv_heads × head_dim × bytes -
cache bytes per token
8-bit -
common KV quantisation level

Common mistakes & follow-ups

Common interview mistakes

  • Planning GPU capacity from weights only, then running out of memory when long conversations arrive.
  • Putting a timestamp or user name at the start of the system prompt, which breaks prefix cache hits.
  • Assuming the cache makes long contexts free; attention still reads all cached tokens each step.

Likely interviewer follow-ups

  • How would you estimate KV cache memory for a model?
  • Why does grouped-query attention help serving?
  • How does prefix caching reduce time to first token?
Interview tip: Quote the formula and one worked number. Saying "about 10 GB for one 32K conversation on a 70B model" turns an abstract idea into a capacity-planning answer.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply KV Cache with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Context Windows
Next topic
Temperature and Top-p