SysDesignAtlas

KV Cache Management

Prefix caching as a radix tree, tiering across HBM/DRAM/NVMe, prefill-decode disaggregation, and cache-affinity routing — squeezing more concurrency out of the resource that actually binds.

HLDHard11 min readaikv-cachecachingrouting
Confidence

#Where the leverage is

From attention and the KV cache: concurrency on a GPU is set by how much KV cache fits alongside the weights. So every megabyte you save or reuse converts directly into more users served on the same hardware.

There are three independent levers, and they multiply:

   1. MAKE IT SMALLER      GQA, quantized cache, MLA
                           → 8-32× reduction, model-side

   2. DON'T RECOMPUTE IT   prefix caching, radix trees
                           → skip prefill entirely on cache hits

   3. PUT IT SOMEWHERE     tiering to DRAM and NVMe,
      ELSE                   disaggregated pools
                           → more effective capacity than HBM

Lever 1 belongs to the model architecture: GQA and MLA are attention designs that store fewer or compressed key/value numbers per token, and a quantized cache stores them at lower precision. This page is levers 2 and 3, which are pure infrastructure and available to you regardless of which model you serve.

#Prefix caching as a radix tree

Here's the fact that makes this work: because each token's cached values depend only on the tokens before it, two requests that start with the same words produce byte-for-byte identical cache entries for that shared opening — no matter how differently they continue.

A simple cache keyed on the whole prompt only catches exact repeats. A radix tree — a tree where each branch point is a place two prompts diverged — catches every shared beginning, at every length.

   Requests arriving:

     R1: [SYS][What is Raft?]
     R2: [SYS][What is Paxos?]
     R3: [SYS][What is Raft?][answer][And Paxos?]

   RADIX TREE OF CACHED BLOCKS

            [SYS]  ← 2,000 tokens, shared by ALL requests
              │
        ┌─────┴─────┐
   [What is      [What is
    Raft?]        Paxos?]
        │
   [answer][And Paxos?]

   R1 hits [SYS] + its own branch
   R2 hits [SYS], prefills only its branch
   R3 hits [SYS][What is Raft?][answer] — everything but
      the last few tokens

How the tree is used:

  • Each node owns real KV blocks in GPU memory, plus a reference count — how many running requests are currently using those blocks.
  • When a request arrives, walk down the tree for as long as its tokens match. Everything along that path is already cached. Only the part after the last match — the suffix where this request diverges — needs to be prefilled, and it becomes a new branch.
  • When memory runs low, evict least-recently-used leaves (the ends of branches). Never evict a node that still has children, because every child's cache depends on the prefix stored above it.

This is why providers price cached input at a fraction of uncached input. They are passing through a real, large cost difference — not offering a discount.

#Cache-affinity routing

Prefix caching only helps if the request lands on the replica holding the prefix. With naive round-robin, an 8-replica fleet gives you a 1-in-8 chance.

cache hit if A is overloaded Request conversation_id Router consistent hash + load check Replica A holds this prefix Replica B cold for this prefix
Route by conversation, fall back on load. Cache locality is worth more than perfect balance.

This is consistent hashing on conversation ID, with one crucial addition: a load-based escape hatch. Pure hashing sends every request for a hot conversation to one replica, which then queues while others idle.

The standard policy — "power of two choices with cache awareness":

   1. Hash the conversation ID → preferred replica P
   2. If P's queue depth is within a threshold of the fleet
      average, route to P (cache hit, worth a little imbalance)
   3. Otherwise pick the least-loaded replica (cold, but fast)

#Tiering

HBM is fast and small. There is much more memory available one or two tiers away.

   TIER          CAPACITY      BANDWIDTH        USE

   HBM           80-192 GB     2-8 TB/s         active requests
   Host DRAM     1-2 TB        ~64 GB/s PCIe    paused / recent
                               (~900 GB/s C2C)
   Local NVMe    10-100 TB     3-7 GB/s         long-tail prefixes
   Object store  unbounded     ~1 GB/s          rarely worth it

   The question at each boundary is always the same:

     transfer_time  vs  recompute_time

   Recomputing a 2,000-token prefix on a 70B model:  ~120 ms
   Transferring its KV (2,000 × 164 KB = 328 MB):
       over PCIe at 64 GB/s   →   5 ms   ✓ transfer wins easily
       over NVMe at 5 GB/s    →  66 ms   ✓ still wins
       over network at 1 GB/s → 328 ms   ✗ recompute wins

The crossover is a real calculation, not a heuristic, and it depends on your model size and context length. Longer contexts favour transfer: the bytes to transfer grow in step with length, but recompute cost grows faster than that, because attention compares every token with every earlier token. Shorter contexts favour recompute.

