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 84/ 160
05. AI System Design

Prefix Caching

Reuse KV/compute for shared prompt prefixes across requests in a serving stack.

AdvancedShared Prefix · KV Reuse3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

If many requests begin with the same long instructions, the server remembers its work on those instructions and only processes what's new.

Think of it like…

A printing press that keeps the typeset first pages of a book that is reprinted with different last chapters: only the new pages need setting, and the common pages are shared rather than recreated.

Where you’ve seen it

A self-hosted 70B model uses grouped-query attention with 80 layers, 8 KV heads, head dimension 128 and FP16, so one token's KV cache takes 2 × 80 × 8 × 128 × 2 bytes = 327,680 bytes (about 320 KiB). A 2,400-token system prompt plus tool definitions therefore needs 2,400 × 327,680 ≈ 786 MB (0.73 GiB). With 50 concurrent requests, private copies would use about 36.6 GiB, while a shared cached prefix uses 0.73 GiB, freeing roughly 35.9 GiB for longer contexts or more concurrent users. For compute, if prefill runs at about 8,000 tokens per second per GPU, prefilling 3,100 tokens takes 0.39 s but only the 700 non-cached tokens take 0.09 s, cutting TTFT by about 0.3 s. The team moves a timestamp from the top of the prompt to the end and sorts tool definitions deterministically, which lifts the prefix hit rate from 12% to 78%, and routes requests with the same prefix to the same replica.

Words you’ll hear

KV cache block
A fixed-size chunk of cached keys and values, hashed by its tokens and prefix.
Prefill
The compute-heavy pass that processes the prompt before the first output token.
Prefix hit rate
Share of prompt tokens (or blocks) served from cache.
Cache-aware routing
Sending requests with shared prefixes to the replica that already holds them.

Visual diagram

Loading interactive diagram

Theory & deep dive

How the cache works

During prefill, the model computes keys and values for every prompt token at every layer; those tensors are the KV cache that decoding later reads. Because attention is causal, the KV entries for a token depend only on the tokens before it, so if two prompts share an identical prefix, the entries for that prefix are identical and can be reused. Serving engines like vLLM (with automatic prefix caching) and SGLang (RadixAttention, a radix tree over token sequences) store the cache in blocks, index them by a hash that includes the whole preceding sequence, and on arrival match the longest cached prefix, allocate new blocks only for the unmatched tail, and track reference counts so a block in use by running requests isn't evicted. Unreferenced blocks are retained and evicted by an LRU policy when memory is needed.

The size of what you save is easy to compute: KV bytes per token = 2 (keys and values) × layers × KV heads × head dimension × bytes per element. With grouped-query attention (8 KV heads instead of 64), a 70B-class model needs about 320 KiB per token in FP16, so a 2,400-token prefix is about 0.73 GiB. Quantising the cache to FP8 halves that. The compute saved is the prefill for the matched tokens, so benefits grow with the ratio of shared prefix to total prompt and with how often the prefix recurs.

KV memory per token

2 × 80 layers × 8 KV heads × 128 dims × 2 bytes = 327,680 bytes. For 2,400 tokens: 786,432,000 bytes ≈ 0.73 GiB. Fifty concurrent requests sharing the prefix store it once; without sharing they store it fifty times (36.6 GiB).

Key takeaway: Causal attention makes identical prefixes reusable; savings scale with shared-prefix length and recurrence.

Making prompts and infrastructure cache-friendly

Structure prompts as stable first, dynamic last: system instructions, tool schemas, few-shot examples and static documents at the top, then conversation history, retrieved chunks and the user message. Avoid anything that changes early in the prompt: timestamps, request ids, random ordering of tools, per-user names in the system prompt, or reshuffled few-shot examples. In multi-turn chat, append new turns rather than rewriting history, since an edit in the middle invalidates everything after it. Keep block alignment in mind: only full blocks are reusable, so a 2,410-token prefix with 16-token blocks reuses 150 blocks (2,400 tokens) and prefills the rest.

