Phase 03/Alternative engines/SGLang
PHASE 03 · Alternative engines

SGLang

0%
6 h5 subtopics2 lessons · 1 required
In plain English

SGLang is a second, younger kitchen design that competes with vLLM. Its signature idea is a shared recipe tree called RadixAttention. Picture a library where every conversation is a path through a tree of pages: two chats that start with the same instructions share the same first branch, so the kitchen only prepares that part once and both customers benefit. This makes it very fast for workloads with long repeated prefixes, such as agents that re-send the same system prompt, or multi-turn chats. SGLang also ships a small programming language for describing structured outputs and multi-step prompts, and a fast way to force the model to produce valid JSON.

Why it matters

SGLang is used in production at several large labs and often leads vLLM on throughput benchmarks for prefix-heavy traffic. Knowing both engines lets you choose on evidence, and its codebase is a cleaner second example of the same scheduler and KV-manager ideas you just built.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Launch an SGLang server for a small model and query it through its OpenAI-compatible API.
  • Explain RadixAttention and how a radix tree generalises block-hash prefix caching.
  • Measure the cache hit rate and TTFT gain on a shared-prefix workload.
  • Use the SGLang frontend language or JSON schema constraints to produce structured output.
  • Name the main architectural differences between SGLang and vLLM.

Key concepts

RadixAttention
KV cache organised as a radix tree keyed by token sequences so any shared prefix, not just full blocks, is reused automatically.
Radix tree
A compressed prefix tree where each edge holds a token run; lookups find the longest matching prefix.
Cache-aware scheduling
Ordering waiting requests so those sharing a cached prefix run together, raising the hit rate.
Frontend language
SGLang's Python DSL with gen, select and fork for multi-call programs that share state.
Constrained decoding
Masking logits each step so output follows a regex or JSON schema; SGLang uses a compressed finite state machine.
Zero-overhead scheduler
Overlapping CPU scheduling of step N+1 with GPU execution of step N so the GPU never waits.
Tokenizer manager
The SGLang process that tokenizes and detokenizes, separate from the scheduler process that owns the GPU.

Subtopics

  1. 1. Launching and the OpenAI API

    python -m sglang.launch_server, key flags (mem-fraction-static, max-running-requests, context-length), and health checks.

  2. 2. RadixAttention

    Radix tree over token sequences, LRU eviction of leaves, reference counts for running requests, and insertion after each request finishes.

  3. 3. Cache-aware scheduling

    Sorting the waiting queue by matched prefix length to maximise reuse, and its interaction with fairness.

  4. 4. Structured output

    Regex and JSON schema constraints via compressed FSMs (Outlines/XGrammar) and the frontend language's gen and select.

  5. 5. SGLang versus vLLM

    Process layout, scheduler overlap, prefix caching granularity, and which workloads favour each engine.

Resources

Hands-on lessons

L1

Measure RadixAttention cache hits on a T4

Colab T4 · freenotebook90 minrequired

Goal · An SGLang server for Qwen2.5-0.5B-Instruct with a measured TTFT difference between unique prompts and prompts sharing a 600-token system prompt.

  1. 1In Colab run pip install "sglang[all]" openai and launch python -m sglang.launch_server --model-path Qwen/Qwen2.5-0.5B-Instruct --dtype half --port 30000 in the background.
  2. 2Confirm the server is up with curl http://localhost:30000/health and read the startup log for the KV pool size.
  3. 3Build 40 prompts with a shared 600-token system prompt and distinct short questions, and 40 prompts with 600 unique random tokens each.
  4. 4Send each set sequentially with stream=True and record TTFT (time to first content chunk) per request.
  5. 5Read the server log lines for cached tokens per request (or GET /metrics) and compute the hit rate for each set.
  6. 6Plot TTFT distributions for both sets and compute the ratio of medians.
  7. 7Repeat the shared-prefix set with --disable-radix-cache and record the difference.
Deliverable
A notebook with the two TTFT distributions, the hit-rate numbers and the radix-disabled comparison.
Check
Median TTFT for the shared-prefix set is at least 30 percent lower than for unique prompts, and the gap disappears with --disable-radix-cache.
Fallback
Run the same TTFT experiment against the toy CPU server from p3-llm-serving-architecture-l1 after adding a dict-based prefix cache of past_key_values keyed by prompt prefix.
L2