Tiered prefix caching is where this pays off best: keep hot prefixes in HBM, warm ones in DRAM, and a long tail on NVMe. A system prompt used by every customer stays in HBM; a specific document a user uploaded yesterday lives on NVMe and is still much cheaper to fetch than to re-prefill.

#Prefill/decode disaggregation

Disaggregation here means splitting one job across two separate pools of machines rather than doing both on the same ones. It's worth doing because prefill and decode want opposite hardware: prefill saturates the compute units, decode sits waiting on memory. Run them together and every GPU is a compromise between the two.

   COLOCATED                     DISAGGREGATED

   ┌──────────────────┐          ┌────────────┐    ┌────────────┐
   │  GPU pool        │          │ PREFILL    │───►│ DECODE     │
   │  prefill+decode  │          │ pool       │ KV │ pool       │
   │  interleaved     │          │            │    │            │
   └──────────────────┘          └────────────┘    └────────────┘
                                  compute-bound     bandwidth-bound
   · chunking needed to           big batches       many concurrent
     avoid stalls                 high MFU          large KV space
   · one hardware choice          scale on          scale on
     for both phases              prompt volume     output volume
   · simpler                      needs a fast KV transfer

The benefits are real: each pool batches homogeneous work, so both run near their own optimum; TPOT stops being disturbed by other people's prefills; and the two pools scale independently, which matters because prompt volume and output volume move differently.

The cost is the KV transfer — 328 MB for a 2,000-token prefix. Over NVLink or InfiniBand with RDMA that's a few milliseconds and worth it. Over anything slower it isn't.

When it's worth the complexity: high traffic with high prompt-length variance, strict TPOT targets, or heterogeneous hardware where you genuinely want compute-dense parts for prefill and bandwidth-dense parts for decode. For a modest single-node deployment, chunked prefill in one pool is simpler and nearly as good.

#Eviction

Standard LRU is wrong here, because entries differ enormously in value.

SignalWhy it matters
Reference countNever evict blocks a live request is using
RecencyLRU baseline
Prefix lengthA 4,000-token cached prefix saves far more than a 100-token one
Hit frequencyA shared system prompt is worth vastly more than one user's document
Recompute costScales with length and model size

A reasonable scoring function: value = hit_rate × recompute_cost × recency_decay. In practice, protecting a small set of known-hot prefixes (the system prompts, the common tool definitions) explicitly, and running LRU over the rest, captures most of the benefit with far less machinery.

#Check yourself

What are the three KV-cache levers?Show answer
Make it smaller (GQA, quantized cache, MLA), don't recompute it (prefix caching), and put it somewhere else (tiering to DRAM and NVMe, disaggregated pools). They multiply.
Why use a radix tree for prefix caching?Show answer
Each branch point is where prompts diverged, so every shared prefix at every length is reused — not just exact repeats. Nodes hold ref-counted blocks; evict leaves by LRU.
What is prefix caching worth in chat?Show answer
An 8-turn conversation with a 2,000-token system prompt prefills ~6,000 tokens instead of ~34,000 — 5.7× less compute-bound work, and much lower TTFT after turn 1.
How does cache-affinity routing work?Show answer
Hash the conversation ID to a preferred replica; use it while its load is within a threshold of the fleet average, otherwise pick the least loaded. It trades balance for hit rate — quantify the ratio.
How do you decide which tier a cached prefix belongs in?Show answer
Compare transfer time with recompute time: 328 MB of KV takes ~5 ms over PCIe and ~66 ms from NVMe versus ~120 ms to recompute, but 328 ms over a 1 GB/s network loses.
Why disaggregate prefill and decode?Show answer
Each pool runs homogeneous work at its own optimum, TPOT stops being disturbed by other users' prefills, and pools scale independently — at the cost of a fast KV transfer.
What is the KV-cache invalidation trap?Show answer
Cached blocks are valid only for the exact weights, adapter and quantization that produced them. Key by (model version, adapter, quantization, tokens) and flush on any change — stale blocks fail silently.
How should cached prefixes be evicted?Show answer
Never evict blocks in use; weigh recency, prefix length, hit frequency and recompute cost. In practice, pin known-hot prefixes (system prompts, tool definitions) and run LRU over the rest.

#What to carry forward

  • Three multiplying levers: make the cache smaller, don't recompute it, put it somewhere else.
  • A radix tree captures every shared prefix, not just exact matches — 5×+ prefill reduction in chat.
  • Cache-affinity routing trades load balance for hit rate. Quantify the ratio; it usually favours affinity heavily.
  • Tiering is a transfer-versus-recompute calculation at every boundary, and it's computable.
  • Disaggregation lets prefill and decode each run at their own optimum, at the cost of a KV transfer.
  • Key the cache by model version and adapter — stale blocks are a silent correctness bug.
00:00
/ 11m