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.
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.
Why Identical Token Prefixes Produce Bit-Identical KV Tensors
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.
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.
Compressed Prefix Trie Mapping Token Edges to Physical KV Pages
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.
- 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.
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?
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.
Reference Counting & Leaf-First LRU Eviction
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.
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=[])Implementing Longest-Prefix Match & Node Splitting
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.
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.
Longest-Prefix-First Scheduling vs. FCFS Starvation
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.
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.
Page-Boundary Alignment & Tiered CPU-DRAM Offloading
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.
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.
Preventing Cross-Tenant Cache Leaks & Timing Side Channels
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: Make the trade-off yourself.
Why must only leaf nodes with `ref_count == 0` be evicted from the RadixAttention LRU queue?