SGLang keeps the KV cache of every finished request in a radix tree of token runs, so a later request that begins with the same tokens skips recomputing them; its scheduler, router and structured-output path are built around reusing that tree.
Fig. 1, step by step: customer B of section 2's toy bank assistant, through one deployment (schematic layout; the token counts are the page's radix cache's)
cache_aware, sends the request to the replica likely to hold its prefix unless the load is imbalanced./generate) applies the chat template and turns the text into token ids: 15 for this prompt. Three processes per server talk over ZeroMQ sockets so that tokenizing, scheduling and detokenizing never block one another.You need: prefill, decode and the KV cache (the keys and values every layer computed for every earlier token) from the parent Topic: inference-and-serving; continuous batching, paged attention and prefix caching as ideas (keeping the KV after a request ends so the next request with the same beginning reuses it) from Batching, KV cache and scheduling in depth. The other engine, read the same way, is vLLM: inside the default engine.
fcfs (default), or cache-aware lpm (longest prefix match) and dfs-weight (section 4).| SGLang v0.5.21 | vLLM v0.31.0 | |
|---|---|---|
| Prefix cache | A radix tree of token sequences, one node per shared run of tokens, page size 1 token by default (overrides.py L1280); the default class is UnifiedRadixCache (registry.py L80) | A hash per full 16-token block, chained over the blocks before it (kv_cache_utils.py L684); only full blocks are reusable |
| On by default | Yes; --disable-radix-cache turns it off (memory.py L64) | Yes (enable_prefix_caching, cache.py L142) |
| Eviction | Least recently used leaf that no running request holds; lfu, slru, priority, tlru on request (memory.py L25) | Least recently freed block, a request's tail block first (block_pool.py L777) |
| Queue order | fcfs by default; cache-aware lpm and dfs-weight on request (schedule.py L82) | fcfs by default, priority on request (scheduler.py L160) |
| CPU work hidden behind the GPU | Overlap scheduler, on by default (scheduler.py L1941) | Asynchronous scheduling, on unless a feature disables it (config/vllm.py, read for the root's Serving simulator) |
| Structured output | XGrammar by default; llguidance and Outlines selectable (serving_hook.py L219) | XGrammar or guidance (README) |
| Router | SGLang Model Gateway (Rust), cache_aware by default (main.rs L150) | None in the engine; llm-d or the production stack in front (LLM serving in production) |
Everything is read from source at SGLang v0.5.21 (tag commit e00930c5) and vLLM v0.31.0, with file and line beside each claim. Three kinds of evidence are added to the published record, each labelled where it appears: the engines' own prefix-cache classes replayed on the same request traces (section 3); SGLang's own scheduling-policy code ordering real queues (section 4); and SGLang v0.5.21 built from source and run on an Apple M1 Pro through its MLX backend (sections 3 to 6 and 11), which also surfaced bugs on Apple silicon: the release would not start, its cache returned another request's text, and eviction, chunked prefill and cache flushes crashed it. The independent comparison of the two engines is SemiAnalysis InferenceX (section 10). The small open model measured here is Qwen3-0.6B (28 layers, 8 KV heads of 128 dimensions, so 114,688 bytes of KV per token at 16-bit precision, as the root's Engine bench tab measured); the running example is the root's chat assistant.
The problem it started from. In late 2023 most engines threw a request's KV cache away the moment the request finished, yet real traffic repeats itself: every chat turn resends the whole conversation, few-shot prompts resend the same examples, an agent resends its growing history on every step, and a self-consistency run asks the same question several times. The SGLang paper (Zheng et al., arXiv 2312.07104, December 2023, NeurIPS 2024, from the LMSYS group behind Vicuna and Chatbot Arena) proposed two things: a runtime that keeps every request's KV cache in a radix tree so that calls share whatever prefix they have in common (RadixAttention), and a small Python language for programs that make many model calls. The authors report up to 6.4 times the throughput of the systems they compared against authors' measurement.
The frontend language (python/sglang/lang, still shipped) writes a multi-call program as a function over a prompt state s: gen generates into a named variable, select picks among fixed choices by their likelihood, and fork copies the state into parallel branches. Adapted from the frontend docs (not run here):
@sgl.function
def tips(s):
s += "Here are two tips for staying healthy: 1. Balanced Diet. 2. Regular Exercise.\n\n"
forks = s.fork(2) # two branches share everything above
for i, f in enumerate(forks):
f += f"Now, expand tip {i+1} into a paragraph:\n"
f += sgl.gen("detail", max_tokens=256, stop="\n\n")
s += "Tip 1:" + forks[0]["detail"] + "\nTip 2:" + forks[1]["detail"] + "\n"
s += "Overall, " + sgl.select("verdict", choices=["diet", "exercise"]) + " matters more."
In the tree, the shared opening becomes one node with two children, one per branch, and the final call reuses everything before it: the program's structure is exactly the prefix sharing the runtime exploits. Most deployments today send plain requests to the OpenAI-compatible server instead, and the tree finds the same sharing without being told, so the rest of this page is about the runtime.
Releases came every few weeks: v0.4 (December 2024) added the overlap scheduler, the cache-aware router and XGrammar (LMSYS, 2024-12-04); 2025 brought prefill/decode disaggregation and large-scale expert parallelism for DeepSeek (section 9); 2026 added TPUs through SGLang-Jax and Apple silicon, first through MLX and, from v0.5.22 (PyPI 2026-10-16, which also requires Python 3.11 or newer), through the standard PyTorch backend too (releases). A second TPU engine, built on TorchTPU (PyTorch running natively on TPUs, see TPUs and other accelerators), was announced on 20 October 2026, and Meta's PyTorch-TPU lead says "SGLang-TorchTPU is running in production at Meta today" (Google Developers Blog, Oct 20 2026). The release read here, v0.5.21, was published on 2026-10-02 with 779 pull requests from 227 contributors, and makes a Rust implementation of the prefix-cache tree the default (release notes; tag commit e00930c5). v0.5.18 (2026-08-22) overlapped weight loading with graph capture: 35.6 s against 84.8 s to start Qwen3-32B on an H100 with the opt-in flag, against the plain default project's measurement. The project is hosted by the non-profit LMSYS and its README lists xAI, NVIDIA, AMD, LinkedIn, Cursor and the large clouds among adopters, "on over 400,000 GPUs" (README) project's own claim.
The problem. A prefix cache must answer one question fast, millions of times: of the tokens this new request starts with, how many have I already computed, and where is their KV? A dictionary from whole prompts finds only exact repeats. A trie (prefix tree) finds the longest shared beginning by walking one token per level, but a 2,000-token system prompt would be 2,000 nodes deep. A radix tree is a trie whose edges carry whole runs of tokens: the 2,000-token system prompt is one node and each conversation that continues it is one more.
What each node holds (TreeNode, radix_cache.py L249): its run of token ids (the key), the indices of the KV slots holding those tokens' keys and values in the GPU pool (the value), its children (indexed by first token), a lock reference count and a last-access time for eviction. The tree only maps token runs to slot numbers, which is why it can live on the CPU.
Fig. 2 runs eight requests from a toy bank assistant through the page's port of SGLang's cache (src/iso/ref.py, which reproduces SGLang's and vLLM's own classes request by request, section 3): one word per token, a pool of 40 KV slots. Which slot numbers a node holds is drawn lowest free slot first; every count is the cache's.
The five operations of Fig. 2, each with its line in v0.5.21's radix_cache.py:
Walk from the root along the child whose first token matches, comparing token by token (L639). The hit is capped at the prompt length minus one, so at least one token is computed to produce the first output (schedule_batch.py L1702).
If the walk stops inside a node's run, the node is cut in two so the shared part becomes its own node (L665); only the slot list is sliced, nothing moves on the GPU.
A finished request's prompt and output (all but the last token, whose KV was never computed) go in; the part already present is reused and the duplicate slots freed (L698). The leaf is split at the prompt boundary so the output can be evicted before the prompt.
A running request increments the lock count of every node on its path (L583); a prefix in use never disappears under it.
When the pool is full, pop the least recently used unlocked leaf, free its slots, and push its parent if it has just become a childless unlocked leaf (L553). Branches are eaten from the tips inward, so the shared trunk survives longest.
vLLM keeps the same kind of cache as a table of hashed blocks (section 3). Replaying Fig. 2's eight requests through both, in the widget beside this text, shows three differences: the tree shares the tail of a partially filled block and the hash table cannot; the tree evicts whole leaves while blocks go one at a time; the bookkeeping is a handful of nodes against a row per block. Both modes run the page's port of the two caches.
_compute_max_prefix_len; vLLM's max_cache_hit_length = num_tokens - 1). Blocks of 4 reuse 12 (three full blocks inside the first 13 tokens); with vLLM's real 16-token blocks a 14-token prompt reuses nothing. Step to request 6 in the widget: with this pool both caches still hold it.meta_info.cached_tokens in every native response, #cached-token in the prefill log line, the hit counters with --enable-metrics; compare with --disable-radix-cache.Opens on the last request; step back through all 17 frames, or switch the mode. Pool of 40 slots, 10 blocks of 4 (vLLM uses 16; 4 keeps the picture readable).
A claim still repeated in comparisons is that SGLang's tree "wins on shared-prefix traffic" against vLLM's block cache. Both structures answer the same question, so it can be tested directly: replay the same requests through both caches with the same pool and count the reused prompt tokens. That was done here with the engines' own classes, SGLang v0.5.21's UnifiedRadixCache and RadixCache and vLLM v0.31.0's Scheduler and KVCacheManager, on four traces at six pool sizes: 4,800 requests through each class, 72 replays, every one identical request by request to the page's small port (src/iso/ref.py), which is what runs below.
With room for everything they are within one point: the tree reuses 87.6% of the chat trace's prompt tokens and the blocks 86.8%; on the coding-agent trace 97.2% against 97.0%; on unrelated prompts both reuse nothing. The tree's small lead is the tail of the last, partially filled block of each shared prefix, which a hash of full blocks cannot match (up to 15 tokens a request with 16-token blocks). When the pool is tight the blocks can win: with 6,000 slots on the document trace the blocks reuse 69.7% and the tree 65.4%, because vLLM evicts one block at a time, tail first, so a document can lose its last blocks and keep its first; the tree evicts whole leaves, and once a document's questions are gone the 800-token document node is itself a leaf and goes all at once.
Bookkeeping differs far more than hits. At the end of the unbounded chat replay the tree holds 483 nodes where vLLM holds 3,641 cached blocks, each with its hash. A tree lookup compares tokens along one path; a block lookup hashes every full block of the prompt (SHA-256 by default, cache.py L144). Both are cheap next to a forward pass, and SGLang moved its tree to Rust in v0.5.21 to keep that CPU work small.
Share of prompt tokens reused against pool size, recomputed live by the checked port; requests run one at a time so only the cache differs. Pool slots convert to memory at Qwen3-0.6B's 114,688 bytes of KV per token. The first two traces come from the root simulator's generator; each trace is described above the slider.
Tokens reused by the tree minus tokens reused by the blocks, for the trace and pool chosen above. Above the line the tree reused more (usually the tail of a partial block, at most 15 tokens); below it the blocks reused more (a prefix whose first blocks survived eviction while the tree had dropped the whole node).
Checked: 72 of 72 real-class replays identical to the port (14,400 requests: SGLang v0.5.21 UnifiedRadixCache and RadixCache, vLLM v0.31.0 Scheduler and KVCacheManager), run 2026-10-08.
UnifiedRadixCache (Python tree core, a real token allocator and a tiny KV pool on the CPU, set up as in SGLang's own unit tests) and its older RadixCache, both from v0.5.21. v0.5.21 makes a Rust tree core the default; the Python core was run here (the Rust extension was not built), and SGLang runs the same unit suite against both (test/registered/unit/mem_cache/test_rust_unified_radix_cache_unittest.py).Scheduler and KVCacheManager from v0.31.0, with a fake model runner, exactly as the root's Serving simulator tab checked its own engine.Eight four-turn conversations at once under one 600-token system prompt, on SGLang v0.5.21 on the M1 (section 11); each turn adds 60 to 120 tokens of user text and 64 tokens of answer and resends the whole history; KV pool 24,000 tokens. By the fourth turn (about 1,166 prompt tokens, 1,002 of them cached) the mean time to first token was 2.32 s with the radix cache and 4.81 s with --disable-radix-cache, 2.1 times faster; on the first turn, where only the system prompt can be shared, 2.32 s against 2.73 s. But decoding was slower with the cache on (208 against 86 ms per output token), so the whole job took longer (59.9 s against 38.8 s): the Apple backend copies KV between its pool and per-request buffers when the cache is on, a cost a GPU engine with paged attention does not pay (cause not isolated). measured on Apple M1 Pro
The problem. When many requests wait at once and the KV pool cannot hold every shared prefix, the order in which the scheduler admits them decides whether a prefix is reused or evicted before its siblings arrive. Take 96 questions about eight 800-token documents, sent at once in a shuffled order, with a pool that holds about three documents: first come, first served visits the documents at random, so a document is computed, evicted to make room, and computed again a few requests later.
How SGLang orders the queue. Before every prefill batch the scheduler matches each waiting request against the tree and sorts the queue by a schedule policy (calc_priority, schedule_policy.py L260):
Fig. 3 runs a small case through the page's scheduling model, both lanes from the same queue: 16 questions of 20 to 80 tokens about 5 documents of 800 tokens, arriving in one shuffled order, and a 3,000-token pool, room for about three documents with their questions (illustrative sizes; every order, admission, hit and eviction is the model's, whose orders match SGLang's own code).
Arrival order. The default since v0.4.4 (2025-03-13); v0.3 to v0.4.3 defaulted to lpm (server_args.py at v0.4.3 and at v0.4.4); the release notes read here do not give the reason unconfirmed.
Longest cached prefix first, so what is cached is used before it can be evicted (L477). The docs suggest it "if the workload has many shared prefixes" and warn of more scheduling overhead (hyperparameter tuning).
If several waiting requests share 32 or more tokens that are not yet cached, only the first is admitted now; the rest move back and hit the cache once it is computed (L373, thresholds 32 and 32 at L100). Without it, ten questions about an uncached document in one batch would each compute the document.
Walk the tree depth first, heaviest subtree (most waiting requests) first (base_prefix_cache.py L325). The paper proves that for a fixed batch a depth-first visit gives the optimal hit rate when the cache holds at least the longest request, and that longest-prefix-first is equivalent (Theorem 3.1, arXiv 2312.07104).
With more than 128 requests waiting, lpm (and hrrn) silently fall back to arrival order to save the sorting cost (_determine_active_policy, L331). dfs-weight has no such cut-off.
The widget beside this text runs the same model with the settings the reader picks, on 96 questions by default, and all four of SGLang's main policies; it opens on round 1 and steps round by round.
Try the three moves the policies predict: raise the pool to 9,000 and every order converges (ordering pays only when the cache is scarce relative to the prefixes waiting for it); change the arrival order and fcfs and random swing widely while the cache-aware orders hardly move; raise the questions above 128 and lpm behaves like fcfs until the queue drains below the cliff, losing its lead to dfs-weight.
--schedule-policy lpm on a busy server where 300 requests are usually waiting. How much does the queue order change?_determine_active_policy returns FCFS for lpm, so the sort is skipped entirely, and it comes back only when the queue drains. On a server always deep in backlog, lpm does nothing; dfs-weight has no cut-off but costs a tree walk per scheduling pass. The real fix for a permanent backlog is more capacity or a router that keeps related requests together (section 8).hrrn (highest response ratio next, aging by processed tokens, L496) and priority scheduling.#cached-token against #new-token in the prefill log, per-request cached_tokens, and the total time of a fixed batch under each policy.Top: the waiting queue in the order the policy sorted it, one square per question coloured by its document; outlined squares are admitted this round. Bottom: how much of each document the tree holds after the round. Defaults: 96 questions of 20 to 80 tokens on 8 documents of 800 tokens, pool 3,000 tokens, arrival order 1. Over ten arrival orders the share of prompt tokens served from cache was fcfs 51.0% (35 to 68), lpm 86.2% (85 to 86), dfs-weight 84.1% (82 to 86) and random 60.2% (41 to 80); with a 6,000-token pool, which holds most documents, every order lands within a few points: fcfs 79.1%, lpm 83.2%, dfs-weight 81.5%, random 75.7%.
A round: match every waiting question against the tree; order the queue by the policy; admit questions in that order while each one's new tokens plus its output fit in the free and evictable pool and the round's prefill stays under 16,384 tokens, stopping at the first that does not fit; run the admitted ones to completion and insert them. Real SGLang admits continuously, reserves output space by an estimate scaled by --schedule-conservativeness, and overlaps prefill with running decodes, so the numbers are the policy's effect in isolation, not a throughput prediction. SGLang v0.5.21's own SchedulePolicy.calc_priority was run alongside on a shadow RadixCache and produced the identical order on 475 queue orderings and prefix matches, 0 mismatches. Arrival orders and the random policy use the root simulator's seeded generator.
SGLang v0.5.21 on the M1 Pro (MLX backend, Qwen3-0.6B 4-bit): 64 questions (40 tokens each) about 8 documents of 800 tokens, all sent at once in one fixed shuffled order, 16 output tokens each, at most 8 running, two runs per policy where the server survived (restarted for each). The pool had to be roomy (24,000 tokens) because this backend crashed whenever the radix cache had to evict (section 11), so the scarce-cache case above could not be run for real; what still separates the policies is in-batch sharing. Result: fcfs 77.4% of prompt tokens from cache, batch done in 24.1 s (runs 20.4 to 27.9); lpm 77.4%, 21.3 s (runs 20.8 to 21.9); random 80.4%, 19.5 s (one run). Within the run-to-run spread the policies did not differ: the requests reached the server 2 ms apart and at most 8 ran at once, so the queue was ordered in small slices and most documents were cached after their first question whatever the order. dfs-weight crashed the server in all four attempts and has no result. measured on Apple M1 Pro The isolated model above admits a whole round under a token budget rather than 8 requests at a time, so it does not reproduce these digits; compare the direction only.
Illustrative durations: 5 ms of GPU work and 1.5 ms of CPU work per step. Steady state: GPU plus CPU per step in the plain loop, the larger of the two with overlap.
The problem. Every decode step has CPU work around the GPU work: pick the batch, allocate KV slots, match prefixes, build the input tensors, then read the sampled tokens back, check stop conditions, free finished requests and insert them into the tree. In a plain loop the GPU waits through all of it. With a small model, or many GPUs splitting each step so each one's forward is short, the CPU share can be large: the SGLang v0.4 post says an unoptimized engine "can spend as much as half of its time on CPU overhead" (LMSYS, 2024-12-04) project's claim.
How it works. The overlap loop (event_loop_overlap, scheduler.py L1941) launches batch k on the GPU without waiting, then processes the results of batch k minus 1 and schedules batch k plus 1 while the GPU is busy. Batch k plus 1 needs tokens batch k has not produced yet, so they are passed as placeholders the GPU fills in when it gets there (the FutureMap, overlap_utils.py L248). The plain loop remains (event_loop_normal, L1906) behind --disable-overlap-schedule. The idea is NanoFlow's, as the v0.4 post credits; vLLM's asynchronous scheduling does the same job.
The animation, step by step
--disable-overlap-schedule.Not measured: with the overlap loop on and off, a sequence of 32 requests of 128 tokens in and out at concurrency 1, 4 and 8 crashed the server every time (6 configurations, each retried once on a fresh server). With the overlap on, the Metal out-of-memory error inside the chained-decode path; with it off, an error in the overlap bookkeeping (overlap_utils.py, stash). A short decode (32 tokens) had worked in the first smoke tests; 128-token outputs in sequence did not. The 1.1 times above is the project's own figure.
Constrained decoding sets the probability of every token that would break a grammar (a JSON schema, a regular expression, an EBNF grammar) to zero before sampling, using a token mask over the whole vocabulary (151,936 tokens for Qwen3). How the masks are built, and how XGrammar's context-independent tokens make them cheap, is taught on Sampling and decoding; this section is how SGLang wires it in.
The default backend is XGrammar (serving_hook.py L219), with llguidance and outlines selectable by --grammar-backend; its mask is computed on the CPU, overlapped with the GPU's forward pass, and its paper reports up to 100 times faster than earlier engines (Dong et al., arXiv 2411.15100) authors' measurement. A request asks for it with json_schema, regex or ebnf in its sampling parameters, or the OpenAI response_format. On the M1, 24 of 24 answers with a JSON schema parsed as JSON against 0 of 24 without it (unconstrained, the model wraps its JSON in a Markdown code fence).
The compressed FSM, and what became of it. In February 2024 SGLang introduced jump-forward decoding: where the grammar allows only one continuation (the key {"name": " in a schema, say), append that whole string in one prefill step instead of decoding it token by token, with the radix tree keeping the KV; the post reported up to 2 times lower latency and 2.5 times higher throughput than Outlines with vLLM (LMSYS, 2024-02-05) vendor. It was removed in v0.4.4 "to simplify the code maintenance" (PR #4032, merged 2025-03-03). In v0.5.21 the backends still define try_jump_forward (xgrammar_backend.py L167) but nothing in the scheduler calls it, so no current SGLang release jump-forwards: forced strings are decoded one masked token at a time.
Measured on the M1 with Qwen3-0.6B: first request with a new schema 957 ms to first token (compilation included); 13.4 ms against 4.9 ms per output token with and without the schema measured on Apple M1 Pro, where the grammar also stops decode steps being chained (section 5), which is much of that per-token cost here.
Twelve chat requests asking for an invented person, with and without a JSON schema (name, city, age, up to four skills) through the default XGrammar backend; two passes each. Grammars apply on the Apple backend only with --mlx-enable-sampling: without the flag the same requests were decoded greedily without a mask, the grammar rejected the first token (a code fence) and every request ended after 2 tokens with invalid output (0 valid of 24). One server run with another job on the machine (load average 13.7), so read the ratio, not the absolute times.
A server starts with one command (sglang serve --model-path ..., or the older python -m sglang.launch_server) and serves the OpenAI API plus a native /generate endpoint. The knobs that matter, with their v0.5.21 defaults read in source:
| Flag | Default | What it trades |
|---|---|---|
--mem-fraction-static | chosen by a heuristic | Share of GPU memory for weights plus the KV pool. Higher means more cached tokens and bigger batches, until activations or CUDA graphs run out of memory; the docs say to leave 5 to 8 GB free and read available_gpu_mem in the start-up log (hyperparameter tuning). |
--max-total-tokens | derived from the line above | Caps the KV pool in tokens (the experiments here set it to make the cache scarce). The pool, not --context-length, sets the real prompt limit: v0.5.19 refuses a prompt of at least min(context − 1, pool − 1) − 5 tokens, and nothing makes the pool hold the advertised window. Read the pool size in the start-up log and lower the context length if it is smaller (a 1,048,576-token window on a 681,280-token pool led to Cloudflare's KV cache exposure). |
--chunked-prefill-size | 2,048 under 20 GB of GPU memory; 4,096 under 60 GB; 8,192 for H100 and H200; 16,384 above (memory_hook.py L88) | Longest piece of a prompt computed in one step. Smaller means decode steps wait less behind a long prefill (lower inter-token latency) and less activation memory, at some prefill throughput; -1 turns chunking off. The trade is measured on Batching, KV cache and scheduling in depth. |
--max-prefill-tokens | 16,384 (schedule.py L67) | Prefill tokens admitted per batch. |
--max-running-requests | bounded by the pool | Concurrency cap; lower it if decode runs out of memory. |
--schedule-policy | fcfs | Section 4. lpm or dfs-weight for deep queues over shared prefixes. |
--schedule-conservativeness | 1.0 (L135) | How much KV the scheduler reserves for the outputs of admitted requests. Lower (0.3) admits more when requests stop early; higher (1.3) if the log keeps saying KV cache pool is full. Retract requests (retraction is SGLang's word for preemption: the request is pushed back to the queue and recomputed). |
--page-size | 1 (64 or 128 with some attention backends) | Granularity of the KV pool and the tree. |
--radix-eviction-policy | lru | lfu or slru for a stable hot set, priority with priority scheduling, tlru to keep only the history each conversation's next turn needs to meet a TTFT budget (eviction policies; T-LRU is arXiv 2510.15152). |
--enable-hierarchical-cache | off (memory.py L99) | HiCache: the tree spans GPU memory (L1), host memory (L2, twice the GPU pool by default) and optionally storage shared across machines (L3: file, Mooncake, 3FS, NIXL, AIBrix), so evicted prefixes are copied back instead of recomputed (HiCache design). |
--disable-overlap-schedule, --grammar-backend, --enable-metrics | overlap on, xgrammar, metrics off | Sections 5 and 6; Prometheus metrics at /metrics. |
--tp, --dp, --ep, --enable-dp-attention | 1, 1, 1, off | Section 9. |
Reading the log. Each decode batch prints a line such as #running-req: 233, #token: 370959, token usage: 0.82, gen throughput (token/s): 4594.01, #queue-req: 317 (the docs' example on an H100-class GPU). Token usage above 0.9 with a queue means the pool is the limit; a queue of 0 in an offline job means the client is not sending fast enough (the docs suggest 100 to 2,000 waiting for offline throughput); frequent retraction means the scheduler admitted more than fit. The prefill lines print #new-token and #cached-token, the radix tree's hit for that batch.
The problem. With several replicas of a model, each has its own radix tree. A round-robin load balancer sends a conversation's next turn to a replica that has never seen it, so the hit rate falls toward one over the number of replicas; sending every request to the replica holding its prefix piles popular prefixes onto one replica. The router has to trade cache affinity against load.
The router (now the SGLang Model Gateway, written in Rust) keeps an approximate radix tree per worker of the request texts it has sent there, in characters rather than tokens so it never tokenizes, and never asks the workers what they actually hold. Imbalance means the busiest worker has more than balance_abs_threshold requests more than the idlest and more than balance_rel_threshold times as many; a prefix match counts when the matched share exceeds cache_threshold. The file's header comment says a miss goes to the worker with the "smallest tree size"; the code picks the least loaded, ties broken at random. Trees are trimmed least recently used on a timer.
Defaults, and whether they act. The command-line defaults are a 0.3 cache threshold, 64 requests absolute and 1.5 times relative imbalance, eviction every 120 s and up to 226 tree nodes; the Rust struct's own Default (0.5, 32, 1.1, 30 s, 10,000) and the Python launcher (eviction 60 s) disagree with them, so check which entry point you use. At those defaults the imbalance rule may never act: replaying the Mooncake conversation trace on three real replicas, LLM serving in production (section 2) never saw it fire, because no replica ever had more than 10 requests in flight, far below 64 measured there. The v0.4 post reported 1.9 times the throughput and a hit rate of 75% against 20% with 8 replicas on a workload of long shared-prefix groups (LMSYS, 2024-12-04) vendor, one workload.
cache_aware.rs, select_worker L387, thresholds at the command-line defaults of v0.5.21 (main.rs L150-170).
The other policies are round_robin, random, power_of_two (pick the less loaded of two random workers), prefix_hash, consistent_hashing and bucket (policies/). The gateway also does prefill/decode routing, retries, circuit breakers, rate limits and tokenization in Rust (README). A router in front of real replicas, measured against round robin and least-loaded, is on LLM serving in production; its section 2 steps eight requests through three real replicas under each routing rule.
SGLang's large-scale recipes target mixture-of-experts models such as DeepSeek-V3/R1 (671 billion parameters, 37 billion active per token, 256 routed experts per layer, multi-head latent attention with one compressed KV vector per token). Five pieces, each explained as a mechanism on Distributed and disaggregated serving, with SGLang's switch for each:
--enable-dp-attention), each GPU holding different requests' KV, and gathers only around the expert layers; v0.4 reported 1.9 times decode throughput from it vendor.--moe-a2a-backend deepep, EP docs).mooncake (the default), nixl, mooncake_tcp, mori, ascend, and fake for tests (choices.py L120-127, PD docs); v0.5.21 lets an instance switch role without a restart (#28403). Run v0.5.22 or later, or backport #36988 and #38935, so a refused request is retired before its KV handoff, with deferred KV release on both roles (the default from v0.5.21) so an aborted transfer cannot write into reused slots; why: Distributed and disaggregated serving, section 6.The headline numbers are the team's own and each measured one thing vendor: 22,282 decode tokens/s per node of 8 H100 for DeepSeek-V3 with prefill and decode measured separately (May 2025); 3.8 and 4.8 times that per GPU on GB200 NVL72, up to 1.8 and 1.9 times of it from lower precision (September 2025); and "up to 25x" for GB300 NVL72 against H200 (February 2026), measured at 50 tokens/s per user, where the older GPU is weakest; the same post says that without the latency constraint H200 reaches similar throughput to its earlier figures. None of this was run here: it needs dozens of datacenter GPUs.
| Post | Set-up | Result | Read it as |
|---|---|---|---|
| 2025-05-05 | DeepSeek-V3, 12 nodes of 8 H100 (96 GPUs): prefill measured on 4 nodes (EP32) and decode on 9 (EP72), each phase separately with the other assumed unlimited, 2,000-token inputs | 52.3k input and 22.3k output tokens/s per node; decode 22,282 tokens/s per node with a batch of 256 sequences; up to 5 times vanilla TP; "$0.20 per 1M output tokens" | Prefill and decode measured separately, each assuming the other phase unlimited; the dollar figure is a derived local cost, not a price |
| 2025-09-25 | DeepSeek-V3/R1 on GB200 NVL72, FP8 attention and NVFP4 experts, 2,000-token inputs | 26,156 input and 13,386 output tokens/s per GPU, 3.8 and 4.8 times the H100 setting; 18,471 and 9,087 at BF16 attention and FP8 GEMMs | Lower precision accounts for up to 1.8 and 1.9 times of it |
| 2026-02-20 | DeepSeek-R1 on GB300 NVL72 against H200, in SemiAnalysis InferenceX | "Up to 25x" | Measured at 50 tokens/s per user; a ratio at one interactivity point |
Matching DeepSeek's own published serving profile was the stated goal of the first post: with simulated perfect expert balance SGLang's prefill came within 6% of DeepSeek's profile, and decode with simulated multi-token prediction within 6.6% vendor. The arithmetic of expert and tensor parallelism (bytes per token over each link, why EP crosses nodes) is computed on Distributed and disaggregated serving with the root's Capacity planner.
What independent data says. Which engine is faster depends on the model, the GPU, the precision, the prompt length, the per-user speed you promise and the date of the build. The one place both engines are run by a third party on the same model and GPUs is SemiAnalysis InferenceX, a continuously running benchmark (repository, dashboard) independent. Of the models it lists, only DeepSeek-V4-Pro has single-node runs of both (no speculative decoding, builds from June to September 2026, read from its public API on 2026-10-08). Neither engine dominates: at matched concurrency with 1,024-token prompts, SGLang's throughput per GPU ran from 0.83 to 1.37 times vLLM's on B200 FP4, 0.50 to 1.01 times on B300 FP4 and 0.83 to 1.04 times on H200 FP8; only on MI355X did one engine lead at every matched concurrency (SGLang, 1.85 to 3.32 times, against a vLLM ROCm nightly build).
Each point is one run at one concurrency; to the right each user gets more tokens per second, up each GPU produces more in total. An engine is better where its upper-right envelope (the line) is higher at the per-user speed you need.
The old version of this page said SGLang "leads by about 20 to 30% on prefix-heavy small and mid-size models" and that "at 70B+ dense scale differences shrink to a few percent" (2026 folklore, no source given): no measurement found supports either figure, so they are dropped.
| Claim | Baseline and conditions | Source |
|---|---|---|
| Up to 5 times higher throughput | Against Guidance and vLLM v0.2.5 (no cross-request prefix cache), Llama-7B on A10G, program workloads | LMSYS 2024-01-17 vendor |
| Up to 6.4 times higher throughput | The paper's baselines on agent, reasoning, few-shot, JSON, RAG and chat tasks | arXiv 2312.07104 authors |
| 3 times faster JSON decoding | Jump-forward with a compressed FSM against Outlines with vLLM; feature removed in v0.4.4 | LMSYS 2024-02-05 vendor |
| 1.1 times from the overlap scheduler | Against SGLang v0.3, Llama-3.2-3B, 4,096 in / 2,048 out | LMSYS 2024-12-04 vendor |
| 1.9 times throughput, 75% against 20% hit rate | Cache-aware router against round robin, 8 replicas, a shared-prefix workload "perfectly balanced" across groups | same vendor |
| 52.3k input and 22.3k output tokens/s per node | DeepSeek-V3 on 96 H100 with PD disaggregation and EP; phases measured separately | LMSYS 2025-05-05 vendor |
| Up to 25 times on GB300 NVL72 against H200 | DeepSeek-R1 at 50 tokens/s per user in InferenceX; much smaller without the latency constraint | LMSYS 2026-02-20 vendor, on independent runs |
Choosing. The prefix caches reuse the same tokens (section 3); the differences lie in queue policies (section 4; both default to FCFS), the router (section 8) and the large-scale MoE recipes (section 9):
| If your situation is | Lean towards | Why, and how to check |
|---|---|---|
| Deep bursts of requests sharing long prefixes (evaluations, synthetic data, RL rollouts, retrieval over a corpus) | SGLang with --schedule-policy lpm or dfs-weight | Cache-aware ordering, absent from vLLM's policies; check #cached-token and batch time, and keep the waiting queue under 128 for lpm. |
| Many replicas, multi-turn chat or agents | Either, with a prefix-aware router | SGLang's gateway or llm-d's scheduler for vLLM; the router matters more than the engine (section 8). |
| DeepSeek-class MoE on many GPUs, PD disaggregation | SGLang's published recipes, or vLLM's wide-EP and Dynamo | Both have recipes; reproduce on your hardware (Distributed and disaggregated serving). |
| A model, quantization or chip one engine supports and the other does not | That engine | Check each project's supported-model list for your exact checkpoint before benchmarking anything. |
| Anything else | Run both on your own traffic | Same model, precision, GPU, prompt and output lengths, concurrency sweep, TTFT and TPOT percentiles (LLM serving in production on honest load testing). |
With SGLANG_USE_MLX=1 the scheduler, radix cache and API are SGLang's own and the forward pass runs in Apple's MLX (Apple Metal docs); that is what made this page's real-engine measurements possible on a laptop (from v0.5.22 Apple silicon also runs on the standard PyTorch backend, without MLX). v0.5.21 on the M1 Pro, installed from source, broke in four ways:
AttributeError: 'MlxModelRunnerStub' object has no attribute 'kv_cache_configurator'); fixed upstream one day after the tag (PR #41314).[METAL] Command buffer execution failed: Insufficient Memory, with gigabytes free) whenever the cache had to evict, a prefill batch mixed a chunked prompt with other requests, or a burst followed /flush_cache.1. It did not start. A refactor of the token-capacity code had not been carried to the Apple path; the fix (PR #41314, merged 2026-09-30) landed one day after the release's tag commit. Applying its seven-line property let the server start.
2. It answered the wrong question. The second A came back as "a) the number of employees in the company...". Disabling the radix cache made it go away, which pointed at the cache. Issue #42415 was reported on v0.5.20; PR #42542 traces it to chained decode steps writing a finished request's KV into slots the tree still points at. With that patch the repeat answered A again, every time. Fresh server, cache on, greedy: A, B, A, B, A:
3. Cached and uncached answers differ. The cached A diverged after eight tokens ("is used to store" against "represents the hierarchical"). MLX-LM alone, with no SGLang, does the same when the prompt is computed in two pieces instead of one: at the ninth generated token, where the texts part, the gap between the two best candidates was 0.000, 0.125 and 0.125 in logit in the three runs. Computing in a different order rounds differently, and a near-tie flips.
4. Crashes. Every time the radix cache had to evict (a 3,000-token pool and 840-token prompts one at a time, with and without the patch of item 2); every time a prefill batch mixed a chunked prompt (512-token chunks) with other requests, inside _async_extend_batch, with 6 GB free, while the same bursts of 8 to 32 requests ran cleanly with chunks of 4,096 (not reported upstream as of this writing); on a burst of requests sent after /flush_cache (seen in two runs, not isolated further); in every run of the overlap experiment (section 5); and in every dfs-weight run. Open pull requests on the Apple backend touch neighbouring code (per-request buffers released late, #39251; retracted requests' state, #38179; no device-memory figure on Apple, #39675); none was confirmed as the cause here. The runs avoid all of them: a pool large enough never to evict, chunks of 4,096 and no flushes.
e00930c5, 2026-09-29), installed from source (no macOS wheel on PyPI: the v0.5.21 wheels are Linux only) with the srt_mps extra and Rust extensions off (SGLANG_BUILD_RUST_EXTS=none): PyTorch 2.13.0, MLX 0.32.3, MLX-LM 0.32.0, XGrammar 0.2.7, Transformers 5.12.1.SGLANG_USE_MLX=1 python -m sglang.launch_server --model-path <model> --disable-cuda-graph --port 8120 --enable-metrics plus --chunked-prefill-size 4096 --max-running-requests 8 and the flags of each experiment; a fresh server per run. The backend gives each running request its own contiguous KV buffer of 4,096 tokens per layer (448 MiB for this model, model_runner.py L258), so at most 8 ran at once. Client: src/m1/exp.py over the native /generate endpoint with token ids cut from WikiText-2, greedy, streaming; time to first token (TTFT) is the arrival of the first streamed chunk. Scripts: src/m1/run_m1.sh (one server per configuration), exp.py, sgclient.py, summarise.py; raw results in src/m1/results/.Design a router for 8 replicas of a chat model with long system prompts. Route by prefix affinity (approximate per-replica trees or consistent hashing of the prefix) but fall back to least-loaded when the load is imbalanced beyond a threshold; measure hit rate, TTFT percentiles and per-replica load. SGLang's gateway does exactly this with a 0.3 match threshold and 64/1.5 imbalance thresholds by default; check that the imbalance thresholds can fire at your real concurrency.
Why does DeepSeek serving use data-parallel attention with expert parallelism? MLA has one compressed KV per token, so tensor-parallel attention would replicate the cache on every GPU; data-parallel attention keeps each request's cache on one GPU, and expert parallelism spreads the experts, with all-to-all exchanges around each MoE layer.
How would you check that prefix caching is working on a production server? Per-request cached-token counts or the hit-rate metric, TTFT split by hit and miss, and a greedy A/B/A correctness test with the cache on and off.
The parent topic and its siblings, the papers and posts behind each mechanism, and SGLang's own documentation and source, each with an approximate time. Links checked on 2026-10-08.
The parent: prefill and decode, the KV cache, batching, engines; its Serving simulator, Engine bench and Capacity planner tabs. Reading: 34 min, plus 3 in closed details
The other engine's scheduler, block pool and prefix hashing read in source. Reading: 41 min, plus 15 in closed details
Continuous batching, paging, eviction policies, offload tiers, chunked prefill, fairness. Reading: 37 min, plus 21 in closed details
EAGLE, MTP (SGLang's NEXTN), n-gram and DFlash, all of which SGLang ships. Reading: 36 min, plus 8 in closed details
Tensor, pipeline and expert parallelism, PD disaggregation, Dynamo and llm-d. Reading: 41 min, plus 21 in closed details
Routers measured on real replicas, autoscaling, structured output overhead, load testing. Reading: 34 min, plus 13 in closed details
llama.cpp, Ollama and MLX on Apple silicon, the backend SGLang's Mac path runs on. Reading: 41 min, plus 49 in closed details
The paging the block cache is built on. 27 min
Logits, masks and greedy decoding, the ground under constrained output. Reading: 22 min, plus 4 in closed details
Zheng et al., NeurIPS 2024: RadixAttention, cache-aware scheduling and Theorem 3.1, the compressed FSM. 45 min
The nine-step tree figure that this page's animation follows. 15 min
Overlap scheduler, cache-aware router, DP attention, XGrammar. 15 min
PD disaggregation, DeepEP, EPLB, two-batch overlap, profiles against DeepSeek's. 45 min
FP8 attention and NVFP4 experts on a rack. 20 min
The default grammar engine: context-independent tokens, structural tags, up to 80 times faster compilation (authors). 30 min
Evicting only what a conversation's next turn does not need for its TTFT target. 30 min
Continuous independent benchmarks of SGLang, vLLM and TensorRT-LLM. browse
Start with hyperparameter tuning, server arguments, structured outputs, HiCache, model gateway. 40 min for the core pages
radix_cache.py (800 lines, the clearest), schedule_policy.py, scheduler.py event loops, cache_aware.rs, then mem_cache/README.md for the unified cache. 2 h
The team's talks and slides. 1 h 30 min
v0.5.21 (2026-10-02) and the releases since. 10 min each