Skip to main content
← CONCEPTS / AI & MACHINE LEARNING SYSTEMS
An end-to-end domain learning journey

AI/LLM Prefix Caching &
RadixAttention (Zero-Copy KV Sharing).

RadixAttention indexes cached GPU KV-cache blocks in a compressed prefix trie (Radix Tree) with LRU eviction, enabling zero-copy prefix sharing across concurrent and sequential LLM requests.
Start the journey7 sections· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep serving pipelines predictable under bursty prompts, because causal self-attention only depends on preceding tokens, any two prompts sharing a prefix of N tokens can share the exact same physical GPU KV-cache pages—cutting prefill FLOPs and TTFT by 5x–10x.

TL;DR30-second simplified summary
▾

Because causal attention is prefix-invariant, identical leading tokens produce identical KV tensors. A Radix Tree indexes token spans to physical GPU pages.

Requests pin matched paths (ref_count > 0) during execution, and idle leaves evict via LRU.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Disaggregated LLM Serving (Prefill vs. Decode Pools)
Disaggregated LLM serving separates prompt prefill (compute-bound TTFT) and autoregressive token decode (HBM-bandwidth-bound ITL) onto independent GPU pools, transferring computed KV-cache blocks over RDMA or NVLink without stalling in-flight decode batches.
CNN, RNN & Transformer Architectures
Neural architectures encode distinct inductive biases: CNNs exploit local spatial translation invariance, RNNs/LSTMs process sequential recurrence with O(1) inference state, and Transformers use parallel self-attention over global context.
Full walkthrough · 7 stages
01
STAGE 01 · CAUSAL INVARIANCEfoundation

Why Identical Token Prefixes Produce Bit-Identical KV Tensors.

Why this matters: Exploit causal Transformer prefix invariance so requests sharing a prompt prefix reuse identical KV tensors.

In a causal decoder-only Transformer, token i's Key and Value vectors (K_i, V_i) depend strictly on tokens 0..i and never on tokens > i.

Therefore, if Request A and Request B share an identical prefix of 2,048 tokens (with identical LoRA adapter and positional encoding), their first 2,048 KV vectors are mathematically identical—allowing 100% zero-copy reuse.

STAGE 01 · CAUSAL INVARIANCE

Why Identical Token Prefixes Produce Bit-Identical KV Tensors

Req A: [Sys + Docs]+ Q1Cold ComputeCausal KV InvarianceBit-IdenticalReq B: [Sys + Docs]+ Q2Zero Re-PrefillTTFT Drops 85%Compute Savedreused by

1.Causal Mask Property: In decoder-only Transformers, token i never attends to tokens > i, making prefix KV states pure functions of 0..i.

2.Zero Quality Loss: Reusing cached KV pages is mathematically identical to recomputing the prefix from scratch.

3.Massive Savings: System prompts, few-shot examples, and RAG documents often make up 80-95% of prompt tokens.

Causal attention guarantees identical token prefixes produce bit-identical KV tensors that can be shared with zero quality loss.

02
STAGE 02 · RADIX TREE INDEXfoundation

Compressed Prefix Trie Mapping Token Edges to Physical KV Pages.

Why this matters: Index cached token spans in a compressed Radix Tree that splits edges dynamically when new prompts diverge.

Think of Compressed Prefix Trie Mapping Token Edges to Physical KV Pages as the intuition layer for AI/LLM Prefix Caching & RadixAttention (Zero-Copy KV Sharing): Index cached token spans in a compressed Radix Tree that splits edges dynamically when new prompts diverge.

Each node in the Radix Tree represents a contiguous span of cached tokens mapped to fixed-size GPU KV pages (e.g., 16 tokens/page). When a new prompt diverges mid-edge (e.g., matching 1,000 of 1,500 tokens on an edge), the engine splits the edge at token 1,000 into a shared parent node and two child branches—without copying any GPU tensors.

STAGE 02 · RADIX TREE INDEX

Compressed Prefix Trie Mapping Token Edges to Physical KV Pages

Radix RootTree EntryCompressed EdgeContiguous SpanMid-Edge DivergenceBranch NodePagedAttentionBlocksGPU HBMsplits on diff

