Unit 1 of 12 · about 4 hours · explain, implement
Typed OpenAI-compatible schemas, token streaming and backpressure
The API schema and its stream are the product the learner operates. Every SLO, bill and debug session starts at the request fields and the event stream, not inside the model.
You'll be able to
- Send a typed chat-completions request to a local engine and parse its SSE stream down to the
[DONE]terminator. - Explain where backpressure sits when a client reads slower than decode produces, using per-request queues and
stream_interval. - Constrain one endpoint with a JSON-schema structured output and state when a schema change defeats the grammar cache.
Covers
Read
In this order, only the parts listed
0 of 4 done
- vLLM OpenAI-Compatible ServervLLM Online Serving, Architecture and Production Metrics
Supported APIs through Extra HTTP Headers: endpoint table,
vllm servewith--api-key token-abc123,extra_bodywithtop_k,--enable-request-id-headerswithx-request-id, andX-Vllm-Priority - Streaming with batching from scratchHands-On LLM Serving and Optimization - Chapters 3 and 4, serving system design
Chapter 3, Streaming with Batching (printed pp. 77-82): Table 3-1 batch evolution T0-T3,
/generate_streamwithmedia_type="text/event-stream", per-promptasyncio.Queueand theNonefinish signal - vLLM structured outputsvLLM Online Serving, Architecture and Production Metrics
Online Serving section:
choice,regex,jsonandgrammarexamples throughextra_body, the--structured-outputs-config.backendflag, and the deprecatedguided_jsonmapping box - OpenAI chat streaming contractOpenAI API Reference - streaming, auth, rate limits and request IDs
Create chat completion: the
streamandstream_options.include_usageparameters (the usage chunk arrives beforedata: [DONE]) and the streaming example ending indata: [DONE]; the linked Streaming events page for thechat.completion.chunkfieldsdeltaandfinish_reason(page read 2026-10-14)Read only the streaming contract. vLLM on your GPU is the implementation under test, not the hosted service.
Focus on
- The typed contract is
model,messages, sampling fields such astemperature,top_kandseed, plus vLLM extras (structured_outputs,request_id,session_id,cache_salt,priority) passed throughextra_body.suffixis unsupported anduseris ignored. - Each SSE chunk is one
dataline carrying a JSONdeltaobject; the stream ends with a bare[DONE]data line, not with connection close. With output tokens andstream_interval, expect an initial role-only chunk, then about token-bearing chunks plus[DONE], since the first and last tokens are always sent immediately. - Backpressure lives in per-request queues between the decode loop and the HTTP connection. A slow reader grows queueing and connection time; it does not pause generation or reduce billed tokens.
- A structured-output grammar is compiled per distinct schema and reused on repeat. Rotating schemas per request turns every call into a cold compile; keep a small fixed schema set.
Common mistakes · 3
temperature=0does not silence reasoning models. A local Qwen3-0.6B withtemperature=0andseed=1still opens with<think>; temperature controls sampling, not the thinking trace.- The server takes default sampling values from the model's
generation_config.jsonin its Hugging Face repository. Fields your request sets still win; omitted ones inherit the model creator's values. Pass--generation-config vllmto fall back to vLLM's own defaults. guided_json,guided_regex,guided_choiceandguided_grammarwere removed in v0.12.0. In v0.31.0 they do not fail: the server ignores them, returns HTTP 200 with unconstrained output and logs a one-time warning. Usestructured_outputswithjson,regex,choiceorgrammar.
Try it yourself
Closed-book, before checking anything
stream=True and max_tokens=8. Save the raw bytes, list every data line, point at the [DONE] terminator, and reassemble the assistant text from the delta fields only.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Which endpoints does vLLM's
--api-keyprotect?AnswerOnly paths under
/v1,/v2and/inferenceas documented (the v0.31.0 source also guards/cohere)./health,/metricsand/invocationsstay unauthenticated, so put the server behind a reverse proxy that enforces auth.2.How does a client know a stream is finished?Answer
It receives a bare
data: [DONE]line. Connection close alone is ambiguous: it can also mean a dropped connection mid-generation.3.With 8 output tokens and
stream_interval=3, about how many data chunks arrive?AnswerAbout token-bearing chunks (tokens 1, 2 to 4, 5 to 7, then 8) after the role-only chunk, then
[DONE]. The first token and the final chunk go out immediately; the middle ones wait for three new tokens.4.Why does minting a fresh JSON schema per request hurt structured-output latency?Answer
The grammar backend compiles each distinct schema, so a fresh schema misses the compiled-grammar cache on every call. A small fixed schema set reuses compiled grammars.
Practice
- llm-model-inference ch03: streaming API tests
test_generate_streamandtest_generate_stream_concurrentagainst/generate_stream;test_stream.shfor the live-server variantRun with a tiny CPU model. Assert close-terminated JSON
datalines and concurrent-stream isolation on/generate_stream, which sends no[DONE]line. Then assert the[DONE]terminator on a local vLLM stream of/v1/chat/completions.
You're done when
Your saved stream parses to [DONE], the deltas reassemble to the full text, and you can name which sampling knobs came from the model repository and which from your request.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- vLLM Online Serving, Architecture and Production MetricsvLLM Project · primary
Trace the API server, engine core, scheduler, KV manager and model runner, then map documented metrics to your SLIs. The link is pinned to v0.31.0; add the auth, tenant, quality and rollout controls the engine leaves to you.
- Hands-On LLM Serving and Optimization - Chapters 3 and 4, serving system designChi Wang and Peiheng Hu (O'Reilly) · required
Read Chapter 3 (an online service from scratch, batching with streaming, multi-model trade-offs) and the enterprise-architecture part of Chapter 4. Convert the designs into explicit request, model-lifecycle and failure state machines.
- OpenAI API Reference - streaming, auth, rate limits and request IDsOpenAI · reference
Read the chat streaming event shape with the
[DONE]terminator, bearer auth, rate-limit headers, andx-request-idwith caller-suppliedX-Client-Request-Id. vLLM is the implementation under test; use this only for the contract it claims compatibility with.
Also in this section
- vLLM Production MetricsvLLM Project · required
Define every selected queue, cache, phase and request metric, check histogram buckets and measure exporter overhead. Add model version, cancellation, rejection, quality sample and tenant-safe trace fields in the surrounding service.
- Machine Learning Systems, Volume 2 - Inference at Scale and Serving Fault ToleranceHarvard (Vijay Janapa Reddi) · required
Read "Load Balancing and Request Routing", "Multi-Tenancy and Isolation" and "Autoscaling and Global Infrastructure" in Inference at Scale, then "Serving Fault Tolerance" and "Graceful Degradation" in the Fault Tolerance chapter.
- Inference Engineering - Chapter 7, ProductionPhilip Kiely (Baseten Books) · support
Read Chapter 7 for containers, autoscaling, cold starts, routing and queueing, zero-downtime deployment, cost estimation and client-side streaming. Skip the vendor section at its end.
- Gateway API Inference ExtensionKubernetes SIG Network · required
Study model-aware routing, endpoint selection and operational integration. Use it for architecture and an optional local deployment only after the service passes lifecycle and failure tests without Kubernetes.
- SGLang documentation - Production MetricsSGLang Project · support
Compare its metric names and phase boundaries with vLLM's, so your dashboards do not depend on one engine's vocabulary.
- AI Systems Performance Engineering - Production Inference LabsChris Fregly · required
Use Chapter 16 monitoring, cache health, capacity planning and load-test utilities, then Chapter 17 routing only if distributed. Add process death, overload and bad-version cases that the performance pairs do not cover.
- 100 Days of LLM Inference - Days 22 to 26Elizabeth Thomas · support
Use the container, autoscaling, routing, capacity and zero-downtime notebooks as small operational simulations. Replace calendar order and fixed scale targets with the stage checkpoint and your hardware limits.
- AI Infrastructure Engineer Learning - Project 103 LLM DeploymentAI Infra Curriculum · support
Use its Docker, API, monitoring, Kubernetes and cost files as scaffolding only. Check its resource assumptions against your own model and GPU, and rerun any benchmark before reusing a result.
- LLM Inference Systems Laboratory - Operations and FailureRoadmap-Final · support
Complete production gateway, isolation, telemetry, canary, drain, rollback and fault campaigns. Store first-cause timelines and revise runbooks from observed blind spots.
- vLLM Multimodal Inputs - media validation, fetch policy and cache identityvLLM Project · reference
Read Online Serving for image, video and audio inputs:
--allowed-media-domains, fetch timeouts,--limit-mm-per-prompt, local-media path restriction, and media UUIDs for cache identity. The link is pinned to v0.31.0.