The evolution of the SGLang runtime: an overview of its optimizations, from RadixAttention to agent workloads

Published

SGLang began in 2024 as a frontend language and a runtime for structured LLM programs. This article follows how the runtime has evolved since, based on Ying Sheng's MIT lecture, and what it can now infer without the application declaring it.

Adapted from Ying Sheng’s MIT 6.S979 lecture, SGLang: The Evolution of an LLM Runtime (November 18, 2026). The lecture traces the runtime through its cache system, because caching makes each design decision concrete.

Background

A coding task is a program, not a request. In the AgentX trace of 393 Claude Code sessions, the median session has 43 turns. The median turn sends 320 input tokens for every output token, and 44% of sessions fork subagents. One task is many model calls, and the calls are related. Each turn resends the history, and branches start from a shared context.

The application knows how its calls relate. The request stream does not say. This article uses one example throughout: an agent reads a repository, then forks into Fix bug (two turns) and Write tests. The server receives three requests, each with its full history.

Program and requestsBlock width = token count
What the application knowsShared contextFix bugTurn 2Write testsWhat the server receivesRequest 1Request 2Request 3
The application knows one program: a shared context, two branches, and a second turn.
t = 0/3

The idea behind SGLang is that program structure is an optimization resource. Some of that structure is visible in the tokens, and the rest has to be declared.

  • Shared prefixes are in the tokens. The runtime can find them and reuse state.
  • Branches about to arrive are known to the application in advance. Declaring them lets the shared part be computed once.
  • Sessions and weight updates are not in the tokens at all. They must be declared, so the runtime knows whether to keep, drop, or refresh state.

The four parts below follow how the line between inferred and declared has moved.

The original design

There are two ways to find shared prefixes. The frontend can declare the branches, so the program says where requests share context. Or the runtime can match incoming token prefixes against the cache. The 2024 SGLang paper combined both.

Frontend

In the SGLang frontend, a prompt is a state s. fork creates branches from the same point, and gen requests a completion for each branch.

s += shared_context
branches = s.fork(2)
branches[0] += "Fix bug"
branches[1] += "Write tests"
for b in branches:
    b += gen("result")

The frontend knows about the fork before either request exists. It uses that as a hint and sends the shared context first. The runtime computes it once, and both branches reuse it. Without the hint, caching still works for requests that arrive later. The difference is timing.

Fork hintTwo branches from one shared context
FrontendShared contexts.fork(2)Fix bugWrite testsRuntime: prefillKV cacheemptyShared context computed 0×
The frontend holds one shared context and two branches.
t = 0/2

RadixAttention

Serving KV involves three separate jobs. Allocation decides where KV fits in GPU memory, which is what PagedAttention does. The prefix index answers which prefix is already cached, which is what RadixAttention does. Movement carries KV between GPUs, host memory, and storage. It arrives later, with HiCache.

Reuse matters because KV is expensive. Take a model with 32 layers, 8 KV heads of 128 dimensions, and BF16 values. One token takes 128 KiB of KV, and a 32K-token context takes 4 GiB. With a prefix index, a shared prefix is stored once, and requests point to the same pages.

Shared pagesEach block is 1 page · every request adds 1 page of its own
Without sharingWith sharing12 pages6 pagesPPP1PPP2PPP3PPP123

RadixAttention stores cached prefixes in a radix tree. Each node holds a span of tokens, the page ids of that span’s KV, and a lock count. A new request walks the tree from the root and reuses KV up to its first token that differs. A match is rounded down to whole pages. A token’s KV depends on every token before it, so nothing after the first difference can be reused, even if the text is identical.

A running request raises the lock count on every node along its path. A node can be evicted only when its count is 0, and eviction takes unlocked leaves first. A shared prefix therefore outlives the branches below it.

Radix treeSchematic · 1 token per page
New requestRadix treeShared context4 tokens · pages 0–3lock 0Fix bug2 tokens · pages 4–5lock 0Fix bug: turn 21 token · pages 6lock 0
The cache holds Fix bug and Fix bug: turn 2.
t = 0/5

Scheduling

The order of requests changes how much prefill the cache saves. Take a cache that holds 6 tokens and two pairs of requests, where each pair shares a 4-token prefix. Alternating between the pairs computes 24 tokens. Grouping by prefix computes 16. For an offline batch, a depth-first walk of the tree gives the minimum. Each node’s tokens are computed once, which is 4 + 2 + 1 + 3 = 10 tokens on the running example.

