Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Prefix | The start of a prompt. Two requests “share a prefix” when their first N tokens are identical, for example the same system prompt. |
| Prefix cache | Keeping the KV cache of a prefix after a request finishes, so the next request with that prefix skips recomputing it (12.m). |
| Radix tree | A tree in which each edge is labelled with a run of tokens. Walking down from the root spells out a token sequence; requests that share a start share the path. |
| LRU eviction | When memory is full, throw away what was “least recently used” first. |
| Constrained decoding | Forcing the output to follow a grammar or JSON schema by forbidding, at each step, the tokens that would break it (12.o, 18.e). |
| Finite-state machine (FSM) | A small graph of states and allowed moves. A JSON schema or regular expression can be turned into one; the current state says which characters may come next. |
| Router | A process in front of several engine copies (replicas) that decides which replica gets each request. |
| DSL | Domain-specific language: a small programming language, here embedded in Python, for one job. |
1. What is it?#
SGLang is an open-source LLM serving engine from the LMSYS group (the paper appeared in
December 2023; the project is now run by the sgl-project organisation). Its distinguishing
ideas are RadixAttention, a prefix cache organised as a radix tree, and a frontend
language for writing LLM programs that branch and share context.
vLLM's thesis: memory management is the bottleneck → PagedAttention
SGLang's thesis: LLM programs have structure (shared prefixes, branching,
constrained output) → exploit itBoth are right, and the two engines have converged: vLLM has automatic prefix caching (17.f), SGLang has paged memory. Their origins still explain their strengths.
The latest release is v0.5.23 (2 November 2026). Facts checked on 12 November 2026.
2. Why does it exist?#
Real LLM traffic repeats itself. An agent sends the same 5,000-token tool list on every turn. A chat session resends the whole conversation each time. A classifier sends the same 30 few-shot examples before every input. Without a prefix cache, every one of those requests recomputes the same KV cache from scratch: the GPU spends most of its prefill time redoing old work.
SGLang was built on the observation that this sharing is the normal case, not an edge case, and that the serving system should see and plan around it: store shared prefixes once, schedule requests that share them together, and route requests to the replica that already holds them.
3. Simple analogy#
A filing system organised by folders, against one organised by document number.
Document numbers (a flat hash table): every document has an ID and you look it up by ID. Exact retrieval is easy, but you cannot see that documents A and B are both in the “Q3 Reports” folder, and deleting a folder that other documents still point at is a hazard you must guard against separately.
Folders (a radix tree): the hierarchy is the structure. Shared context is a shared parent folder. Clearing out old material leaf-first is safe by construction. And you can see at a glance which documents share context, so you can work on them together.
4. Tiny example: the tree after four requests#
Four requests arrive:
R1: [SYS] [JSON] What is X?
R2: [SYS] [JSON] What is Y?
R3: [SYS] [BRIEF] Summarize:
R4: [SYS] [JSON] What is X? (again)
[SYS] = "You are a helpful assistant." 2,000 tokens
[JSON] = "Answer in JSON." 10 tokens
[BRIEF] = "Be concise." 5 tokensThe radix tree after them:
root
│
[SYS] 2,000 tokens
╱ ╲
[JSON] 10 [BRIEF] 5
╱ ╲ │
"What is X?" "What is Y?" "Summarize:"Prefill work with and without the tree:
tokens to prefill without cache with RadixAttention
R1 2,015 2,015 2,015 (nothing cached yet)
R2 2,015 2,015 5 (reuses [SYS][JSON])
R3 2,010 2,010 5 (reuses [SYS])
R4 2,015 2,015 0* (whole prompt cached)
total 8,055 2,025 → 75% less prefill
* the engine still recomputes the last token to get logits for sampling5. Technical explanation#
RadixAttention#
Instead of a flat table mapping block hash to block (vLLM’s approach, 17.f), SGLang keeps a radix tree of token sequences. Each node holds the KV cache for its run of tokens. A new request walks the tree from the root, matching as far as it can, and reuses everything along the path. After the request finishes, its new tokens stay in the tree as a new branch until memory pressure evicts them.
Why a tree helps:
- Branching is explicit. Agent workflows, tree search and multi-sample generation produce branches from a common prefix. The tree represents them directly.
- Eviction respects the hierarchy. The cache evicts leaves first, by LRU, and never a node that a running request or a child still uses (each node keeps a reference count). A flat cache has to enforce the same rule separately, by hashing each block together with its parent’s hash.
- Longest-prefix match is the natural operation. Walking down the tree is the lookup.
- The scheduler can see sharing. It can order the waiting queue so that requests sharing a node run close together, while that node is still in memory.
Cache-aware scheduling#
Point 4 is SGLang’s scheduling contribution. With --schedule-policy lpm (longest prefix
match), the scheduler sorts the waiting queue by how many tokens of each request are already
cached, so batches form around shared prefixes. In v0.5.23 the default policy is fcfs (first
come, first served), and even lpm falls back to fcfs when more than 128 requests are waiting,
because matching every waiting request against the tree costs CPU time. Other policies include
dfs-weight, lof (longest output first) and priority.
The frontend language#
SGLang’s second contribution is a Python DSL for LLM programs:
import sglang as sgl
@sgl.function
def multi_question(s, document, questions):
s += sgl.system("You are a document analyst.")
s += sgl.user(f"Document:\n{document}") # long, shared prefix
s += sgl.assistant("I have read the document.")
forks = s.fork(len(questions)) # one branch per question
for f, q in zip(forks, questions):
f += sgl.user(q)
f += sgl.assistant(sgl.gen("answer", max_tokens=200))
forks.join()
@sgl.function
def extract(s, text):
s += sgl.user(f"Extract the person from: {text}")
s += sgl.assistant(
'{"name": "' + sgl.gen("name", stop='"') + '", '
'"role": "' + sgl.gen("role", stop='"') + '"}'
)
sgl.set_default_backend(sgl.RuntimeEndpoint("http://localhost:30000"))
state = extract.run(text="Ada Lovelace, the first programmer.")
print(state["name"], state["role"])What the runtime does with this:
- The document prefix is prefilled once and every question branch reuses it through the radix tree.
forkcreates branches that share the parent’s KV cache.- The literal text in
extract({"name": "and so on) is not generated. It is appended to the prompt directly, so the model only generates the variable parts. That is faster, and the structure cannot come out wrong.
The DSL is optional. Most production traffic uses SGLang’s OpenAI-compatible HTTP API on port
30000 (sglang serve --model-path <model> or python -m sglang.launch_server).
Constrained decoding#
For JSON schemas and regular expressions sent through the API, SGLang compiles the grammar into
an automaton and masks forbidden tokens at each step. The default grammar backend is
xgrammar; outlines and llguidance are alternatives (--grammar-backend). The fast path
has two parts:
MASK CACHING precompute, per automaton state, the bitmask of allowed tokens.
At generation time the mask is mostly a lookup, not a scan of the
whole vocabulary.
JUMP-FORWARD when the automaton has exactly one valid continuation for several
characters (for example `{"name": "`), append them all at once
instead of generating them one token per step.The grammar backends in v0.5.23 implement jump-forward (try_jump_forward); check the docs for
your version before relying on it, because the interaction with tokenisation is subtle.
6. Under the hood#
flowchart TB
C(("clients")) --> GW["SGLang Model Gateway<br/><small>Rust router: cache-aware, PD-aware</small>"]
GW --> TM
subgraph R1["One SGLang server (per replica)"]
TM["TokenizerManager<br/><small>HTTP, chat template, tokenize</small>"]
SCH["Scheduler<br/><small>batching, policy, overlap</small>"]
TREE["Radix cache<br/><small>tree nodes → KV pages</small>"]
MR["Model runner<br/><small>FlashInfer / FA kernels, CUDA graphs</small>"]
DT["DetokenizerManager<br/><small>token IDs → text</small>"]
end
TM -->|"ZeroMQ"| SCH
SCH <--> TREE
SCH --> MR --> SCH
SCH -->|"ZeroMQ"| DT --> TM
class GW,TM,DT io
class SCH queue
class TREE memory
class MR compute- Three kinds of process. The
TokenizerManager(with the HTTP server), oneSchedulerprocess per GPU rank, and aDetokenizerManager, joined by ZeroMQ sockets. It is the same separation vLLM uses (16.d), for the same reason: keep CPU text work from blocking the GPU loop. - The overlap scheduler. By default the scheduler prepares the next batch on the CPU while
the GPU runs the current one (
--disable-overlap-scheduleturns it off). vLLM’s async scheduling does the same job (16.g, 17.d). - The radix cache lives in
python/sglang/srt/mem_cache/radix_cache.py. Tree nodes point at pages of a paged KV pool. HiCache extends it with host-memory and storage tiers, so evicted prefixes can come back from CPU RAM or files instead of being recomputed (14.k). - The SGLang Model Gateway (
sgl-model-gateway) is a Rust router and control plane for many replicas; the repository also carriessgl-router, a slimmer KV-aware router for one model. The gateway’scache_awarepolicy keeps an approximate radix tree per replica and sends a request to the replica most likely to hold its prefix, balanced against load. It also handles prefill/decode disaggregation, retries and circuit breakers. Prefix-aware routing in general is 21.h.
7. Performance implications#
| Workload | Why SGLang tends to do well |
|---|---|
| Agent loops | Long shared prefix (tools plus scratchpad), many short generations |
Multi-sample generation (n > 1) | All samples share the prompt |
| Tree search, self-consistency | Branching is native |
| Few-shot classification | Huge shared prefix, tiny output |
| Document QA with many questions | One document, many branches |
| Multi-turn chat at volume | Deep reuse across turns |
| Large MoE models with expert parallelism | Heavy investment in DeepSeek-style serving at rack scale |
The original paper reported up to 6.4x throughput over the systems of its day on these workloads, almost entirely from cache reuse, not from faster kernels. Today vLLM also caches prefixes, so the gap on the same workload is much smaller and changes with each release.
Where SGLang wins least: single-turn traffic with unique prompts and no sharing. There it performs about like vLLM, because both run similar kernels.
Two costs to remember:
- Cached prefixes occupy KV memory. A large cache leaves less room for running requests. The cache only pays when hits are common.
- Cache-aware ordering is unfair by design. A request with no cached prefix can wait behind
a stream of requests that hit the cache. That is one reason
fcfsis the default.
8. Production implications#
- Evaluate SGLang when your workload has heavy prefix sharing: agents, few-shot, multi-sample and document QA are its home ground.
- Run the gateway in front of several replicas. Without prefix-aware routing, round-robin scatters each prefix across replicas and every replica’s hit rate drops.
- Measure your hit rate. Both SGLang and vLLM expose cached-token counts in their usage output and metrics. If the hit rate is low, the radix tree is not what you are paying for.
- Pin the version and check your model. SGLang releases about every two weeks, and model support tracks vLLM closely but not identically.
- The frontend DSL is optional. It is useful for complex programs; most teams use the OpenAI-compatible API and get the cache benefits anyway.
9. Common mistakes#
- Expecting a win on unique-prompt workloads. The gains come from sharing.
- Not using the gateway, then getting poor cache hit rates across replicas.
- Treating prefix caching as free capacity. Cached blocks come from the same pool as active requests.
- Breaking the prefix. Putting a timestamp or a request ID at the start of the system prompt makes every prompt unique. Put variable content at the end.
- Assuming
lpmis always on. Check--schedule-policy; the default isfcfs.
10. Hands-on exercise#
- Measure the sharing win. Build a workload with a 2,000-token shared prefix and 100 different short questions. Run it on vLLM (prefix caching on) and on SGLang. Compare time to first token and throughput. Is there a difference, and where does it come from?
- Fork semantics. Use the frontend to generate 8 answers from one prompt with
fork. Compare time and peak KV usage against 8 independent requests. - Scheduling policy. Rerun exercise 1 with
--schedule-policy fcfsandlpm, with 50 and then 200 requests waiting. When doeslpmhelp, and why does it stop helping above 128? - Router evaluation. Run 4 replicas behind the gateway, once with
cache_awareand once withround_robin. Measure the overall prefix hit rate and p95 time to first token. - Read the radix tree. Read
radix_cache.py. Find insertion, longest-prefix match and the eviction that respects reference counts.
11. Interview questions#
- What is RadixAttention, and how does it differ from a flat prefix hash table?
- Give three advantages of a tree for prefix caching.
- What is cache-aware scheduling, and what does it cost in fairness and CPU time?
- What is jump-forward decoding, and why is it faster than masking alone?
- Which workloads favour SGLang, and why?
- What does SGLang’s gateway do that a plain round-robin load balancer does not?
- When would SGLang and vLLM perform about the same?
12. Further reading#
Checked on 12 November 2026.