SGLang: radix cache, cache-aware scheduling, large-scale serving

Reading: 34 min, plus 16 in closed details. SGLang read from source at v0.5.21, its prefix cache and scheduler replayed against vLLM's, and the real engine run on an Apple M1 Pro. Data as of October 2026.

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)

  1. Router (section 8). The SGLang Model Gateway, written in Rust, keeps an approximate tree of the text it has sent to each replica; its default policy, cache_aware, sends the request to the replica likely to hold its prefix unless the load is imbalanced.
  2. TokenizerManager. The HTTP server (OpenAI-compatible or native /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.
  3. Scheduler: the queue and the tree (sections 2 and 4). One Scheduler per GPU rank owns the waiting queue, the radix tree and the KV pool, and runs the model (scheduler.py). The queue is ordered by the schedule policy; the request's tokens are matched against the tree: 9 of its 15 are cached (the system prompt). Everything this page says about caching and ordering happens here.
  4. The KV pool on the GPU (section 5). The tree lives on the CPU and maps runs of token ids to slot numbers in the GPU's KV pool; the KV itself never moves. Prefill reads the 9 cached tokens' KV in place and computes only the 6 new ones into free slots, while the overlap loop prepares the next batch on the CPU.
  5. Decode, the grammar mask, the stream (section 6). Each step samples one token per request, after masking the vocabulary if the request asked for a schema. The DetokenizerManager turns new ids into text and streams it back (detokenizer_manager.py).
  6. Finish: insert, and evict when full (section 2). The prompt and the answer, minus its last token, go into the tree as a new branch. When the pool fills, the least recently used leaves that no running request holds are evicted.

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.

Radix tree
a prefix tree whose edges carry whole runs of tokens; a node exists only where two cached sequences part (section 2).
Lock reference
a count of running requests using a node; a locked node cannot be evicted.
Schedule policy
the order of the waiting queue: fcfs (default), or cache-aware lpm (longest prefix match) and dfs-weight (section 4).
Overlap scheduler
the loop that prepares step k plus 1 on the CPU while the GPU runs step k (section 5).
Retraction
SGLang's word for preemption: a running request is pushed back to the queue and recomputed later (section 7).
HiCache
the radix tree extended over host memory and storage (section 7).
The short answer
On the same requests the radix tree and vLLM's hash blocks reuse almost exactly the same tokens (within 0.8 points, section 3). SGLang's edge, where it has one, comes from what sits around the cache: queue ordering when the cache is scarce, the router, structured-output plumbing and the large-scale MoE recipes; and both engines move fast enough that any benchmark older than a few months says little about today.
SGLang v0.5.21 and vLLM v0.31.0 side by side, with the source line for each default (reference)
SGLang v0.5.21vLLM v0.31.0
Prefix cacheA 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 defaultYes; --disable-radix-cache turns it off (memory.py L64)Yes (enable_prefix_caching, cache.py L142)
EvictionLeast 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 orderfcfs 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 GPUOverlap 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 outputXGrammar by default; llguidance and Outlines selectable (serving_hook.py L219)XGrammar or guidance (README)
RouterSGLang 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)
How this page knows: the evidence behind it (provenance)

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.

1. Where it came from, and the frontend language

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.

Read the early speedups with their baseline
The launch blog's "up to 5x faster" (LMSYS, 2024-01-17) compared against Guidance and vLLM v0.2.5, which kept no KV cache across requests at all. vLLM added automatic prefix caching in v0.4.0 on 2024-03-30, off by default at first (release notes), and its V1 engine turns it on by default. So the 2024 gap was mostly "cache across requests or not", which no longer separates the two engines (section 3 measures what is left).
Releases since the paper (history)

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.

