SGLang

Run SGLang in production. Serve models over HTTP and Python, reuse shared prompt prefixes with the radix cache, constrain output and parse tool calls, scale across GPUs, and benchmark every change with evidence you can defend.

  • Beginner → production
  • 13 units · approximately 14 hours
  • v0.5.18 · Reviewed 2026-09-02

Independent educational course. Project names and marks belong to their respective owners; their use does not imply sponsorship or endorsement.

How to work through this course

Before you begin: The free Foundations course or equivalent knowledge: tokens, prefill and decode, the KV cache, and serving metrics. You should be comfortable with Python and a Linux shell. The deployment runbooks need an NVIDIA GPU; the lesson exercises run on a laptop with Python and NumPy.

By the end: Launch and operate an SGLang service, predict when prefix reuse will cut prefill work, validate structured output and tool calls in your own code, and decide on speculative, quantized, or parallel setups with controlled benchmarks.

  1. Understand the idea. Read each section in order and study its diagrams. When a pause-and-predict question appears, commit to an answer before you reveal it. Look up unfamiliar terms in the glossary below.
  2. Try it yourself. Run the code examples and compare your output with the lesson's. Use the browser labs where available; steps that need a GPU are optional and say so.
  3. Check your understanding. Answer the knowledge check at the end of each lesson and make sure you can say why the other options are wrong. Complete all units to unlock the final quiz; the passing score is 80%.

The optional project brings the lessons together. Keep notes on your choices, results, and any failures so you can explain what you learned.

Course orientation

What is SGLang?

SGLang is an open-source serving engine for large language models and multimodal models. Its runtime, SRT (SGLang Runtime), accepts requests over HTTP or from Python, batches them continuously on one or more GPUs, keeps their KV cache in a radix tree so that shared prompt prefixes are computed once, and streams tokens back. SGLang also includes a frontend language for programs that make several model calls.

The problem it solves

Real traffic repeats itself. Chat turns resend the whole conversation, agents resend the same tool instructions, and few-shot prompts share their examples. A server that recomputes that shared text for every request spends GPU time on prefill and makes users wait longer for the first token. SGLang finds identical token prefixes and reuses their KV cache while it batches many requests, and it constrains and parses outputs for structured and agent workloads.

Request path

  1. 01HTTP server and tokenizer manager

    The API server accepts OpenAI-compatible and native requests, applies the chat template, tokenizes the prompt, and passes the request to the scheduler.

  2. 02Scheduler and radix cache

    The scheduler matches each prompt against the radix tree of cached prefixes, admits requests when KV cache memory allows, and forms every prefill and decode batch.

  3. 03Model workers

    Workers run the forward pass on one or more GPUs, using the chosen attention backend, CUDA graphs, and tensor, pipeline, data, or expert parallelism. Grammar masks restrict sampling when output must match a schema.

  4. 04Detokenizer and response

    The detokenizer turns token IDs back into text and streams it to the client. Parsers separate reasoning from the answer and extract tool calls in the formats a model family uses.

What it covers

  • Scheduling requests into continuous prefill and decode batches and admitting them against KV cache memory.
  • Reusing the KV cache of identical token prefixes across requests, and evicting the least recently used entries when memory runs short.
  • Constrained decoding for JSON schemas, regular expressions, and grammars, plus parsers for reasoning and tool-call formats.
  • Running models across GPUs with tensor, pipeline, data, and expert parallelism, and speeding up decode with CUDA graphs, quantization, and speculative decoding.

Outside its scope

  • Matching prompts by meaning. The radix cache reuses only identical token prefixes, so a reworded or reordered prompt misses.
  • Deciding whether a tool call is allowed. SGLang returns a proposed call, and your application must validate and authorize it before anything runs.
  • Training or fine-tuning models. SGLang serves weights and LoRA adapters that were trained elsewhere.
  • Promising that every combination of features works together. Test each combination you plan to use on the pinned release.
Key terms in this course
SRT
SGLang Runtime: the serving engine that schedules, batches, and executes requests.
RadixAttention
SGLang's way of reusing KV cache for shared prompt prefixes, organized as a radix tree.
Radix tree
A tree of token sequences in which requests that start with the same tokens share one path, and therefore one copy of that KV cache.
Prefix hit
The leading part of a prompt whose KV cache is already in the radix tree, so prefill can skip it.
Chunked prefill
Splitting a long prompt's prefill into pieces so that other requests' decode steps are not stuck behind it.
Constrained decoding
Masking tokens during sampling so the output must match a JSON schema, a regular expression, or a grammar.
Speculative decoding
Drafting several tokens cheaply and checking them in one forward pass of the main model, which can cut the time per output token.
TTFT and ITL
Time to first token and inter-token latency: how long a user waits for the first token, and between later ones.
Goodput
The number of requests per second that succeed and meet every latency target.
PD disaggregation
Running prefill and decode on separate workers and moving each request's KV cache between them.

