How Prefix Caching Works
When processing LLM requests, SGLang automatically:- Detects shared prefixes between incoming requests and cached sequences
- Reuses cached KV states instead of recomputing attention
- Stores completed requests in the cache for future reuse
- Evicts old entries when memory is full
Prefix caching happens automatically - no application changes needed. Just send your requests and SGLang handles the rest.
Cache Lifecycle
1. Request Arrival
When a request arrives, the scheduler searches for matching prefixes:python/sglang/srt/managers/schedule_policy.py:182-211
2. KV Cache Allocation
For uncached portions, new KV cache is allocated:python/sglang/srt/mem_cache/memory_pool.py:155-177
3. Attention Computation
During forward pass, attention uses both cached and new KV states:- New KV states: For uncached tokens
- Cache indices: Pointers to cached KV states
- Sequence lengths: Total length including cached portion
python/sglang/srt/layers/radix_attention.py:99-135
4. Request Completion
When a request finishes, its KV cache is inserted into the tree:python/sglang/srt/mem_cache/radix_cache.py:459-504
Already-cached portions are freed to avoid duplication. The tree maintains a single copy of each unique prefix.
Use Cases
System Prompts
Many applications use the same system prompt for every request:Few-Shot Examples
Few-shot prompting with examples benefits greatly from caching:Multi-Turn Conversations
Conversation history is incrementally cached:Document-Based QA
Long documents can be cached and queried multiple times:This pattern is common in RAG (Retrieval-Augmented Generation) applications where the same document is queried multiple times.
Memory Management
Protected vs Evictable Memory
Cache memory is divided into two categories:python/sglang/srt/mem_cache/radix_cache.py:607-639
Eviction Triggers
Eviction occurs when:- Memory pressure: Not enough space for new requests
- Scheduled eviction: Periodic cleanup of old entries
- Explicit flush: Manual cache clearing
python/sglang/srt/mem_cache/radix_cache.py:578-605
Only leaf nodes (endpoints of cached sequences) can be evicted initially. As leaves are removed, their parents may become new leaves and become evictable.
Eviction Policies
Choose the policy that best fits your workload:LRU (Least Recently Used)
Best for: General-purpose caching with temporal localityLFU (Least Frequently Used)
Best for: Caching popular prefixesFIFO (First In First Out)
Best for: Simple, predictable eviction Evicts oldest inserted nodes first, regardless of usage.Priority-Based
Best for: Multi-tenant or QoS-aware systemsAdvanced Features
In-Batch Prefix Caching
SGLang detects shared prefixes even within a single batch:python/sglang/srt/managers/schedule_policy.py:213-240
Extra Key Namespace
Separate cache namespaces usingextra_key:
- LoRA adapters: Separate cache per adapter
- Multi-tenancy: Isolate cache by customer
- Cache versioning: Invalidate by changing version
python/sglang/srt/mem_cache/radix_cache.py:67-79
Page Alignment
For memory efficiency, cache can be aligned to page boundaries:- Efficient memory allocation: No fragmented pages
- Better sharing: Only complete pages are shared
- Aligned access: Hardware-friendly memory access patterns
Set
--page-size based on your hardware and model. Typical values: 1 (no alignment), 8, 16, or 32.Performance Metrics
Cache Hit Rate
Monitor cache effectiveness:- RAG workloads: 80-95%
- Few-shot prompting: 70-90%
- Multi-turn chat: 60-80%
- Diverse queries: 20-40%
Memory Usage
Track cache memory:Time Savings
Measure prefill time reduction:Configuration
Key configuration options:Best Practices
- Design for reuse: Structure prompts with common prefixes
- Monitor hit rates: Low hit rates indicate poor prompt design
- Use appropriate eviction: Match policy to workload characteristics
- Set sufficient memory: Undersized cache leads to thrashing
- Leverage extra_key: Isolate cache when needed
Limitations
- Exact token match required: Even one different token breaks the prefix
- Special tokens matter: System tokens must match exactly
- Tokenizer dependence: Same text with different tokenizers won’t match
- Memory overhead: Tree structure adds ~10-20% overhead
- Eviction cost: Cache lookup and eviction have CPU overhead
Related Topics
- RadixAttention - The attention mechanism
- System Architecture - Overall system design
- Continuous Batching - Dynamic batching