2. The radix tree, from zero

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.

  1. Request 1: an empty tree. Customer A's 14-token prompt matches nothing, so all 14 tokens are computed. Prompt and answer, minus the answer's last token (whose KV was never computed), are inserted: 17 of 40 slots. The leaf is split at the prompt boundary so the answer can be evicted before the question.
  2. Request 2: match, then split. Customer B shares the 9-token system prompt. The walk stops inside A's node, which is cut in two so the shared part becomes its own node; only the slot list is sliced, nothing moves on the GPU. B's 6 new tokens and its answer hang off the shared node: 26 of 40.
  3. Request 3: a second turn. A resends its whole first turn: 17 of 21 prompt tokens match, all the way down A's answer, and only ". And savings ?" is new. The matched path is locked while the request runs, so nothing on it can be evicted under it: 31 of 40.
  4. Request 4: the first eviction. A travel assistant shares only "You are a" (3 tokens), so the trunk splits again near the root. It needs 12 slots and 9 are free: the least recently used unlocked leaf, B's answer "Yes , online" (3 tokens), is evicted. The pool is full, 40 of 40.
  5. Requests 5 and 6: hits to the token. C matches 10 tokens, the system prompt plus "What", splitting A's question there; B's question (6 tokens) and A's "$9" (1) are evicted. D repeats A word for word and reuses 13 of 14 tokens: the last prompt token is always recomputed to produce the first output. D reserved 4 slots by evicting ". And savings ?", then gave them back when its KV turned out to be in the tree already: 36 of 40.
  6. Requests 7 and 8: tips first. The travel customer's second turn reuses 15 of 18 tokens; E reuses 12 ("... What is my"), and C's answer "Nine to five" is evicted. Branches are eaten from the tips inward, so the shared trunk survives longest.
  7. The tree at the end. 14 nodes describe everything cached; the eight requests reused 79 of 123 prompt tokens (64%). The same requests through hash blocks are compared below.

The five operations of Fig. 2, each with its line in v0.5.21's radix_cache.py:

match

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).

split

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.

insert

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.

lock

A running request increments the lock count of every node on its path (L583); a prefix in use never disappears under it.

evict

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.

Tree against hash blocks, on the same requests

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.

Predict: request 6 repeats request 1 word for word ("You are a bank assistant . Be brief . What is my balance ?", 14 tokens) after other requests have filled the pool. At most how many of its tokens can the radix tree reuse?
Cost, when it matters, how to check
  • Cost: CPU work proportional to the matched length, one node per branch point, and no GPU memory beyond KV that would otherwise sit in free slots (eviction gives them back on demand).
  • When: any traffic with repeated beginnings (chat history, shared system prompts, few-shot examples, retrieval over the same documents, agents). On unrelated one-shot prompts it does nothing and costs little (no measurable overhead without hits, launch blog).
  • Check: 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.

The same eight requests, tree against hash blocks of 4: the tree shares partial blocks and evicts whole leaves

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).

3. Radix tree or hash blocks: does the data structure matter?

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.

Predict, then drag: in the coding-agent trace each turn resends the whole conversation (2,000-token system prompt plus every earlier turn). The pool grows from 24,000 to 48,000 token slots. What happens to the share of prompt tokens reused?

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.

So what does differ between the engines?
Not how many tokens the cache can reuse, but what the engine does with it: whether the scheduler orders the queue to reuse it before it is evicted (section 4), whether the router keeps a conversation on the replica that holds it (section 8), how big the pages are (SGLang's page size 1 matches to the token; most fast attention kernels want 16 or more, and SGLang uses 64 or 128 with some of them, overrides.py L1068), and how the cache spills to host memory and disk (HiCache, section 7; vLLM's offload connectors, Batching, KV cache and scheduling in depth).

Same requests, two caches: hit rate is a cliff in the pool size, and the two curves almost coincide

radix tree (SGLang, page size 1)hash blocks of 16 (vLLM)your pool size

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.

Request by request: where the tree or the blocks reused more (the lab beside the text, one bar per request)

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.

How the replays were run, and what the port leaves out (method)
  • SGLang: its default 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).
  • vLLM: its own v1 Scheduler and KVCacheManager from v0.31.0, with a fake model runner, exactly as the root's Serving simulator tab checked its own engine.
  • Traces: chat (seed 7; 90% of conversations under one of 3 system prompts of 600 tokens), agent (seed 11; turns 15 s apart, up to about 4,800 tokens of history per request), documents (seed 5; questions and answers of 20 to 80 tokens), unrelated (seed 3; 100 to 800 tokens).
  • The port: match the prompt (capped at its length minus one), lock the matched path, evict least recently used leaves or blocks until the request's new KV fits, insert prompt and output (minus the last token), unlock. Not modelled: concurrency (several running requests locking more of the tree), HiCache or vLLM's offload tiers, page sizes other than 1 and 16, sliding-window or hybrid models.
On the real engine: a four-turn chat with the radix cache on and off (measured on the M1)

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

radix cache on (default)--disable-radix-cache

