SGLang boosted multi-call LLM throughput by up to 6.4x and cut latency by up to 3.7x over vLLM, Guidance, and LMQL by keeping key-value (KV) cache across requests in a persistent radix tree instead of per-request scratch memory. Lianmin Zheng, Ying Sheng, and ten collaborators across UC Berkeley, Stanford, Shanghai Jiao Tong University, and Texas A&M introduced the system in December 2023 (updated June 2024) for programmatic LLM workloads.
Modern AI applications rarely send one isolated prompt. Agents loop through tool calls, evaluators run branch-solve-merge judges, few-shot pipelines prepend shared demonstrations, and structured extractors enforce JSON schemas. Stateless serving engines built around single chat completions discard every request’s KV cache at completion and step through constrained JSON one token per forward pass. SGLang co-designs a Python-embedded DSL with a runtime (SRT) combining RadixAttention, compressed finite state machines, and API speculative execution.
- Up to 6.4x throughput, 3.7x lower latency: Measured across ten multi-call benchmarks on Llama-7B (single NVIDIA A10G), Mixtral-8x7B (8x A10G), and Llama-2-70B (4x A100G 80 GB), with LLaVA-v1.5-7B reaching 1.15 image/s vs. 0.18 image/s for Hugging Face Transformers (6.4x).
- 50% to 99% cache hit rates at low overhead: Longest-shared-prefix-first scheduling averages 96% of offline optimal hit rates, while zero-hit ShareGPT runs add only 0.2 seconds out of 74.3 seconds (under 0.3% overhead).
- 1.6x faster JSON decoding: Merging singular FSM transitions lets the decoder jump across multi-token JSON syntax in one pass, while reusing preprocessed FSMs avoids a 2.4x compilation slowdown.
- Production Chatbot Arena gains: Over one month of single-worker serving, RadixAttention hit 74.1% reuse on Vicuna-33B (cutting first-token latency 1.7x) and 52.4% on LLaVA-NeXT-34B.
Retaining and scheduling prefix trees with RadixAttention
Autoregressive Transformers compute a KV tensor for every prompt token during prefill, and each token’s KV state depends strictly on prior tokens. Earlier engines captured only fragments of this overlap: Orca’s iteration-level scheduling eliminated batch padding without keeping finished KV tensors, while vLLM’s PagedAttention shared prefix blocks via copy-on-write within a single batch or static system prompt, not across dynamic request trees over time.
RadixAttention turns KV cache into an LRU-managed radix tree in CPU memory with negligible linear overhead. Unlike a token trie with one node per token, a radix tree labels edges with variable-length token spans (or image hashes) and splits an edge whenever a new request diverges mid-sequence. KV tensors live in non-contiguous GPU DRAM at 1-token page granularity, compatible with PagedAttention, continuous batching, tensor parallelism, FlashInfer, and Triton.
Two allocation rules keep cached state from crowding out active traffic:
- Unified GPU pool: Cached leaves and running requests share one DRAM pool rather than fixed partitions, so heavy batches can evict all unreferenced cache entries instead of shrinking concurrency.
- Leaf-first reference-counted LRU: Nodes track active request references; only
ref_counter == 0nodes are evictable, and LRU evicts leaves first so shared ancestor prefixes stay warm.
Request order matters just as much. Under First-Come, First-Served (FCFS) or random scheduling, mixing unrelated prompts evicts shared prefixes before sibling requests run. In Theorem 3.1, the authors prove that visiting a batch’s radix tree in Depth-First Search (DFS) order computes each edge once, hitting the lower bound sum(|e|) when cache capacity holds the longest request, and prove by induction that longest-shared-prefix-first sorting equals DFS offline (approximating it online for 50% to 99% hit rates, 96% of optimal).
Frontend-runtime co-design prevents the final scheduling race. SGLang’s Python DSL treats each prompt state s as an asynchronous stream supporting += (extend), gen, select, fork, join, image, and video, dispatching branches without blocking until s["var"] is read (2.1x fewer lines of code on the essay judge). When s.fork(k) spawns k parallel branches, firing all k prompts at once would prefill the shared prefix k times concurrently. Instead, a Frontend Hint inserts the shared prefix first before launching branch suffixes. Figure 8(c) confirms that disabling tree structure, cache-aware scheduling, frontend parallelism, or Frontend Hints each hurts throughput.
Jump-forward JSON decoding and API speculation
Prefix reuse shrinks prefill, yet constrained generation still stalls during decode. Guidance and Outlines convert regexes or JSON schemas into a Finite State Machine (FSM) and mask invalid logits on every step. Even when a schema prefix like {"summary": " has only one valid continuation, normal decoders still execute one sequential forward pass per token because the FSM sits outside the runner loop.
SGLang builds a Compressed FSM over characters, recursively merging singular transition edges (one successor, one valid character or string) into multi-character edges. Whenever decoding reaches a compressed edge, the runtime jumps forward in a single pass. To avoid tokenization artifacts from unnatural subword splits (summa, ry, ":_), SGLang retokenizes the prior text plus the compressed edge with the model’s tokenizer. In Section 6.3, Compressed FSM lifts JSON throughput 1.6x, while sharing preprocessed FSMs across batches avoids a 2.4x compilation slowdown.
For closed endpoints such as OpenAI’s GPT-3.5 and GPT-4, SGLang adds API speculative execution: ignoring stop sequences on an early gen call lets the model overshoot into the next template field (name: then job:), trimming input-token costs roughly 3x on three-field Wikipedia extraction.
How five serving workloads hit or miss the cache
Across the paper’s ten evaluation workloads, SGLang’s gains come from different combinations of tree depth, batch ordering, and jump-forward decoding rather than one uniform mechanism. Use the explorer below to compare how five representative workloads map onto RadixAttention and the Compressed FSM.
Select a workload (or use Left and Right arrow keys) to inspect its sharing geometry, why stateless baselines stall, and the measured result.
MMLU (5-shot) and HellaSwag (20-shot)
1- to 2-level treeEvery benchmark question shares the same multi-example demonstration prefix, and HellaSwag branches again across multiple answer choices.
- Why stateless engines stall
- Recomputing 5-shot or 20-shot example prefixes for every question burns prefill FLOPs and forces smaller batches due to duplicated KV memory.
- SGLang mechanism
- RadixAttention splits the root node after the shared examples; HellaSwag adds a second split per question stem across candidate completions.
- Measured evidence
- Achieves near-ceiling cache hit rates (up to 99% across evaluated workloads) and cuts both first-token latency and KV memory footprint.
- Scheduling sensitivity
- Longest-shared-prefix-first keeps the shared demonstration trunk pinned while sweeping through sibling questions.
Tree-of-Thought, Skeleton-of-Thought, and LLM Judge
Dynamic branchingPrograms fork mid-generation into parallel reasoning paths or evaluation rubrics that share the prior search history and prompt.
- Why stateless engines stall
- Sequential API calls underutilize intra-program parallelism, while naive concurrent forks race to prefill the same ancestor context redundantly.
- SGLang mechanism
- Frontend Hints insert the shared prefix first before dispatching parallel fork streams, and DFS-order scheduling sweeps subtrees before eviction.
- Measured evidence
- Disabling Frontend Hints, parallelism, or tree structure in Fig. 8(c) drops normalized throughput substantially on Tree-of-Thought and LLM Judge.
- Cache hit curve
- Ablating matched tokens on Tree-of-Thought directly shrinks max batch size and raises both first-token and total latency (Fig. 8a-b).
Multi-turn chat: short vs. long responses
Growing historyEach follow-up turn extends the prior conversation path in the radix tree, splitting only if sessions diverge from a shared system prompt.
- Why stateless engines stall
- Without cross-request persistence, turn 4 recomputes the KV cache for turns 1 through 3; under memory pressure, naive eviction drops shared trunks.
- SGLang mechanism
- Leaf-first LRU preserves the system prompt and active conversation stem; in Chatbot Arena, Vicuna-33B hit 74.1% reuse and 1.7x faster TTFT.
- Where speedup vanishes
- On 4-turn chat with long outputs (256-512 tokens per turn), autoregressive decode dominates runtime and SGLang matches vLLM with near-zero speedup.
- Zero-reuse overhead
- On 100 unrelated ShareGPT prompts with 0% reuse, radix tree maintenance added 0.2s out of 74.3s (under 0.3% overhead).
Regex-constrained JSON generation
Constrained decodeOutputs follow a strict schema with fixed keys, punctuation, and restricted value patterns enforced by a finite state machine.
- Why stateless engines stall
- Per-token logit masking steps through deterministic strings like {"summary": " one GPU forward pass at a time, and rebuilding FSMs per request lags.
- SGLang mechanism
- Compressed FSM merges singular edges into multi-token jump-forward passes and retokenizes the full prefix to avoid BPE boundary artifacts.
- Measured evidence
- Compressed FSM lifts JSON decoding throughput 1.6x, and caching preprocessed FSMs across batches avoids a 2.4x slowdown.
- Accuracy caveat
- Multi-token string choices (like Excellent vs. Above Average) can still distort choice probabilities without path marginalization (Appendix B.3).
LLaVA image and video question answering
Hashed media keysVisual encoders turn images or video frames into hundreds or thousands of prompt tokens queried repeatedly across questions.
- Why stateless engines stall
- Reference Hugging Face pipelines lacked continuous batching and recomputed visual tokens on every follow-up question about the same image.
- SGLang mechanism
- Hashes input images into radix-tree edge keys, reusing cached visual KV states across requests; LLaVA-NeXT-34B hit 52.4% reuse in Chatbot Arena.
- Measured evidence
- LLaVA-v1.5-7B reached 1.15 image/s vs. 0.18 image/s (6.4x) on A10G; LLaVA-NeXT-34B video reached 0.10 frame/s vs. 0.02 frame/s (5x) on A100G.
- Comparison caveat
- Because Guidance, LMQL, and vLLM v0.2.5 lacked support for those models, Table 2 compares against the authors' Hugging Face baseline.
Source: Zheng et al. (2024), Figures 3, 8, 9, and Section 6.2.
If you skip the tabs, five operational rules summarize where SGLang’s gains appear:
- Few-shot batches (MMLU, HellaSwag): Two-level radix splitting caches both shared demonstrations and question stems across answer choices, pushing cache hit rates up to 99%.
- Branching programs (Tree-of-Thought, LLM Judge): Frontend Hints and longest-prefix-first scheduling keep parent context warm across parallel
forkstreams instead of recomputing roots concurrently. - Multi-turn chat: Prefix reuse shines when outputs are short (74.1% reuse and 1.7x lower TTFT on Vicuna-33B in production), whereas long 256 to 512 token responses become decode-bound and erase the speedup over vLLM.
- JSON schemas: Compressed FSM jump-forward passes raise throughput 1.6x once FSM compilation is amortized across batches (avoiding a 2.4x compilation penalty).
- Multimodal media: Hashing image inputs into radix-tree keys reuses expensive visual token prefills (52.4% hit rate on LLaVA-NeXT-34B in Chatbot Arena; 1.15 vs. 0.18 image/s on LLaVA-v1.5-7B).
Limits, scheduling traps, and modern context
Five caveats bound how far the paper’s headline numbers generalize in production.
First, RadixAttention only accelerates prefill-heavy or prefix-shared workloads. When requests emit hundreds of unique tokens and share little history, decode memory bandwidth dominates runtime; on long multi-turn chat, SGLang’s throughput collapses onto vLLM’s baseline. On completely unshared ShareGPT traffic, RadixAttention adds negligible overhead (0.2s out of 74.3s), so keeping it enabled is safe, yet it creates zero speedup without prefix overlap.
Second, greedy prefix scheduling introduces request starvation. Sorting the waiting queue by longest matched prefix maximizes cache reuse, but a steady stream of requests hitting a hot system prompt can indefinitely delay requests with cold prefixes. The authors explicitly flag this gap and point to fair queuing schemes such as Virtual Token Counter as future integration work.
Third, the Compressed FSM does not eliminate token-boundary probability bias. Merging deterministic spans is exact, whereas multi-token choice branches (Excellent|Above Average|Fair|Below Average) still skew sampling probabilities toward the first token of each option unless the runtime marginalizes across all valid tokenizations. Similarly, SGLang’s experimental compiler mode (Appendix D) cannot trace data-dependent Python branches, and using GPT-4 to reorder prompt graph nodes for 60 extra shared tokens on average silently broke prompt semantics on 3 of 15 test templates.
Fourth, cache capacity stops at GPU HBM and distributed routing is weakly consistent. The evaluated RadixAttention keeps KV pages strictly in GPU DRAM rather than spilling warm prefixes to host RAM or NVMe. Under data parallelism across multiple workers (Appendix A.4), a central router tracks worker subtrees via an eventually consistent meta-tree fed by asynchronous worker eviction queues, trading strict cache locality against load balance across four workers on MMLU.
Finally, the serving landscape adopted the core idea. The authors themselves note in a footnote that later vLLM releases began integrating experimental automatic prefix caching inspired by RadixAttention. In modern inference stacks, prefix-tree KV retention sits alongside PagedAttention memory paging, Sarathi-Serve chunked prefill, and DistServe prefill-decode disaggregation as standard building blocks. For engineers designing LLM backends today, the lasting lesson is architectural: structure multi-call applications around stable, front-loaded prefixes and let a prefix-aware scheduler turn shared context from wasted FLOPs into shared memory.


