Skip to main content
Prefix caching is a key optimization in SGLang that allows multiple requests to share Key-Value (KV) cache for common token sequences. This dramatically reduces memory usage and computation time, especially for workloads with repeated context.

How Prefix Caching Works

When processing LLM requests, SGLang automatically:
  1. Detects shared prefixes between incoming requests and cached sequences
  2. Reuses cached KV states instead of recomputing attention
  3. Stores completed requests in the cache for future reuse
  4. 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:
Reference: python/sglang/srt/managers/schedule_policy.py:182-211

2. KV Cache Allocation

For uncached portions, new KV cache is allocated:
Reference: python/sglang/srt/mem_cache/memory_pool.py:155-177

3. Attention Computation

During forward pass, attention uses both cached and new KV states:
The attention backend (e.g., FlashInfer) receives:
  • New KV states: For uncached tokens
  • Cache indices: Pointers to cached KV states
  • Sequence lengths: Total length including cached portion
Reference: python/sglang/srt/layers/radix_attention.py:99-135

4. Request Completion

When a request finishes, its KV cache is inserted into the tree:
Reference: 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:
With prefix caching, the 800-token system prompt is processed once and reused, reducing prefill time by ~96% for subsequent requests.

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:
Reference: python/sglang/srt/mem_cache/radix_cache.py:607-639

Eviction Triggers

Eviction occurs when:
  1. Memory pressure: Not enough space for new requests
  2. Scheduled eviction: Periodic cleanup of old entries
  3. Explicit flush: Manual cache clearing
Reference: 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 locality
Use when recent requests are likely to be repeated soon.

LFU (Least Frequently Used)

Best for: Caching popular prefixes
Keeps frequently-accessed prefixes even if not accessed recently.

FIFO (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 systems
Requests can specify priority levels to influence cache retention.
For most use cases, LRU provides the best balance of hit rate and simplicity. Use priority-based eviction for production systems with different SLA tiers.

Advanced Features

In-Batch Prefix Caching

SGLang detects shared prefixes even within a single batch:
Reference: python/sglang/srt/managers/schedule_policy.py:213-240

Extra Key Namespace

Separate cache namespaces using extra_key:
Use cases:
  • LoRA adapters: Separate cache per adapter
  • Multi-tenancy: Isolate cache by customer
  • Cache versioning: Invalidate by changing version
Reference: python/sglang/srt/mem_cache/radix_cache.py:67-79

Page Alignment

For memory efficiency, cache can be aligned to page boundaries:
This ensures:
  • 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:
Typical hit rates:
  • 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

  1. Design for reuse: Structure prompts with common prefixes
  2. Monitor hit rates: Low hit rates indicate poor prompt design
  3. Use appropriate eviction: Match policy to workload characteristics
  4. Set sufficient memory: Undersized cache leads to thrashing
  5. Leverage extra_key: Isolate cache when needed
For maximum benefit, organize your application to send requests with shared context consecutively or in batches.

Limitations

  1. Exact token match required: Even one different token breaks the prefix
  2. Special tokens matter: System tokens must match exactly
  3. Tokenizer dependence: Same text with different tokenizers won’t match
  4. Memory overhead: Tree structure adds ~10-20% overhead
  5. Eviction cost: Cache lookup and eviction have CPU overhead