4. Cache-aware scheduling: the order of the queue

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).

  1. The queue as it arrived. Both lanes hold the same 16 questions in arrival order, coloured by document, and nothing is cached. Each round, the policy sorts the queue, the scheduler admits from the front while the new tokens fit, runs them, and keeps their KV in the tree.
  2. Round 1: in-batch prefix caching. fcfs admits the first three arrivals: one question on document 3 and two on document 5, so document 5 is computed twice in one batch, since neither copy is cached yet. lpm finds nothing cached either, but admits only the first question of each uncached document (documents 3, 5 and 1) and moves their siblings back.
  3. Round 2: what is cached goes first. lpm sorts the three waiting questions on document 5 to the front: 2,400 tokens reused. fcfs takes the next arrivals instead (documents 1 and 2, document 2 twice), reuses nothing, and evicts documents 3 and 5 to make room while three questions on document 5 still wait. lpm also computes document 2 twice: the deferred sibling still fit in the round.
  4. Round 3: lpm empties the queue. All seven remaining lpm questions are about documents 2 and 4, both cached: 5,600 tokens reused, 345 computed. fcfs reuses document 2 twice (1,600 tokens) but computes document 4 three times and evicts document 1.
  5. Round 4: fcfs pays again. fcfs's last five questions reuse document 4 three times (2,400 tokens) and compute document 5 twice more, the document it computed in round 1 and evicted in round 2.
  6. The count. fcfs: 4 rounds, 4,000 of 13,559 prompt tokens reused (30%), 9,559 computed. lpm: 3 rounds, 8,000 reused (59%), 5,559 computed: 4,000 fewer, five documents' worth. The orders differ only in when each question was admitted.
fcfs (the default)

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.

lpm: longest prefix match

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).

in-batch prefix caching (inside lpm)

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.

dfs-weight

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).

the 128 cliff

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.

Every setting, four policies

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.

Predict: you enable --schedule-policy lpm on a busy server where 300 requests are usually waiting. How much does the queue order change?
Cost, when it matters, how to check
  • Cost: a prefix match per waiting request per pass, plus the sort; and fairness: a request whose prefix nobody shares can wait behind a stream of hits. The paper names this starvation risk; SGLang now offers hrrn (highest response ratio next, aging by processed tokens, L496) and priority scheduling.
  • When: offline batch jobs and bursts (evaluations, synthetic data, RL rollouts with many samples per prompt, retrieval over a shared corpus) where the queue is deep and the cache smaller than the hot prefixes. At steady low load the queue is nearly empty and every policy is FCFS.
  • Check: #cached-token against #new-token in the prefill log, per-request cached_tokens, and the total time of a fixed batch under each policy.

Every setting, four orders: lpm and dfs-weight keep a document cached until its questions are served

More settings (documents, their length, the arrival order)

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%.

The scheduling model, and how it was checked against SGLang's own code (method)

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.

On the real engine: the policies on a burst of shared-document questions (measured on the M1)

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.

Five decode steps: the plain loop leaves the GPU idle during CPU work; the overlap loop fills those gaps

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.

5. The overlap scheduler: hiding the CPU behind the GPU

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

  1. Step 1. The CPU schedules batch 1 (0.75 ms), the GPU runs its forward pass (5 ms), then the CPU processes the results (0.75 ms). The GPU waits through both CPU parts.
  2. Step 2. Batch 2 cannot start until batch 1's results are processed and batch 2 is scheduled: another 1.5 ms of idle GPU between the two forward passes.
  3. Step 3. The same gap again: every step costs GPU time plus CPU time, 6.5 ms.
  4. Steps 4 and 5. Five steps take 32.5 ms, and the GPU is busy 77% of the time.
Cost, when it matters, how to check
  • Cost: complexity, a finished request noticed one step late (its slot frees one step later), and a sync wherever the CPU must see a token before building the next step: on the Apple backend a batch with a grammar or a custom logit processor cannot be chained (scheduler_mixin.py); on GPUs SGLang syncs for grammars only with some speculative-decoding algorithms (L2015).
  • When: small models, low batch sizes, many GPUs per model, fast GPUs: whenever a forward pass takes a few milliseconds. The v0.4 post measured 1.1 times its previous version and says the gain is largest "on small models and large tensor parallelism sizes" vendor.
  • Check: a profiler timeline (Nsight Systems on NVIDIA) shows gaps between kernels in the plain loop and none with overlap; or compare decode throughput at concurrency 1 with and without --disable-overlap-schedule.