Online serving pays for this. Longest-prefix-first sends uncached requests to the back of the queue. The scheduler can also find a fork without the frontend. When two queued requests share a prefix that nothing has cached yet, it holds one back for a batch. The first request caches the prefix, and the second reuses it.

Queue orderCache holds 6 tokens · each pair shares 4 · each request adds 2
AlternatingTokens computed 0Fix bugUnrelated 1Write testsUnrelated 21234GroupedTokens computed 0Fix bugUnrelated 1Write testsUnrelated 21234
t = 0/4

What ships today is more conservative. The default is first come, first served, and the cache-aware rules are opt-in with --schedule-policy lpm. The deferral threshold is 32 tokens. Above 128 waiting requests the scheduler falls back to arrival order, because matching and sorting every waiting request costs too much.

Structured output

A shared prefix is structure in the input. A schema is structure in the output. In {"summary": "...", "grade": "A"}, the field names and punctuation are fixed syntax. Only the summary text and the grade are the model’s choice. The schema limits which tokens can be sampled.

The original design added jump-forward. When the grammar allows only one string, it is appended in one step instead of being decoded token by token. The forced tokens still need KV, so that step is a prefill over them. Jump-forward saves model passes, not KV.

Jump-forwardOutput schema: {"summary": "...", "grade": "A"}
Decode token by tokenModel passes on forced text 0Jump-forwardModel passes on forced text 0
t = 0/6

Looking back

Three kinds of structure show where a declaration is needed.

  • Shared prefixes. Cached prefixes are found by matching tokens. Requests that arrive together must be declared, or one of them waits.
  • Output constraints. The application supplies a schema or grammar.
  • Session lifetime. The runtime cannot tell whether a tool pause means the session is done. The Workloads part returns to this.

Not all of the original design survived.

  • Stayed: automatic prefix reuse. It is on by default. The unified radix tree now covers full KV, sliding-window KV, and recurrent state.
  • Changed: scheduling and the entry point. The default queue order is first come, first served. Applications call an OpenAI-compatible server instead of the frontend language.
  • Stepping stone: jump-forward. It was removed in 2025. Token masking by a grammar backend stayed, with xgrammar as the default.

Models and memory

The original design kept KV for every token, all on the GPU. Neither assumption still holds. Each new layer type and memory tier changed what a cached prefix must hold. New layer types each got their own cache at first, and in 2026 they merged into one.

Cache milestonesMonth of first merge in sgl-project/sglang
  1. Jan 2024RadixAttentionPrograms sharing long prefixesblog
  2. Jan 2025HiCache host tierReused KV outgrew GPU memory#2771
  3. Jun 2025Window-layer cacheLlama 4: local + full layers#6563
  4. Sep 2025Linear-state cacheQwen3-Next: GDN linear layers#10233
  5. Mar 2026HiSparseSparse attention: DeepSeek-V3.2, GLM-5#20343
  6. Apr 2026Unified radix treeFull + window + linear in one model#21206
  7. Jul 2026Unified memoryFixed pools: one runs dry, one idle#29678

Every layer type has to answer the same five questions. The original design answered the first four, for full attention only.

  1. State. What must be kept to resume?
  2. Resume point. Where can a request restart?
  3. Protection. What is locked, and what is evicted?
  4. Memory. Which pool holds the state?
  5. Movement. Where does it live beyond the GPU?

Unified radix tree

Hybrid models mix three layer types, and each keeps different state. Full attention keeps KV for every token, so a request can resume after any matched token. A sliding-window layer keeps only the KV of its recent window. A recurrent layer keeps one state, saved only at some tokens, and each request works on its own copy.

SGLang puts all three on one unified radix tree. A request resumes at the deepest token where every layer type has usable state, and recomputes the rest. Locks and eviction also follow each layer type’s own rule. See Unified Radix Cache in SGLang for the tree and its reuse rules.

Unified memory

Every new layer type brought its own memory pool, sized at startup. Demand shifts with the workload, so a fixed split strands memory. On Reflection Beam, a hybrid-attention model, the default split gives window KV 80% of KV memory, while agent traffic needs 9%. The full-attention pool runs out while the window pool sits idle.

Unified Memory (--enable-unified-memory) replaces the fixed splits with one arena that every KV and state pool shares. On 4× B300, Reflection Beam fits 4.7× as many concurrent long-context requests. See Unified Memory in SGLang for how pages are shared, moved, and freed.

HiCache

Cached state no longer fits on the GPU. HiCache keeps evicted state in host memory and in optional shared storage, and loads it back on a hit. On Inkling-Small with 8× H200 and a 500 GiB storage tier, effective input throughput rises from 15.5K tokens/s with the GPU cache alone to 67.1K. See HiCache in SGLang for the tiers and transfers, and Storage hardware behind SGLang HiCache for when restoring beats recomputing.