At the system level, use cache-aware routing (consistent hashing on a prefix id, or a router that tracks which replica holds which prefixes) so a shared prefix isn't rebuilt on every replica, and size KV memory for the working set of hot prefixes. Monitor prefix hit rate, TTFT split by cache hit and miss, eviction rate and GPU memory. Mind the trade-offs and risks: cached blocks compete with active requests for memory; some features (certain adapters, multimodal inputs, sliding-window attention) limit reuse; and shared prefix caches across tenants can leak information through timing side channels (a fast response reveals that someone else used the same prefix), so isolate by tenant or add a per-tenant salt to the hash when that matters. Hosted APIs offer similar provider-side prompt caching with discounted cached-token pricing; the same layout rules apply.

A layout fix

Before: the system prompt starts with "Current time: 2026-11-20T09:14:03Z", so no two requests share a prefix (12% hit rate from other effects). After: the timestamp moves to the final user message and tools are sorted by name, so the 2,400-token block sequence is identical and the hit rate rises to 78%.

Key takeaway: Put stable content first, route by prefix, monitor hit rate and isolate tenants where timing leaks matter.

How it works, step by step

Step 1 of 4
Engineering

1. Audit the prompt for stable parts

Identify the system prompt, tools, examples and documents that repeat across requests.

2,400 of 3,100 tokens are shared
Key numbers at this step
Ratio
shared ÷ total

When to use it & trade-offs

What it is

Prefix caching reuses the KV cache (the attention keys and values already computed for a prompt prefix) across requests that start with the same tokens, so the model skips the prefill work for the shared part. In a serving stack such as vLLM, the KV cache is split into fixed-size blocks (for example 16 tokens) and each block is identified by a hash of its tokens and everything before it, so a new request finds the longest matching run of cached blocks, reuses them and prefills only the remainder. The effect is lower time to first token, higher throughput and less memory duplicated across concurrent requests, provided prompts are structured with a stable prefix.

Why it matters: Real prompts repeat a lot: a long system prompt, tool definitions, few-shot examples, a shared document or an earlier conversation. Recomputing that prefix on every request wastes GPU time and delays the first token, and storing a private copy of its KV cache per request wastes scarce GPU memory. Prefix caching turns that redundancy into capacity and latency gains, but only when prompt layout, routing and eviction cooperate with it.

When to reach for it

  • Long system prompts and tool definitions
  • Multi-turn chat and agent loops with growing context
  • RAG with shared documents

When to avoid or be careful

  • Placing timestamps or user data at the top of the prompt
  • Reshuffling tools or examples between requests
  • Sharing prefix caches across tenants when timing leaks matter

Caching in LLM serving

Prefix (KV) caching
Best for: Shared system prompts, tools, documents and chat history

Strengths: Lower TTFT and memory; no change in outputs.

Watch out: Needs a stable prefix and cache-aware routing.

Semantic response caching
Best for: Repeated questions with reusable answers

Strengths: Skips generation entirely.

Watch out: False hits; scope and staleness issues.

No caching
Best for: Highly unique, short prompts

Strengths: Simplest.

Watch out: Recomputes everything; higher latency and cost.

Interview signals & numbers to know

When this topic comes up

  • “TTFT is high with a long system prompt”
  • “GPU memory is full of duplicate KV caches”
  • Automatic prefix caching
  • RadixAttention
  • Prompt layout for caching

Benchmarks & rules of thumb

2 × L × H_kv × d × bytes -
KV cache bytes per token
0.73 GiB vs 36.6 GiB -
shared vs duplicated 2,400-token prefix for 50 requests
12% → 78% -
prefix hit rate after fixing the layout

Common mistakes & follow-ups

Common interview mistakes

  • Putting a request id at the start of the system prompt.
  • Editing earlier turns of a conversation and invalidating the cache.
  • Assuming cached blocks are free: they still occupy GPU memory until evicted.

Likely interviewer follow-ups

  • How does prefix caching reduce TTFT?
  • How do you compute the KV cache size per token?
  • How should you order a prompt to maximise cache hits?
Interview tip: Show the per-token KV arithmetic. Anyone can say "it saves memory"; the numbers prove you understand where the saving comes from.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Prefix Caching with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Semantic Caching
Next topic
Token Budgets