Why there is no measurement from the M1 here (a failed experiment)

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.

6. Structured output: where the grammar sits, and the jump-forward that was removed

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.

Cost, when it matters, how to check
  • Cost: compiling the grammar (cached per schema), a vocabulary-sized mask per step, and on some paths the loss of CPU/GPU overlap. A constrained answer is also not the answer the model wanted: masking forces a different token where the model's choice was invalid, which can lower quality; reasoning models are usually left unconstrained while they think (structured outputs for reasoning models).
  • When: tool calling and any machine-read output. The serving-time trade-offs (overhead under load, measured with llama.cpp grammars) are on LLM serving in production.
  • Check: parse every response, and compare time per output token with and without the schema at the same output length.

A constrained request in SGLang: the grammar is compiled once per schema, then masks every step

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.

The JSON-schema run on the M1, with one answer each way (measured on the M1)

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.

7. Running and tuning a server

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:

FlagDefaultWhat it trades
--mem-fraction-staticchosen by a heuristicShare 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-tokensderived from the line aboveCaps 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-size2,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-tokens16,384 (schedule.py L67)Prefill tokens admitted per batch.
--max-running-requestsbounded by the poolConcurrency cap; lower it if decode runs out of memory.
--schedule-policyfcfsSection 4. lpm or dfs-weight for deep queues over shared prefixes.
--schedule-conservativeness1.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-size1 (64 or 128 with some attention backends)Granularity of the KV pool and the tree.
--radix-eviction-policylrulfu 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-cacheoff (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-metricsoverlap on, xgrammar, metrics offSections 5 and 6; Prometheus metrics at /metrics.
--tp, --dp, --ep, --enable-dp-attention1, 1, 1, offSection 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.

8. The router: keeping a conversation where its cache is

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.

How the cache-aware policy picks a worker: balance first, then the longest prefix, then the least loaded

cache_aware.rs, select_worker L387, thresholds at the command-line defaults of v0.5.21 (main.rs L150-170).

The gateway's other policies and features (reference)

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.

9. Large scale: DeepSeek on 96 GPUs and on a rack

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:

DP attentionWith MLA there is a single KV head, so splitting attention by heads would copy the whole KV cache to every GPU. SGLang runs attention data-parallel (--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.
Expert parallelism with DeepEPEach GPU holds a slice of the experts; tokens go to the GPUs holding their experts and back (all-to-all), with DeepEP's normal mode for prefill and low-latency mode for decode (--moe-a2a-backend deepep, EP docs).
EPLBDeepSeek's expert-parallel load balancer replicates hot experts into redundant slots (256 plus 32 = 288), which also allows 12 or 72 GPUs instead of powers of two.
Two-batch overlapSplit the batch in two so one half's all-to-all runs while the other half computes; on GB200 NVL72's faster links SGLang moved to finer single-batch overlap.
Prefill/decode disaggregationPrefill and decode on different GPU pools, the KV moving between them over a transfer backend: 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.

The three posts in detail: set-up, result and how to read each (vendor numbers)
PostSet-upResultRead it as
2025-05-05DeepSeek-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 inputs52.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-25DeepSeek-V3/R1 on GB200 NVL72, FP8 attention and NVFP4 experts, 2,000-token inputs26,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 GEMMsLower precision accounts for up to 1.8 and 1.9 times of it
2026-02-20DeepSeek-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.

10. SGLang or vLLM?

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).

Throughput per GPU against speed per user: each engine's envelope wins somewhere, and the lead changes with the GPU

vLLMSGLang

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.

Runs at the same concurrency, and what this comparison can and cannot say (table and caveats)
  • Different builds and dates. The vLLM runs used v0.25.0 to v0.25.1 or nightly images from July to September 2026; the SGLang runs used nightly images from late June and July 2026 (shown per row). Both engines have released several versions since (vLLM v0.31.0, SGLang v0.5.21).
  • Different recipes. Each engine ran with its own tensor, expert and data-parallel choices (TP and EP columns), so a row at the same concurrency can compare different numbers of GPUs per replica; the envelopes, which take each engine's best configuration, are the fairer reading.
  • One model. DeepSeek-V4-Pro is a 1.6-trillion-parameter mixture of experts with a long-context attention design; results on a dense 8B or 70B model can differ completely.
  • No prefix reuse. These are single-turn random prompts, so nothing here exercises the radix cache or cache-aware scheduling, where section 3 found the two caches equal.

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.

What each project claims about itself, with the baseline (vendor claims)
ClaimBaseline and conditionsSource
Up to 5 times higher throughputAgainst Guidance and vLLM v0.2.5 (no cross-request prefix cache), Llama-7B on A10G, program workloadsLMSYS 2024-01-17 vendor
Up to 6.4 times higher throughputThe paper's baselines on agent, reasoning, few-shot, JSON, RAG and chat tasksarXiv 2312.07104 authors
3 times faster JSON decodingJump-forward with a compressed FSM against Outlines with vLLM; feature removed in v0.4.4LMSYS 2024-02-05 vendor
1.1 times from the overlap schedulerAgainst SGLang v0.3, Llama-3.2-3B, 4,096 in / 2,048 outLMSYS 2024-12-04 vendor
1.9 times throughput, 75% against 20% hit rateCache-aware router against round robin, 8 replicas, a shared-prefix workload "perfectly balanced" across groupssame vendor
52.3k input and 22.3k output tokens/s per nodeDeepSeek-V3 on 96 H100 with PD disaggregation and EP; phases measured separatelyLMSYS 2025-05-05 vendor
Up to 25 times on GB300 NVL72 against H200DeepSeek-R1 at 50 tokens/s per user in InferenceX; much smaller without the latency constraintLMSYS 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 isLean towardsWhy, 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-weightCache-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 agentsEither, with a prefix-aware routerSGLang'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 disaggregationSGLang's published recipes, or vLLM's wide-EP and DynamoBoth have recipes; reproduce on your hardware (Distributed and disaggregated serving).
A model, quantization or chip one engine supports and the other does notThat engineCheck each project's supported-model list for your exact checkpoint before benchmarking anything.
Anything elseRun both on your own trafficSame model, precision, GPU, prompt and output lengths, concurrency sweep, TTFT and TPOT percentiles (LLM serving in production on honest load testing).

11. Running SGLang on a Mac, and the test that caught a wrong-answer bug

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:

  1. It did not start (AttributeError: 'MlxModelRunnerStub' object has no attribute 'kv_cache_configurator'); fixed upstream one day after the tag (PR #41314).
  2. It answered the wrong question: send A, an unrelated B, then A again, all greedy, and the second A came back as unrelated text with 25 of its 26 prompt tokens reported cached. Open issue #42415; the open pull request #42542 fixes it.
  3. Not a bug: even patched, the cached A diverged from the uncached A after eight tokens, at a near-tie of two candidates. Prefix caching is exact in arithmetic, not in floating point.
  4. Crashes ([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.
The habit this teaches
Before trusting a cache, run the same greedy request with it on and off, and an unrelated request in between. Identical text is not guaranteed (item 3), but a different topic is a bug (item 2). All measurements on this page were taken with both fixes applied and the crashes avoided.
The four problems in detail, with the reproduction (evidence)

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.

The set-up on the M1, and what transfers to a datacenter GPU (provenance)
  • Machine: Apple M1 Pro, 16 GB unified memory, shared with other jobs (load average 3.9 to 27.2 at the start of the runs; every configuration repeated, spread shown). Measured on 2026-10-08 and 2026-10-09.
  • SGLang v0.5.21 (tag commit 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.
  • Two patches from upstream, both in src/m1/: the start-up fix of PR #41314 (merged after the tag) and the cache fix of PR #42542 (open).
  • Model: Qwen3-0.6B (Qwen/Qwen3-0.6B at commit c1899de2) quantized here to 4 bits, group size 64, with MLX-LM 0.32.0, from the root's model store.
  • Server: 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/.
  • Transfers: which tokens are cached and reused (the scheduler and tree are the same code), the ordering effects of the queue policies, the correctness test, the fact that a grammar adds per-step CPU work.
  • Does not transfer: the absolute times. A 0.6B model on a laptop GPU makes the forward pass short and the Python scheduler's share large, so CPU-side effects (overlap, grammar masks) look bigger here than on an H100 serving a 70B model; prefill costs far more per token here than on a GPU, so cache hits save more seconds here. The MLX backend also lacks paged attention: it copies a cached prefix out of the pool into a per-request cache (model_runner.py).
Interview rehearsal: three design questions (optional)

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.