Sparse attention

Sparse attention reads only a few KV entries per step, yet a GPU-only cache still holds the full context. HiSparse keeps the full KV in host memory and only the selected entries on the GPU, which frees GPU memory for larger decode batches. With GLM-5.1-FP8 on one 8× H200 server, decode throughput at 256 concurrent requests is more than 3× higher. See HiSparse in SGLang.

Answers by layer type

Full attentionSliding windowRecurrent state
StateKV for every tokenKV for the last windowThe saved recurrent state
Resume pointAny matched token, rounded down to a whole pageWhere a full window of KV sits right before itThe deepest saved state; recompute the rest
ProtectionLock the whole path to the root. Evict unlocked leaves, with their window KV and stateLock the nodes that span one window. Evict older KV; the node staysLock one node. Evict the state alone
MemoryFull KV pool; grows with the contextWindow KV pool; bounded by the windowState pool of fixed-size slots
MovementThe node’s KVKV within one windowOne state slot

The new layer types need nothing new from the application.

Execution

The previous part made more state reusable. This part follows the time that a cache hit leaves behind.

Hit rate and TTFT

A higher hit rate does not lower time to first token by the same amount. Hit rate counts tokens: reused tokens divided by input tokens. TTFT counts time: the wait in the queue, the CPU work of matching the prefix and building the batch, and the GPU prefill of the new tokens. A hit shortens only the last part. The CPU time stays the same and becomes a larger share, so the CPU starts to set the pace.

Hit rate and TTFTSchematic · not measurements
Input tokensCached prefix: reusedNew tokensTime to first tokenQueueCPU: match, build batchGPU: prefill

Overlap scheduling

SGLang prepares the next batch while the GPU runs the current one. With 2 ms of CPU and 6 ms of GPU work per batch, a serial loop takes 8 ms per batch. An overlapped loop takes 6 ms, because the GPU never waits for the CPU.

Overlap schedulingCi prepares batch i · Gi runs it · ideal steady state
Serial8 ms per batchCPUGPUC1C2C3G1G2G3Overlapped6 ms per batchCPUGPUC1C2C3G1G2G3

One dependency stands in the way. The input of batch N+1 is the token sampled by batch N, and waiting for it would undo the overlap. So the CPU never waits for the token. It names a slot in a GPU buffer of sampled tokens as the input, and the GPU fills the slot. In the code this mechanism is FutureMap.

FutureMapSlot k: the request's row in a GPU buffer of sampled tokens
CPUGPUslot k: emptyBatch N+1: read slot k
Batch N+1 needs the token that batch N has not sampled yet.
t = 0/3

Overlap has a limit. A step costs max(CPU, GPU) instead of their sum. With 8 ms of CPU and 6 ms of GPU per batch, a serial step takes 14 ms and an overlapped step takes 8 ms, with the GPU idle for 2 ms. Prefix hits shrink the GPU step, and once the CPU step is the longer one, the CPU sets the pace.

Less CPU work

When overlap is not enough, the remaining lever is to shrink the CPU work. With short prefills, kernel launches and radix tree operations dominate.

An eager forward launches every kernel from the CPU. A CUDA graph replays captured kernels instead, but some operations cannot be captured. A breakable graph runs such an operation between two captured segments. Graph A replays, the operation runs and writes a fixed buffer, and graph B replays and reads that buffer. On gpt-oss-120b with TP4 on 4× GB300, prefill is 1.70× faster than eager. See Breakable CUDA Graph in SGLang.

The radix tree’s match, insert, and evict operations run in Rust, and Python only orchestrates the cache. The Rust radix tree prototype lowers TTFT by up to 38%.

Workloads

Agent and RL workloads raise two questions that the request stream cannot answer. The first is whether a session is over. When a turn finishes and no new request has arrived, a tool call may still be running, or the user may have left. The second is whether cached KV comes from the current weights. A new request can match a cached prefix token for token after the weights were updated. In both cases the tokens are the same, so the runtime cannot tell which case it is in.

Sessions

While a request runs, its KV cannot be evicted. Once it finishes, the KV is evictable. While a tool runs, nothing protects the session’s KV, and the cache sees it as unused. If another request needs memory, the KV is evicted, and the next turn pays for the full history again.

The application can say which requests form a session. With --enable-session-radix-cache, it tags the turns with one session id, or calls open_session and close_session. Session KV is then evicted last, and other unused KV goes first. Closing the session, or a timeout, removes the tag, and the KV becomes ordinary cache again. Each cached node counts the open sessions that reach it, so shared KV stays protected until the last session that uses it ends.

