Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Event loop | The single thread in an asyncio program that switches between many waiting tasks. If one task blocks it, every task waits. |
| Chat template | A small program shipped with a chat model that turns a list of messages into the exact text layout the model was trained on. |
| Jinja2 | The template language chat templates are written in. |
| Thread pool | A fixed set of helper threads that run blocking jobs so the event loop does not have to. |
| Admission control | Deciding at the door whether to accept a request at all, instead of queueing everything. |
| HTTP 503 | “Service unavailable”: the standard “try again, maybe elsewhere” answer. |
| TTFT | Time to first token: from sending the request to receiving the first piece of the answer. |
1. What is it?#
The frontend is everything that happens to a request before the engine core sees it, all in the API server process, all on the CPU. A JSON body is validated, a chat template turns a list of messages into one string, a tokenizer turns the string into integers, limits are checked, and finally an admission check decides whether the server has room at all.
None of this uses the GPU, and all of it adds to time to first token. On long prompts and with images it can be the largest part of that time, which is why it has its own process, its own thread pools and, increasingly, its own machines. Read from the v0.32.0 source; facts checked on 13 November 2026.
flowchart LR J[":i-file-text: <b>JSON body</b><br/><small>messages, tools, sampling</small>"] --> V[":pydantic: <b>Validate</b><br/><small>request schema</small>"] V --> T[":i-code: <b>Chat template</b><br/><small>Jinja2 to one string</small>"] T --> K[":huggingface: <b>Tokenizer</b><br/><small>thread pool</small>"] IMG[":i-eye: <b>Images, audio</b><br/><small>fetch, decode, preprocess</small>"] --> MM[":i-cpu: <b>MM processor</b><br/><small>single worker + cache</small>"] K --> IP[":i-funnel: <b>InputProcessor</b><br/><small>length, params, LoRA</small>"] MM --> IP IP --> AD[":i-shield-check: <b>Admission</b><br/><small>queue limits to 503</small>"] AD --> E[":vllm: <b>Engine core</b><br/><small>EngineCoreRequest</small>"] class J,IMG neutral class V,T,K,MM compute class IP,AD queue class E io
2. Why does it exist?#
The engine core is a tokens-in, tokens-out machine (16.d). Something has to turn the many API shapes clients speak (OpenAI chat, OpenAI completions, Responses, Anthropic Messages, Cohere, embeddings, audio) into token IDs and sampling parameters, and has to refuse bad or excessive requests before they cost GPU time. Doing that in the engine core would stall the scheduler; doing it carelessly on the API server’s event loop would stall every other client. The frontend is the careful version.
3. Simple analogy#
The front desk of a clinic. The receptionist checks your form is filled in (validation), copies your answers onto the clinic’s standard sheet (chat template), codes them for the system (tokenising), checks the request makes sense (you cannot book a two-hour slot in a one-hour day), and, if the waiting room is already too full to see you today, tells you at once to try the clinic down the road (503) rather than letting you wait four hours.
4. Tiny example: one chat request, rendered#
messages: [{"role": "system", "content": "Be brief."},
{"role": "user", "content": "Hi"}]
rendered: <|im_start|>system\nBe brief.<|im_end|>\n
<|im_start|>user\nHi<|im_end|>\n
<|im_start|>assistant\n
token IDs: [151644, 8948, 198, ...] (one integer per token)The trailing <|im_start|>assistant\n is the generation prompt: it tells the model that the
next thing to write is its own reply. You can see this for any model by calling the server’s
/tokenize endpoint with a messages body and then /detokenize with the IDs it returns
(exercise 2).
5. Technical explanation#
The server#
The API server is a FastAPI application run by uvicorn on a single asyncio event loop. Route
handlers live under vllm/entrypoints/, one sub-package per API family: openai/, anthropic/,
cohere/, pooling/, speech_to_text/. All of them end by calling the same method,
AsyncLLM.generate() (or AsyncLLM.encode() for embedding models).
Because there is one event loop, anything slow must be moved off it or every other client waits. That rule explains the structure of this whole lesson.
warning
--api-key protects only paths that start with /v1, /v2, /inference or /cohere
(GUARDED_PREFIX in vllm/entrypoints/serve/middleware/authenticate.py). Other routes on the
same port are not authenticated: /invocations, which can run inference, as well as
/metrics, /health, /tokenize and, when enabled, the development endpoints. Do not expose
the port directly to an untrusted network; put a reverse proxy or gateway in front and allow
only the paths you intend to serve.
Step 1: the chat template#
A chat model was trained on text with a precise layout: special tokens marking where each turn begins and ends and who is speaking. The chat template is a Jinja2 program, shipped in the model’s tokenizer configuration, that produces that layout from a list of messages.
- No template, no chat. If the model ships none and you do not pass
--chat-template, every/v1/chat/completionsrequest fails./v1/completionsstill works; it sends your string as written. - Templates take arguments.
chat_template_kwargsin the request body is passed through. This is how per-request switches such as “enable thinking” reach models that support them. - Tools go through the template. The
toolsarray is rendered into the prompt by the template; there is no separate channel (18.i). - The template is treated as untrusted code. It comes from a model repository, so it runs in
Jinja2’s
ImmutableSandboxedEnvironmentwith a time limit (VLLM_CHAT_TEMPLATE_RENDER_TIMEOUT, 30 seconds by default). A template that hangs is abandoned and its thread pool replaced, so the stuck thread cannot block later requests.
The class that owns templating and tokenising is the renderer (vllm/renderers/).
HfRenderer (hf.py) handles anything with a Hugging Face tokenizer; a few model families
(mistral.py, deepseek_v4.py, kimi_k3.py and others) have their own.
Step 2: the tokenizer#
Tokenising is CPU work that can take tens of milliseconds for a long prompt. Doing it on the
event loop would freeze every other connection, so the renderer hands it to a thread pool. From
BaseRenderer.__init__ in vllm/renderers/base.py:
# Thread pool executor for blocking tokenizer operations. The
# multimodal processor receives a deep-copied tokenizer (see #36557)
# so it is safe to run tokenization and MM preprocessing concurrently.
pool_workers = config.model_config.renderer_num_workers
self._executor = _SwappableExecutor(max_workers=pool_workers)
# Separate single-worker executor so tokenization never queues behind
# MM preprocessing; must stay single-worker per #38418 (P0/P1 order).
self._mm_executor = ThreadPoolExecutor(max_workers=1)--renderer-num-workers defaults to 1. Hugging Face “fast” tokenizers are written in Rust and
release the GIL while they work, so one thread keeps the loop responsive; raise it when many long
prompts arrive together. (It has no effect on the offline LLM class, which renders prompts one
after another.)
Multimodal preprocessing (resizing images, extracting video frames, computing audio features) gets a separate single-thread pool, so text requests never wait behind an image. The preprocessed result is cached by content hash, so the same image sent twice is processed once; that cache is mirrored in the engine core so the processed data does not cross the socket a second time (18.h).
Step 3: InputProcessor#
InputProcessor.process_inputs() in vllm/v1/engine/input_processor.py turns a rendered prompt
plus parameters into an EngineCoreRequest. It is where most client mistakes are caught, before
any GPU time is spent:
| Check | Rule | What the client sees |
|---|---|---|
| Empty prompt | Zero prompt tokens is an error | 400: “The decoder prompt cannot be empty” |
| Prompt too long | prompt_len > max_model_len | 400: “The decoder prompt (length N) is longer than the maximum model length of M” |
| No room to answer | prompt_len == max_model_len for a generative model | 400: prompt “plus the number of requested output tokens (at least 1) is longer than…” |
max_tokens unset | Set to what is left of the context, max_model_len - prompt_len (the HTTP layer also caps it by any max_new_tokens in the generation config) | The answer may run to the end of the context window |
| Token IDs out of range | An ID not in the vocabulary | 400 |
| LoRA not enabled | The request names an adapter but the server was started without LoRA support | 400: “Got lora_request … but LoRA is not enabled!” |
| Sampling parameters | Types and ranges, and that any structured-output schema is acceptable to the backend | 400 |
One line, in assign_request_id(), deserves attention:
request.request_id = f"{request.external_req_id}-{random_uuid():.8}"Whatever request ID the client supplied, the engine appends eight random characters. Two clients
sending the same X-Request-Id therefore cannot collide inside the scheduler. The original ID is
kept as external_req_id and is what appears in responses.
Step 4: n > 1 becomes n requests#
If the client asks for n: 4, the engine has no notion of “one request with four answers”.
AsyncLLM.add_request creates a ParentRequest (vllm/v1/engine/parallel_sampling.py) and four
child requests with their own IDs (and, when a seed was given, their own seeds). They are
scheduled as four independent sequences. Their identical prompt is computed once and shared
through prefix caching, and the parent reassembles the outputs. For admission, a request with
n = 4 counts as four.
Step 5: admission control#
By default vLLM’s waiting queue is unbounded: requests are accepted until memory runs out, and
each waits as long as it must. Under overload that is the wrong behaviour: latency grows without
limit and clients time out after the work has already been queued. Two optional limits
(AsyncLLM.check_admission) turn excess load into an immediate, retryable error:
| Flag | Counts | At the limit |
|---|---|---|
--max-num-queued-reqs | Unfinished requests, waiting and running, across all data-parallel engines this API server routes to | HTTP 503 (QueueOverflowError) |
--max-num-queued-tokens | Total prompt tokens of requests that have not yet produced their first token | HTTP 503 (MaxQueuedTokensError) |
503 is deliberate: load balancers and client SDKs treat it as “try another instance”. Unlike
--max-num-seqs, which is per engine, these limits are enforced in the API server.
The token limit is a TTFT guard, and the config’s own docstring gives the formula:
max_num_queued_tokens = target_TTFT × prefill_throughput
e.g. target 2 s, measured prefill speed 20,000 tokens/s → 40,000If 40,000 prompt tokens are already waiting to be read, a new request cannot possibly start answering within two seconds, so it is better refused than accepted.
The count is deliberately pessimistic. A request contributes its whole prompt length until its first output token arrives, even if most of the prompt has been read or was found in the prefix cache, because the engine core reports nothing to the API server during prefill. The docstring says so: this “overestimates the real backlog, causing earlier rejection than strictly necessary — the safe direction for QoS.”
With several API server processes, the request count is kept in a small shared-memory array
(SharedAdmissionStats in vllm/v1/engine/admission_control.py): each process writes only its
own 64-byte slot, so there is no lock and no cache-line contention, and readers sum the slots.
Step 6: hand-off#
AsyncLLM._add_request then does three things in order:
self.check_admission(request_id=request.request_id)
# Register locally before the first await so concurrent tasks see this request.
self.output_processor.add_request(request, prompt, parent_req, index, queue)
await self.engine_core.add_request_async(request)The output side is registered before the request is sent. If it were the other way round, a very fast engine could return the first token for a request the API server did not yet know about.
6. Under the hood: splitting the frontend off#
Since the engine core only ever sees token IDs, the frontend can run somewhere else:
vllm launch render <model>starts a server with no GPU that only renders: it exposes/v1/chat/completions/render,/v1/completions/renderand the matching/derenderpaths (messages to token IDs and back).vllm serve --enable-scale-outadds those endpoints plus a tokens-in, tokens-out endpoint (/inference/v1/generate) to an ordinary server;--tokens-onlyserves only the tokens-in, tokens-out endpoint.- An experimental API server written in Rust (
VLLM_USE_RUST_FRONTEND=1 vllm serve, source inrust/) replaces the Python one and speaks the same socket protocol to the engine core (19.h).
A router that knows the token IDs before choosing a replica can send a request to the replica whose prefix cache already holds that prompt. That is the main reason the split exists (21.g).
7. Performance implications#
Size the token limit, then watch it work. The simulation feeds a server more prompt tokens per second than it can read and compares an unbounded queue with a bounded one.
package main
import "fmt"
func main() {
const (
prefillSpeed = 20000.0 // prompt tokens the GPU reads per second
targetTTFT = 2.0 // seconds
promptTokens = 4000 // every request, for simplicity
arrivalRate = 7.0 // requests per second: 28,000 tokens/s, 40% over capacity
seconds = 30
)
maxQueuedTokens := int(targetTTFT * prefillSpeed)
fmt.Printf("max_num_queued_tokens = %.0f s x %.0f tok/s = %d\n\n",
targetTTFT, prefillSpeed, maxQueuedTokens)
run := func(limit int) (accepted, rejected int, worstWait float64) {
backlog := 0.0 // prompt tokens waiting to be read
const tick = 0.01
carry := 0.0
for t := 0.0; t < seconds; t += tick {
backlog -= prefillSpeed * tick
if backlog < 0 {
backlog = 0
}
carry += arrivalRate * tick
for carry >= 1 {
carry--
if limit > 0 && int(backlog) >= limit {
rejected++
continue
}
// This request waits for everything ahead of it, then its own prompt.
wait := (backlog + promptTokens) / prefillSpeed
if wait > worstWait {
worstWait = wait
}
backlog += promptTokens
accepted++
}
}
return
}
for _, limit := range []int{0, maxQueuedTokens} {
a, r, w := run(limit)
name := "unbounded queue"
if limit > 0 {
name = fmt.Sprintf("limit %d tokens", limit)
}
fmt.Printf("%-20s accepted %3d rejected(503) %3d worst time-to-first-token %.1f s\n",
name, a, r, w)
}
}Output:
max_num_queued_tokens = 2 s x 20000 tok/s = 40000
unbounded queue accepted 210 rejected(503) 0 worst time-to-first-token 12.2 s
limit 40000 tokens accepted 160 rejected(503) 50 worst time-to-first-token 2.2 sWithout the limit every request is accepted and the last ones wait over twelve seconds for their first token. With it, about a quarter are refused instantly and everyone who is accepted is served close to the target. Refusing is the kinder behaviour: a 503 in one millisecond can be retried elsewhere; a twelve-second wait cannot be taken back.
Other costs to keep in mind:
- Tokenising is per request, detokenising is per token (16.f). Under many short streaming
requests the API server’s CPU, not the GPU, is often the first limit. More API servers
(
--api-server-count) or more renderer threads help. - Images are expensive. Fetching and preprocessing one image can take longer than reading a thousand text tokens, and it all lands on time to first token.
8. Production implications#
- Set
--max-num-queued-tokensfrom a measured prefill speed and your TTFT target, and make sure your load balancer retries 503s on another replica. - Size
--max-num-queued-reqsas roughlyDP × max_num_seqsplus the queue depth you accept, or it will bind before the engines do. - Never expose the raw port to the internet;
--api-keycovers only some prefixes. - Pass
max_tokensexplicitly from clients. An unset value lets one request run to the end of the context window. - Pin or override the chat template (
--chat-template) if you need identical prompts across model revisions.
9. Common mistakes#
- Leaving the queue unbounded under bursty traffic. Latency climbs for everyone instead of some requests failing fast.
- Assuming
--api-keysecures the server./invocationsand other paths are open. - Sending a prompt exactly
max_model_lenlong. It is rejected: there is no room for even one output token. - Expecting
n = 4to cost one request. It is four sequences, for the scheduler and for admission. - Blaming the GPU for slow first tokens on image requests. Measure frontend time first.
10. Hands-on exercise#
- Send a chat request with
"max_tokens"omitted and a tiny prompt. Look atusagein the response and at the server’smax_model_len. What wasmax_tokensset to? - Call
/tokenizewith a chatmessagesbody, then/detokenizewith the IDs it returns. The text you get back is the rendered chat template. Find the generation prompt at the end. - In the program, set
arrivalRateto 4.5 (below capacity). How many requests are rejected with the limit on? (It prints 0 for both, with a worst wait of 0.2 s.) What does that tell you about the cost of enabling the limit when the server is healthy? - Start a server with
--api-key secretand trycurl localhost:8000/v1/modelsandcurl localhost:8000/metricswithout the key. Which one answers?
11. Interview questions#
- Why does tokenising run on a thread pool instead of directly in the request handler?
- A request has a prompt exactly as long as
max_model_len. Is it accepted? Why? - Why does the queued-token count use the full prompt length even when most of the prompt is cached?
- Why does the API server register a request with its output processor before sending it to the engine core?
- Why are chat templates rendered in a sandbox with a timeout?
- What does a 503 from admission control let a load balancer do that a slow 200 does not?
12. Further reading#
Checked on 13 November 2026, against the v0.32.0 tag.
vllm/v1/engine/input_processor.py:process_inputs,assign_request_id, the length checksvllm/v1/engine/async_llm.py:check_admission,add_request,_add_requestvllm/renderers/base.py: the two thread poolsvllm/config/scheduler.py: the admission limits and their docstringsvllm/entrypoints/serve/middleware/authenticate.py: which paths--api-keyguards- OpenAI-compatible server
- Security