Syllabus

  1. 02Client APIs, streaming, and operator endpoints70 minProOpenChoose between SGLang's OpenAI-compatible endpoints and the native `/generate` API from the fields each one takes and returns.
  2. 03The offline Engine and the frontend language60 minProOpenStart an `sgl.Engine` inside a Python program and name the processes it launches.
  3. 04Inside the runtime: processes and the scheduler loop60 minProOpenTrace one request through the tokenizer manager, scheduler, model worker, and detokenizer, and say which process owns each step.
  4. 05CUDA graphs and torch.compile in SGLang55 minProOpenExplain which cost CUDA graph replay removes, which cost `torch.compile` removes, and when each one matters.
  5. 06RadixAttention: reuse the KV cache of shared prefixes65 minLabProOpenTrace how SGLang's radix tree matches a prompt, splits a node on insertion, and evicts the least recently used leaf.
  6. 07Scheduling, chunked prefill, and KV cache pressure70 minProOpenPredict how SGLang's `fcfs` and `lpm` scheduling policies order a waiting queue, and pick one for a workload.
  7. 08Structured output, reasoning, and tool calls70 minProOpenConstrain SGLang output with a JSON schema, regex, or EBNF grammar, and say what the token mask guarantees and what it does not.
  8. 09Models, modalities, embeddings, and scoring75 minProOpenCheck whether SGLang v0.5.18 supports a model for your exact task, and read what the server reports about it in `/model_info`.
  9. 10Quantization, KV cache precision, and LoRA adapters70 minProOpenTell weight, activation, and KV cache precision apart, and calculate how each one changes the tokens an 80 GB GPU can hold.
  10. 11Speculative decoding: draft, verify, and measure the gain70 minProOpenExplain how one speculative round drafts tokens, verifies them in a single target pass, and still produces the target model's output.
  11. 12Parallel and distributed serving60 minProOpenCalculate weights, KV cache per token, and KV capacity per GPU for a model under tensor and pipeline parallelism.
  12. 13Benchmark and operate an SGLang service75 minProOpenRun a controlled `bench_serving` comparison that changes one thing and records everything needed to repeat it.
Full unit-by-unit learning objectives (56 outcomes)

01 · What is SGLang?

  • Name the processes a request crosses inside SGLang Runtime and say what each one does.
  • Estimate how much prefill work prefix reuse saves for a workload that repeats a system prompt, and spot prompt layouts that defeat it.
  • Explain what an OpenAI-compatible endpoint guarantees and what stays specific to the engine behind it.
  • Launch SGLang v0.5.18 with a small model, send a first request, and confirm from the reply and the server log that it worked.

02 · Client APIs, streaming, and operator endpoints

  • Choose between SGLang's OpenAI-compatible endpoints and the native `/generate` API from the fields each one takes and returns.
  • Read a streamed response to its final event and tell a normal finish from a length cut, an abort, a mid-stream error, and a dropped connection.
  • Cancel a request by disconnecting or through `/abort_request`, and check that the scheduler stopped working on it.
  • Configure `--api-key`, `--admin-api-key`, and a gateway allowlist so that only an authenticated operator path can reach `/flush_cache` and the other control endpoints.

03 · The offline Engine and the frontend language

  • Start an `sgl.Engine` inside a Python program and name the processes it launches.
  • Send work through `generate` and `async_generate` in batches, and match every result to its prompt.
  • Write a frontend-language program with `gen`, `select`, and `fork`, and predict the requests it sends.
  • Handle startup failures, cancellation, child-process crashes, and shutdown when your application owns the engine.

04 · Inside the runtime: processes and the scheduler loop

  • Trace one request through the tokenizer manager, scheduler, model worker, and detokenizer, and say which process owns each step.
  • Walk through one iteration of the scheduler loop and predict whether it runs a prefill or a decode batch.
  • Calculate whether the scheduler will admit a waiting request from its token budget, and explain why admission belongs in the scheduler.
  • Explain how the overlap scheduler hides CPU work under GPU work, and measure what it saves.

05 · CUDA graphs and torch.compile in SGLang

  • Explain which cost CUDA graph replay removes, which cost `torch.compile` removes, and when each one matters.
  • Predict which captured graph a decode batch replays, how many slots it pads, and when SGLang falls back to eager execution.
  • Configure SGLang v0.5.18's decode and prefill graph backends, capture sizes, and `--enable-torch-compile`, and confirm what actually ran.
  • Run a controlled eager, graphs, and combined comparison that separates startup, first request, warmed latency, and graph memory.