Session lifetimeOne session · a tool call between two turns
Turn 1Tool runs: no requestTurn 2
GPU cacheAnother requestSession A's KVOther KVunusedOther KVunusedTurn 2
Session A is about to start.
t = 0/4

RL rollouts

In RL, new weights can invalidate old KV. The same prompt tokens under new weights give different KV, and token matching cannot see the change. The update call makes the choice. flush_cache defaults to true, so the cache is dropped and the prompt is recomputed with the new weights. Keeping the KV is fast but stale. --enable-prefill-weight-versions reports which weights computed each token’s KV.

Weight updateThe same prompt P before and after an update
EngineWeightsKV of prompt Pv1from v1 · reusedexact, no prefill

Distribution

With several engines, reuse also depends on where a request lands. Miles, an RL framework on SGLang, sends a session’s turns to the same engine and DP rank. A DP rank is a data-parallel replica with its own cache. Miles reports about 96% prefix-cache hits in a GLM-5.2 agentic RL run.

Session affinityThree turns of one session · each engine has its own cache
SessionTurn 1Turn 2Turn 3Engine AEngine BEngine C
A session is about to send three turns.
t = 0/3

For general traffic, the router tracks which engine has each prefix. Each engine streams KV events, and sgl-router’s cache_aware policy keeps one prefix index. The policy is opt-in, and the default is round_robin. The index can be stale, because an engine may evict a prefix before the request reaches it. The engine then checks its local state and restores or recomputes. A stale index costs a recompute, never a wrong answer.

Router indexEngines stream KV events: stored, removed
Engine AEngine BRouter indexRequest: P + suffixholds prefix Pholds prefix Qno entries yet
Engine A holds prefix P. Engine B holds prefix Q.
t = 0/4

A cache hit is not always the fastest route either. The router compares queue time plus remaining work on each engine, and a load-pressure guard can override the best cache match.

Routing choiceIllustrative · remaining work: 10 ms warm · 40 ms cold
RouterEngine A · warmbest cache match80 + 10 = 90 msEngine B · coldfinishes first5 + 40 = 45 ms

The index only works if both sides see the same tokens. If the router and the engine each render the chat, a slightly different template changes one token, and the match stops there. So the router tokenizes once and forwards the ids (#28744). The engine skips its own tokenizer.

Tokenize onceToken ids are illustrative
RouterEngine101202303404505101202999404505first difference
Tokens that match on both sides 2

Prefill/decode disaggregation uses the same reuse to save transfers. With --disaggregation-decode-enable-radix-cache, a decode worker that already holds KV for earlier tokens receives only the missing pages. The reused pages stay locked until the request finishes or fails, so they cannot be evicted while the missing ones are still arriving.

Prefill/decode transfer384-token input · 64 tokens per page
Prefill workerDecode worker257–320321–3841–6465–128129–192193–256257–320321–384Locked until the request finishes or failsTransfer128 →
Reuse 256Transfer 128

Summary

The runtime infers more, and the application declares the rest. In 2024 the application declared the whole program. Today the runtime finds shared prefixes on its own, in every layer type and on GPU, host, and storage. The application declares only what tokens cannot show: the output schema, which requests form a session, and when the weights changed.

Declared and inferredWho knows the program's structure

2024: the original design

The application declares
  • The whole program: fork, gen
  • Output constraints
The runtime infers
  • Cached shared prefixes

Today

The application declares
  • This is one session
  • The weights changed
  • Output schema
The runtime infers
  • Shared prefixes in every layer type
  • On GPU, host, and storage

Next?

The application declares
  • Expected tool duration
  • Fan-out about to happen
  • Deadline
The runtime infers
  • The structure of programs agents write

Open problems

Some hints would help, but an application cannot declare them today.

  • Expected tool duration. Should a paused session’s state stay on the GPU, move to host memory, or be freed?
  • Fan-out about to happen. Should the shared prefix be prefilled once, before the branches arrive?
  • Chance that a prefix returns. Which state is worth keeping, or backing up to host memory?
  • Deadline. Which state should be evicted first? Requests carry a priority today, not a deadline.

Two questions go beyond the cache. Agents now write the programs, so can the runtime learn their structure without a frontend? And when KV is shared across tenants, can reuse leak one tenant’s prompt to another through timing?

Try on SGLang Open the SGLang repo and run this in a real inference engine

Further reading

This visualized tutorial was written by Yichi Zhang.