1.Compressed Edges: Storing variable-length token spans on edges keeps tree depth proportional to branch points, not prompt length.

2.Dynamic Edge Splitting: When a new prompt diverges at token 1,000 of a 1,500-token edge, split into [0..1000] + two child branches.

3.Zero-Copy Mapping: Multiple active requests point directly to the same physical PagedAttention HBM blocks.

A compressed Radix Tree maps variable-length token spans to physical 16-token KV pages and splits edges on divergence.

Engineering Decision Framework
Problem
How to implement AI/LLM Prefix Caching & RadixAttention (Zero-Copy KV Sharing) without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep serving pipelines predictable under bursty prompts, because causal self-attention only depends on preceding tokens, any two prompts sharing a prefix of N tokens can share the exact same physical GPU KV-cache pages—cutting prefill FLOPs and TTFT by 5x–10x.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When AI/LLM Prefix Caching & RadixAttention (Zero-Copy KV Sharing) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · EVICTION & SCHEDULINGintermediate

Reference Counting & Leaf-First LRU Eviction.

Why this matters: Protect active generations with reference counting and reclaim HBM via leaf-first LRU eviction.

Active requests pin their matched prefix path by incrementing ref_count += 1 on every ancestor node, preventing eviction mid-generation. When a request finishes, ref_count decrements.

Only leaf nodes with ref_count == 0 sit in the LRU eviction queue; evicting a leaf frees its KV pages and may turn its parent into an evictable leaf.

STAGE 03 · EVICTION & SCHEDULING

Reference Counting & Leaf-First LRU Eviction

Active Request PinEviction LockGeneration DoneRelease PathLeaf-First LRU HeapSafe CandidateReclaim KV PagesMemory Reuseexposes leaves

1.Ancestors Stay Pinned: Internal nodes cannot be evicted while any descendant leaf is still referenced or cached.

2.Leaf-First Eviction: Evicting cold leaves preserves shared root system-prompt KV pages used by many tenants.

3.Zero Race Conditions: Increment ref_count before scheduling prefill so concurrent batches never evict needed KV blocks.

Reference counting pins active prefix paths while leaf-first LRU evicts cold suffixes without disturbing hot shared roots.

04
STAGE 04 · RADIX MATCHERintermediate

Implementing Longest-Prefix Match & Node Splitting.

Why this matters: Implement longest-prefix matching and mid-edge node splitting in the RadixPrefixCache.

from dataclasses import dataclass, field

@dataclass
class RadixNode:
    tokens: tuple[int, ...]
    kv_page_ids: list[int]
    ref_count: int = 0
    children: dict[int, 'RadixNode'] = field(default_factory=dict)

class RadixPrefixCache:
    def __init__(self) -> None:
        self.root = RadixNode(tokens=(), kv_page_ids=[])
STAGE 04 · RADIX MATCHER

Implementing Longest-Prefix Match & Node Splitting

Longest-Prefix WalkTrie TraversalPartial Match SplitEdge SplitCollect kv_page_idsCache HitPrefill UncachedTailCache Populatereturns pages

1.O(MatchLen) Lookup: Hashing/comparing token prefixes on edges executes in microseconds on CPU before GPU kernel launch.

2.Page Alignment: Align splits or pad partial trailing blocks cleanly to 16-token PagedAttention boundaries.

3.Prefix Hit Ratio: Returning both matched page IDs and unmatched suffix tokens seamlessly drives partial prefill.

Longest-prefix traversal returns cached KV page IDs for the matched head and splits edges cleanly for the uncached tail.

05
STAGE 05 · CACHE-AWARE SCHEDULINGadvanced

Longest-Prefix-First Scheduling vs. FCFS Starvation.

Why this matters: Prevent LRU cache thrashing with Longest-Prefix-First (LPF) scheduling bounded by starvation limits.

In a busy queue, FCFS execution can thrash the LRU cache if unrelated prompts interleave. Longest-Prefix-First (LPF) scheduling batches requests sharing the same active Radix branch together, maximizing KV reuse.

To prevent starvation of unique prompts, pair LPF with an aging boost so requests waiting > max_wait_ms promote to the front.

