What a serving engine does
A serving engine is the program that runs a model for many users at once. It accepts requests, usually through the kind of API that OpenAI made popular, queues them, groups them into batches, runs prefill and decode, manages the KV cache in GPU memory, and streams tokens back.
- RouterPicks one of many copies of the model, ideally one that already has the start of this prompt in its cache
- QueueWaits for room in the batch and in KV cache memory
- SchedulerBefore every step, decides which requests run together
- PrefillReads the prompt and fills its KV cache
- DecodeOne token per step, for the whole batch at once
- StreamEach new token goes back to its user straight away
| From | Known for | |
|---|---|---|
| vLLM | UC Berkeley, 2023; now a large open project | PagedAttention; runs on many kinds of chips |
| SGLang | Researchers at Stanford, UC Berkeley and elsewhere (LMSYS), 2023 | RadixAttention for reusing prompts; fast structured output |
| TensorRT-LLM | NVIDIA | Kernels tuned for NVIDIA GPUs |
| LMDeploy | The InternLM project, China | Its TurboMind engine; up to 1.8 times vLLM’s request throughput, by its own measure |
| llama.cpp (llama-server) | Georgi Gerganov and contributors | Runs almost anywhere, CPUs included, from GGUF files; best for one or a few users |
| Ollama | Ollama | One-command models on your own computer; covered in the next lesson |
Speed for one, or speed for all?
Users and server owners want different things. A user wants the first word fast (time to first token, TTFT) and a smooth stream after it (time per output token, TPOT). The owner wants as many tokens per GPU per second as possible, because that is what pays for the GPU. Batching trades one for the other.
| Users at once | Tokens per second, each user | Tokens per second, all users | Maths units busy |
|---|---|---|---|
| 1 | 205 | 205 | 0. |
| 8 | 185 | 1,476 | 2. |
| 32 | 137 | 4,385 | 7. |
| 64 | 102 | 6,529 | 11 % |
| 128 | 68 | 8,643 | 15 % |
| 200 | 49 | 9,783 | 17 % |
Worked out with the roofline model from the last lesson, at the H100’s peak memory speed. Real servers reach less, but the shape is the same.
Going from 1 to 200 users makes each stream about four times slower but serves almost 48 times as many tokens. The right batch depends on the product: a coding assistant needs fast streams, while an overnight job that summarises a million documents only cares about the total.
Services write their promise down as a service-level objective (SLO), for example “first token within 1 second, then at least 20 tokens per second, for 99 % of requests”. DistServe (Peking University, StepFun and UC San Diego, 2024) calls the rate of requests that keep this promise goodput, and argues that goodput, not raw throughput, is the number to maximise.
Quick check
Continuous batching
The simple way to batch is to collect a group of requests, run them together, and wait until the longest one finishes before starting the next group. Replies differ a lot in length, so most slots sit empty while one long answer finishes.
Orca (Seoul National University and FriendliAI, 2022) changed the unit of scheduling from the request to the step. After every decode step the scheduler can drop finished requests and add waiting ones, so a slot is refilled the moment it frees up. On GPT-3 175B, Orca reported 36.9 times the throughput of NVIDIA’s FasterTransformer at the same latency. Every major engine now works this way, under names such as continuous batching, in-flight batching or iteration-level scheduling.
With 4 slots, waiting for whole batches takes 72 steps and leaves the slots busy about half the time. Switch to refilling: 44 steps, with the slots busy 84 % of the time. Press “New requests” a few times. The gap is biggest when one reply is much longer than the rest.
This interactive part needs JavaScript.
Continuous batching brings a new problem. When a long prompt arrives, its prefill can take as long as a hundred decode steps, and every stream in the batch freezes while it runs. Chunked prefill cuts the prompt into pieces and adds one piece to each step, alongside the decodes. Sarathi-Serve (Microsoft Research India and Georgia Tech, 2024) called this stall-free scheduling, and served up to 2.6 times as many requests as vLLM on Mistral-7B within the same latency limits. vLLM now chunks long prefills by default.
Splitting prefill from decode
Prefill is limited by computing power and decode by memory speed, yet on one GPU they take turns and get in each other’s way. Disaggregation runs them on separate GPUs: prefill machines read the prompt and build its KV cache, then send the cache over the network to decode machines, which write the reply.
Together on one GPU
- Simple: one kind of machine
- A long prompt slows down everyone’s stream
- One batch size and one way of splitting the model must suit both jobs
Split across GPUs
- Each side is tuned for its own job, and can even use different chips
- The KV cache must be copied between machines, so fast networks matter
- Each side can grow or shrink on its own as traffic changes
| From | Reported result | |
|---|---|---|
| Splitwise (2023) | Microsoft | 1.4 times the throughput at 20 % lower cost, or 2.35 times the throughput for the same cost and power |
| DistServe (2024) | Peking University, StepFun, UC San Diego | 7.4 times as many requests, or limits 12.6 times tighter, while keeping over 90 % of requests within them |
| Mooncake (2024) | Moonshot AI (maker of Kimi) and Tsinghua University | Lets Kimi handle 75 % more requests on real traffic |
Mooncake treats the KV cache as the most valuable thing in the data centre. Long documents and chats come back again and again, so it keeps their caches in the cluster’s spare CPU memory and SSDs, and its scheduler sends each request to where its cache already is. When the system is overloaded, it predicts which requests would miss their deadline anyway and turns them away early, rather than slowing everyone down.
Quick check
How DeepSeek serves a 671B model
In February 2025, on the last day of its Open Source Week, DeepSeek described how it serves DeepSeek-V3 and R1 and published a day of real figures. The model has 256 experts in each layer and uses 8 for each token, so any one expert sees only a small share of the tokens. To give each expert a batch big enough to keep a GPU busy, DeepSeek spreads the experts over many servers and splits prefill from decode.
| Prefill | Decode | |
|---|---|---|
| One unit of the service | 4 servers, 32 GPUs | 18 servers, 144 GPUs |
| Experts on each GPU, per layer | 9 routed and 1 shared | 2 routed and 1 shared |
| Spare copies of busy experts | 32 | 32 |
| Average speed of one server | 73,700 tokens per second in | 14,800 tokens per second out |
Each server has 8 GPUs. Matrix maths and sending tokens to experts use FP8, as in training; attention and gathering the experts’ results use BF16.
- Two micro-batches. While one is computing, the other’s tokens are on the network, so the communication hides behind the maths. In decode, the work is split further into a five-stage pipeline.
- Three load balancers. One evens out attention work and input tokens across prefill GPUs, one evens out KV cache use and requests in decode, and one places the experts so that no GPU gets the busiest ones all together.
- Day and night. At the daytime peak the service used 278 servers. At night it shrinks, and the freed GPUs go to research and training.
226.75 servers × 8 GPUs × 24 hours × $2 = $87,072The average number of servers in use, at the rental price DeepSeek assumed.
608 billion tokens in (56.3 % from the cache), 168 billion tokens outEach user saw about 20–22 tokens per second, and each new token had about 5,000 tokens of context behind it.
$562,027 ÷ $87,072 ≈ 6.45, a 545 % profit margin, in theoryIf every token had been billed at R1’s API prices. Real income was much lower: the web and app are free, V3 is cheaper, and prices are discounted at night.
one decode server = 8 GPUs × $2 = $16 an hourAt the same assumed rental price.
14,800 tokens per second × 3,600 seconds ≈ 53.3 million tokens an hourThe average output of one decode server.
$16 ÷ 53.3 ≈ $0.30 per million output tokensCompared with R1’s list price of $2.19. The true cost is higher: prefill servers, spare capacity and research are left out.
Huawei served DeepSeek-R1 the same way on its CloudMatrix384, with the experts spread over 320 NPUs. It reported 6,688 tokens per second per NPU in prefill and 1,943 in decode at under 50 ms per token. Under a tighter limit of 15 ms per token, about 67 tokens per second for each user, it still delivered 538 tokens per second per NPU.
Many copies of the model
One server is rarely enough, so services run many copies of the model with a router in front. A simple router sends each request to the least busy copy. A smarter one also looks at the prompt: requests that start the same way, with the same system prompt, the same long document or the same agent conversation, go to the copy that already has that start in its cache. SGLang’s gateway keeps a prefix tree of recent prompts for exactly this, and Mooncake builds its whole design around it.
Does each change mainly raise total throughput, or mainly make each user’s reply faster?
-
Raising the batch from 8 to 128 users
Answer: More throughput
-
Speculative decoding with a small draft model
Answer: Faster for each user
-
Continuous batching
Answer: More throughput
-
Splitting one copy of the model over 8 GPUs with tensor parallel
Answer: Faster for each user
-
An 8-bit KV cache, so twice as many chats fit in memory
Answer: More throughput
-
Chunked prefill, so long prompts stop freezing other streams
Answer: Faster for each user
Run your own server
With one NVIDIA or AMD GPU and vLLM installed, you can run the same kind of server the big services use, and measure it the same way.
# Start an OpenAI-style server on port 8000
vllm serve Qwen/Qwen3-8B \
--max-model-len 32768 \
--gpu-memory-utilization 0.90 \
--max-num-seqs 128
# Ask it something
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "Qwen/Qwen3-8B", "messages": [{"role": "user", "content": "Hello"}]}'
# Measure it: 200 made-up requests, at most 64 at a time
vllm bench serve --model Qwen/Qwen3-8B \
--dataset-name random --random-input-len 1024 --random-output-len 256 \
--num-prompts 200 --max-concurrency 64
--max-model-lencaps the context of each request, and--gpu-memory-utilizationis the share of GPU memory vLLM may take. Whatever is left after the weights becomes KV cache.--max-num-seqscaps how many requests share a batch. If memory runs out mid-reply, vLLM pauses a request and recomputes it later. If that happens often, its guide suggests more memory, fewer requests at once, or more GPUs (--tensor-parallel-size 2).- The benchmark prints throughput, then TTFT, TPOT and the gap between tokens as mean, median and 99th percentile. Run it again with
--max-concurrency 1and compare. Change--seedbetween runs, or the prefix cache can make repeats look faster than they are.
Remember
- A serving engine (vLLM, SGLang, TensorRT-LLM, LMDeploy, llama.cpp) queues requests, batches them, manages the KV cache and streams tokens back.
- Bigger batches give more tokens per GPU but slower streams for each user. Services promise latency in an SLO and aim for goodput: requests per second that keep the promise.
- Continuous batching refills a slot after every step (Orca, 2022). Chunked prefill stops long prompts from freezing other streams.
- Disaggregation puts prefill and decode on different GPUs and moves the KV cache between them (Splitwise, DistServe, Mooncake).
- DeepSeek serves V3 and R1 with experts spread over 144 GPUs per decode unit; its decode costs come to about $0.30 per million output tokens at $2 per GPU hour.
- Routers send requests with the same start to the copy that already has it cached.
Words to know
- Serving engine
- The program that runs a model for many users at once, such as vLLM or SGLang.
- Throughput
- How much work a server gets through: tokens or requests per second, for everyone together.
- Latency
- How long one user waits: for the first token (TTFT) and between tokens (TPOT).
- SLO (service-level objective)
- A written promise about latency, such as “first token within 1 second for 99 % of requests”.
- Goodput
- Requests per second that keep the latency promise.
- Continuous batching
- Adding and removing requests after every step, so free slots are refilled at once.
- Chunked prefill
- Cutting a long prompt into pieces and running one piece per step, beside the decodes.
- Disaggregation
- Running prefill and decode on separate GPUs and sending the KV cache between them.
- Preemption
- Pausing a request when memory runs out, then recomputing it later.
- Micro-batch
- Part of a batch. Two micro-batches can take turns, so one computes while the other communicates.
- Load balancer, router
- The part that decides which GPU or which copy of the model gets each piece of work.
- 99th percentile (P99)
- The value that 99 % of requests beat; what the slowest 1 % of users feel.
Go to the source
This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.
-
Orca: A Distributed Serving System for Transformer-Based Generative Models
Continuous batching, under the name iteration-level scheduling. The idea every engine now uses.
-
Efficient Memory Management for Large Language Model Serving with PagedAttention
The vLLM paper: KV cache in pages, 2–4 times the throughput of earlier systems.
-
SGLang: Efficient Execution of Structured Language Model Programs
RadixAttention for reusing prompts, and fast structured output.
-
Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve
Chunked prefill and stall-free scheduling, with clear pictures of why streams freeze.
-
Splitwise: Efficient generative LLM inference using phase splitting
Measures prefill and decode separately on real traffic, then puts them on different machines.
-
DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving
Defines goodput and shows how to choose the GPUs and parallelism for each phase.
-
Mooncake: A KVCache-centric Disaggregated Architecture for LLM Serving
How Kimi is served: a cluster-wide KV cache in spare memory and SSDs, and turning requests away early under overload.
-
DeepSeek-V3/R1 Inference System Overview
DeepSeek’s own layout, load balancers and one day of costs. Short and full of numbers.
-
Serving Large Language Models on Huawei CloudMatrix384
Serving DeepSeek-R1 on 384 Ascend NPUs, with experts over 320 of them.
-
vLLM: Optimization and Tuning
The practical guide to preemption, chunked prefill and the settings in this lesson.
Check yourself
5 questions. Tap the answer you think is right.
0 of 5 answered
Lesson complete
Answer every question above to complete this lesson.
Your progress is saved on this device only.
Next lessonRun AI on your own computer