06 · RadixAttention: reuse the KV cache of shared prefixes

  • Trace how SGLang's radix tree matches a prompt, splits a node on insertion, and evicts the least recently used leaf.
  • Calculate the KV cache memory and prefill compute that a shared prefix saves for Llama 3.1 8B.
  • Lay out prompts so that stable content forms one shared token prefix, and spot the layouts that silently break reuse.
  • Confirm reuse on a live server with the `#cached-token` log field, the `cached_tokens` usage field, and the cache metrics.

07 · Scheduling, chunked prefill, and KV cache pressure

  • Predict how SGLang's `fcfs` and `lpm` scheduling policies order a waiting queue, and pick one for a workload.
  • Explain what `--chunked-prefill-size` bounds and when `--enable-mixed-chunk` keeps running streams moving during a long prefill.
  • Calculate how many shared prefix tokens survive page alignment for a given `--page-size`.
  • Tell eviction, retraction, and HiCache tier movement apart from the server's logs and metrics.

08 · Structured output, reasoning, and tool calls

  • Constrain SGLang output with a JSON schema, regex, or EBNF grammar, and say what the token mask guarantees and what it does not.
  • Choose the `--tool-call-parser` and `--reasoning-parser` that match a model, and read the `tool_calls` and `reasoning_content` fields they produce.
  • Predict which `tool_choice` settings constrain tool-call arguments in SGLang v0.5.18 and which leave them to the model.
  • Assemble streamed tool calls, then validate and authorize them in application code before any tool runs.

09 · Models, modalities, embeddings, and scoring

  • Check whether SGLang v0.5.18 supports a model for your exact task, and read what the server reports about it in `/model_info`.
  • Calculate how many tokens and how much KV cache an image costs for a vision-language model, from its published configuration.
  • Call the embedding, rerank, and score endpoints, and state the meaning, scale, and direction of what each returns.
  • Explain why a reranker score is not a probability, and calibrate one against labeled examples.
  • Write an admission policy that keeps large images and batch scoring from slowing interactive chat.

10 · Quantization, KV cache precision, and LoRA adapters

  • Tell weight, activation, and KV cache precision apart, and calculate how each one changes the tokens an 80 GB GPU can hold.
  • Serve a pre-quantized checkpoint or quantize online in SGLang 0.5.18, and confirm from the startup log which method, kernel, and KV cache dtype are actually in use.
  • Explain the scaling data a quantized checkpoint carries, and detect FP8 KV cache scales that silently default to 1.0.
  • Configure multi-LoRA serving with a fixed number of GPU slots, a CPU cache, and an allowlist of adapter names, and compute what the slots cost.
  • Assemble the compatibility, quality, memory, and latency evidence that a release decision needs.

11 · Speculative decoding: draft, verify, and measure the gain

  • Explain how one speculative round drafts tokens, verifies them in a single target pass, and still produces the target model's output.
  • Choose among the algorithms SGLang 0.5.18 supports (EAGLE, EAGLE3, NEXTN, STANDALONE, NGRAM, DFLASH) and set their flags, knowing which defaults SGLang fills in.
  • Turn an acceptance rate, a draft length, and step costs into tokens per target pass, target steps avoided, and expected speedup.
  • Read accept length, accept rate, and verify counts from SGLang's log, Prometheus metrics, and per-request `meta_info`.
  • Bound adaptive speculation by batch size and decide when speculation should switch itself off.

12 · Parallel and distributed serving

  • Calculate weights, KV cache per token, and KV capacity per GPU for a model under tensor and pipeline parallelism.
  • Choose between tensor, pipeline, data, and expert parallelism in SGLang v0.5.18 based on whether the problem is fit, traffic, or mixture-of-experts size.
  • Estimate the communication each layout adds per decode step and explain why the interconnect decides whether it pays off.
  • Launch a tensor-parallel SGLang server, confirm every rank is healthy, and measure scaling efficiency against a one-GPU baseline.

13 · Benchmark and operate an SGLang service

  • Run a controlled `bench_serving` comparison that changes one thing and records everything needed to repeat it.
  • Explain why a warm prefix cache changes prefill cost, and set the cache state of a run on purpose.
  • Sweep offered load to find the saturation point, and compute percentiles and goodput from recorded per-request timings.
  • Write an exit test for an advanced feature before you enable it.
  • Reconstruct one slow request from its ID using request logs, scheduler log lines, Prometheus metrics, and traces.

Optional field project

Launch and tune an SGLang support assistant

  1. 01Launch the service and trace one request
  2. 02Measure prefix reuse and scheduling
  3. 03Validate structured output and optional features
  4. 04Benchmark, scale, and operate the service
View optional project brief

Sign in to read the project brief.

Free guides and tools