STAGE 05 · CACHE-AWARE SCHEDULING

Longest-Prefix-First Scheduling vs. FCFS Starvation

Waiting RequestQueueScheduler InputLongest-Prefix-FirstCache LocalityMax-Wait AgingGuardFairness CapCoalesced PrefillThroughput Winbounded by

1.FCFS Thrashing: Interleaving unrelated prompts in strict FCFS evicts warm branches before follow-up turns arrive.

2.LPF Grouping: Running requests sharing a Radix branch back-to-back maximizes KV reuse before eviction.

3.Starvation Guard: Promote any queued request exceeding max_wait_ms regardless of prefix match length.

Longest-Prefix-First scheduling groups requests on shared Radix branches while aging caps prevent tail starvation.

06
STAGE 06 · BLOCK ALIGNMENT & CPU OFFLOADadvanced

Page-Boundary Alignment & Tiered CPU-DRAM Offloading.

Why this matters: Extend KV capacity beyond GPU HBM by offloading cold leaf pages asynchronously to CPU DRAM over PCIe.

PagedAttention aligns KV blocks to fixed sizes (e.g., 16 tokens). Partial trailing tokens (< 16) are either recomputed or padded at system-prompt boundaries.

When GPU HBM fills, hot evicted KV pages can asynchronously offload over PCIe/NVLink to CPU DRAM (L2 KV Cache) rather than discarding them, reloading 5x faster than cold prefill.

STAGE 06 · BLOCK ALIGNMENT & CPU OFFLOAD

Page-Boundary Alignment & Tiered CPU-DRAM Offloading

GPU HBM L1 (>85%)Tier 1 CacheAsync PCIe Gen5 DMANon-Blocking512 GB CPU DRAM L2Tier 2 CacheReload on Cache HitWarm Restorestores in

1.Offload vs. Recompute: Reloading 1.3 GB of 8K-token KV from CPU DRAM over PCIe takes ~20 ms vs. ~300 ms to recompute on GPU.

2.Block Alignment: Fixed 16-token KV pages make DMA scatter-gather transfers simple and fragmentation-free.

3.Async Background: Start offloading cold ref_count==0 leaves at 85% HBM before allocation stalls occur.

Async PCIe Gen5 offloading to CPU DRAM L2 retains 10x more KV prefixes and reloads faster than GPU recomputation.

07
STAGE 07 · MULTI-TENANT SECURITYadvanced

Preventing Cross-Tenant Cache Leaks & Timing Side Channels.

Why this matters: Eliminate cross-tenant TTFT timing side channels by salting Radix roots with tenant and model identity.

Think of Preventing Cross-Tenant Cache Leaks & Timing Side Channels as the intuition layer for AI/LLM Prefix Caching & RadixAttention (Zero-Copy KV Sharing): Eliminate cross-tenant TTFT timing side channels by salting Radix roots with tenant and model identity.

Sharing a global Radix Tree without tenant isolation exposes a subtle TTFT timing side channel: Tenant B can probe whether Tenant A recently sent a secret system prompt by measuring faster TTFT on a cache hit! Always salt every Radix Tree root or block hash with tenant_id (and lora_id) so cross-tenant sharing is strictly disabled.

STAGE 07 · MULTI-TENANT SECURITY

Preventing Cross-Tenant Cache Leaks & Timing Side Channels

Timing Side ChannelLeak HazardRoot Key SaltHard IsolationPer-Tenant HBM CapNoisy NeighborMonitor Hit & EvictSLO Telemetrybounded by

1.TTFT Probe Attack: Without tenant salting, Tenant B can detect whether Tenant A used a secret prompt by measuring faster TTFT.

2.Zero Cross-Tenant Hits: Keying Radix roots by (tenant_id, model_version, lora_id) makes cross-tenant sharing impossible.

3.Quota Enforcement: Per-tenant HBM soft caps prevent one tenant's 32K prompts from evicting everyone else's caches.

Salting Radix roots by (tenant_id, model, lora) and enforcing per-tenant HBM caps eliminate timing side channels.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must only leaf nodes with `ref_count == 0` be evicted from the RadixAttention LRU queue?

Recommended Learning Flow