Force valid JSON with constrained decoding

Colab T4 · freenotebook45 minoptional

Goal · 50 of 50 responses parse as JSON matching a schema using SGLang's json_schema parameter, versus a measured failure rate without constraints.

  1. 1Define a pydantic model for a product review (title, rating 1-5, pros list, cons list) and export its JSON schema.
  2. 2Ask the server for 50 reviews with no constraints and count json.loads plus schema-validation failures.
  3. 3Repeat passing response_format with the json_schema and count failures.
  4. 4Compare tokens per second for both runs and note the overhead of constrained decoding.
Deliverable
A notebook with both failure counts and the throughput comparison.
Check
Constrained run has zero schema failures.

Build your own

Build your own radix-tree prefix cache

PythonCPU · your Mac~6 h

RadixAttention's data structure written from scratch, with node splitting, in-flight locks, LRU eviction under a token budget and a hit-rate replay on agent-style traces.

The real thing: github.com/sgl-project/sglang/blob/main/python/sglang/srt/mem_cache/radix_cache.py ↗

How you know a stage passes

Write tests/test_radix.py first. Stages 1 to 4 are unit tests on token-id lists with hand-drawn expected trees (node count, edge lengths, matched prefix length) plus a brute-force oracle that recomputes the longest common prefix over all inserted sequences and must agree with match_prefix on 1,000 random queries. Stages 5 and 6 are a replay script whose hit-rate numbers are asserted within ranges. Run `pytest -q`.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01insert and match_prefix
    A RadixTree over token ids where each node stores a token slice and a list of KV block ids; insert adds a sequence and match_prefix returns the matched length and the blocks.
    test · Inserting tokens 1..100 then matching 1..50 returns length 50; matching an unrelated sequence returns 0; the brute-force oracle agrees on 1,000 random queries.
  2. 02node splitting
    Inserting a sequence that diverges in the middle of an existing edge splits that node into a shared parent and two children.
    test · Insert A (tokens 1..100) then B (1..60 followed by 60 different tokens); the tree has exactly 3 nodes, the split node holds 60 tokens, and match_prefix(B) returns 120.
  3. 03locks and LRU timestamps
    Nodes used by in-flight requests hold a lock count and cannot be evicted; every match updates a last-access time along the path.
    test · With two nodes locked, evict(k) only removes unlocked leaves, and the removal order over 20 inserted sequences equals the order of their last-access times.
  4. 04eviction under a token budget
    The tree is integrated with a block pool; when the pool is empty, enough leaf tokens are evicted (LRU) to admit the new sequence.
    test · With a 4,096-token budget and 10,000 tokens inserted over time, resident tokens never exceed 4,096 (assertion on every insert) and no insert fails.
  5. 05replay agent traces
    A generator produces multi-turn conversations with five shared system prompts, growing histories and tool-call turns; a replay script feeds them through the tree and reports hit rate and prefill tokens saved.
    test · Hit rate on a 200-conversation synthetic trace is at least 60 percent and on a unique-prompt trace is below 1 percent; both numbers are printed and asserted within those ranges.
  6. 06compare against exact-match LRU and no cache
    The replay script runs the same trace through an exact-prompt LRU cache and no cache and tabulates prefill tokens computed for each.
    test · The radix tree saves strictly more prefill tokens than exact-match LRU on the agent trace, and README has the three-row table and a short explanation.

Knowledge check

QHow does RadixAttention differ from vLLM's block-hash prefix caching?

It matches prefixes at token granularity through a radix tree rather than only whole 16-token blocks, and the tree makes eviction and sharing across many branches natural.

QWhy does SGLang reorder the waiting queue by cached prefix length?

Running requests that share a prefix back to back keeps that prefix hot in the cache and raises the hit rate; it trades some FCFS fairness for throughput.

QHow does constrained decoding guarantee valid JSON?

A finite state machine compiled from the schema tells the sampler which tokens are legal at each step, and all other logits are masked to minus infinity.

QWhich workloads benefit most from SGLang's design?

Prefix-heavy ones such as agents re-sending long system prompts, few-shot prompting, multi-turn chat and tree-of-thought style branching.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 notebook shows the TTFT gap and hit rates with and without the radix cache.
  • Can explain RadixAttention with a drawn radix tree of three shared prompts.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →