Before you start: words you need#
| Word | Plain meaning |
|---|---|
| API | The agreed shape of requests and responses between a client and your service: which URLs, which fields, which errors. |
| Schema | The exact list of fields a request or response may contain, and their types. |
| OpenAI-compatible | Uses the same URLs and JSON fields as OpenAI’s API, so any client written for OpenAI works unchanged. |
| SSE | Server-sent events: a plain HTTP response that stays open while the server writes data: … lines, one per event. How tokens are streamed (12.p). |
| gRPC | A remote-call protocol on HTTP/2 with binary (protobuf) messages. Common between internal services. |
| Stateless / stateful | A stateless API needs the whole conversation in every request. A stateful one keeps the conversation on the server and lets the client refer to it by an id. |
| Liveness / readiness | Two health questions Kubernetes asks: “is the process alive?” (restart it if not) and “should it receive traffic?” (stop sending if not). |
| Idempotent | Safe to send twice: the second copy has no extra effect. Most generation requests are not. |
1. What is it?#
The API is the contract between clients and your inference service: the protocol, the request and response schema, how tokens are streamed, which errors exist, and which limits apply.
For LLMs the industry has converged on the OpenAI-compatible API. In November 2026 that means three shapes, all served by the main open engines (vLLM, SGLang):
| API | Path | Style | Status |
|---|---|---|---|
| Chat Completions | /v1/chat/completions | Stateless: send the whole conversation every time | Still supported by OpenAI; still the most widely implemented |
| Responses | /v1/responses | Typed input and output items, typed stream events, optional server-side state | OpenAI’s recommended API for new projects; published as the vendor-neutral Open Responses specification in January 2026 |
| Messages (Anthropic) | /v1/messages | Anthropic’s shape, which many coding tools speak | vLLM serves it from the same engine (16.b) |
OpenAI shut down its older Assistants API on 26 August 2026 and points users to Responses. Chat Completions was not retired.
Facts checked on 12 November 2026.
2. Why does it matter?#
If your API is OpenAI-compatible:
- it works with the
openaiSDKs, LangChain, LlamaIndex, agent frameworks and every evaluation harness; - clients switch provider by changing one
base_url; - your users already know the fields.
If it is not, every integration is custom work, you maintain your own client libraries, and evaluation tools do not run against you.
Implement the standard schema, and add extensions on top. Compatibility costs about a day; incompatibility costs you for as long as the service exists.
The API is also your first capacity control. Every field a client sets (max_tokens, n,
prompt length) decides how much GPU time and KV cache memory the request can take. The edge is
where you limit that.
3. Simple analogy#
Electrical sockets. A better plug design is worthless if no appliance fits it. The standard socket is worth more than the improvement. You can still add a USB port beside it: that is an extension.
4. Tiny example: one streamed chat request#
Request:
{
"model": "qwen3-32b",
"messages": [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Explain gravity"}
],
"max_tokens": 500,
"temperature": 0.7,
"stream": true,
"stream_options": {"include_usage": true}
}The response is an SSE stream of chunks (lesson 12.p explains the framing):
data: {"id":"chatcmpl-1","object":"chat.completion.chunk","model":"qwen3-32b",
"choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"id":"chatcmpl-1",...,"choices":[{"index":0,"delta":{"content":"Gravity"},"finish_reason":null}]}
data: {"id":"chatcmpl-1",...,"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"id":"chatcmpl-1",...,"choices":[],
"usage":{"prompt_tokens":12,"completion_tokens":143,"total_tokens":155}}
data: [DONE]stream_options.include_usage asks for one extra chunk with token counts. Clients need it for
cost tracking; without it a streaming client never learns how many tokens it paid for.
The same request through the Responses API sends input instead of messages, and the
stream is a sequence of named events (response.created, response.output_text.delta, …,
response.completed) rather than one generic chunk shape. Reasoning text and tool calls get
their own event types, which is why agent frameworks prefer it (12.p, 18.i).
5. Technical explanation#
The endpoints#
POST /v1/chat/completions the main one
POST /v1/responses Responses API (GET /v1/responses/{id} to fetch a stored one)
POST /v1/completions legacy: raw text in, text out, no chat template
POST /v1/embeddings if you serve embedding models
GET /v1/models model discovery (LoRA adapters appear here too, 18.g)
GET /health liveness
GET /metrics Prometheus (19.c)
POST /tokenize, /detokenize useful extensionsStateless or stateful: the serving cost of the Responses API#
Chat Completions is stateless: turn 20 of a conversation resends turns 1–19. That is wasteful on the network but simple to serve: any replica can take any request.
The Responses API can be stateful. With store: true (OpenAI’s default) the server keeps each
response, and the next request can say previous_response_id: "resp_…" instead of resending
the history. That moves work onto the server:
- Storage. Someone must keep every stored response, with a retention period and deletion. That is a database, not part of the engine.
- Routing. The replica that holds the conversation’s KV cache is the cheapest place to run the next turn, so session affinity matters more (20.f, 21.h).
- Privacy. Stored conversations are user data, with all the obligations that brings.
Many self-hosted deployments run the Responses API statelessly (store: false, history in
every request) and keep state in the application. Open-source routers are adding the stateful
part: llm-d 1.0 (October 2026) supports previous_response_id, and KServe 0.18 added Responses
API routing. Check what your engine and router actually store before you rely on it.
Protocol choice#
HTTP/1.1 + SSE HTTP/2 gRPC
Public API ✓ THE STANDARD fine needs grpc-web for browsers
Internal service fine ✓ ✓ best
Requests per conn one at a time many many
Framing per token ~80 bytes of text smaller ~10 bytes protobuf
Browser support native native no
Proxy friendly ✓ (it is just HTTP) mostly often not
Bidirectional no no (in practice) ✓Practical answer: SSE over HTTP for the public API; HTTP or gRPC between gateway and engines. SSE framing costs about 80 bytes per token, which is nothing (5,000 tokens/s × 80 B = 400 KB/s), and its compatibility is worth everything.
Internal gRPC is spreading for a second reason: a router written in Rust or Go can tokenize the prompt itself and send token ids to the engine over gRPC, taking that CPU work out of the engine’s Python process. vLLM gained a gRPC server entrypoint in 2026 for this use with the SGLang Model Gateway, and SGLang workers have a gRPC mode. Treat these as young.
WebSocket appears for realtime audio (vLLM serves /v1/realtime for speech models) because
audio flows both ways at once.
Validation: what to enforce at the edge#
max input tokens protects prefill time and activation memory
max output tokens protects KV cache and how long a slot is held
prompt + max_tokens must be ≤ the context length the server was started with
temperature ∈ [0, 2], top_p ∈ (0, 1], top_k ≥ 1 or absent
n (completions) ≤ small n=100 multiplies the cost by 100
stop sequences ≤ 4, each ≤ 64 characters
messages count and total size
images / audio count, pixel size, durationEach of these is a capacity control, not only hygiene. A client sending
max_tokens: 100000, n: 20 can occupy a large share of a fleet. Reject with a clear 400 that
names the limit and the value you saw.
Errors#
400 invalid request (bad parameter, prompt too long)
401 not authenticated
403 not allowed to use this model
404 unknown model
408 request timeout
413 payload too large
422 semantically invalid (vLLM uses 400 for most validation; be consistent)
429 rate limited: THIS CLIENT is over its quota ← include Retry-After
499 client closed request (an nginx convention, useful in logs only)
500 internal error
503 overloaded: THE SERVICE has no capacity ← include Retry-After
504 upstream timeout429 and 503 mean different things. 429 says “you are over your quota”; 503 says “we are over
capacity”. Clients should back off differently (20.e). Retry-After is a standard HTTP header
(RFC 9110) that tells the client how many seconds to wait.
Once streaming has started the status code has already been sent as 200, so a later error must travel inside the stream (12.p):
data: {"error":{"message":"engine restarted","type":"server_error","code":"engine_crash"}}
data: [DONE]Extensions worth having#
Beyond the standard schema, engines accept extra fields. vLLM’s include:
"priority": int scheduling priority; lower runs first, and the server must be
started with --scheduling-policy priority (17.c, 20.k)
"min_tokens": int force a minimum length
"ignore_eos": bool keep generating past the end token (benchmarks)
"top_k", "min_p",
"repetition_penalty" sampling controls missing from OpenAI's schema (12.o)
"structured_outputs": {...} JSON schema, regex, choice or grammar (18.e);
the standard "response_format" field maps onto itSelecting a LoRA adapter needs no extension: the adapter’s name goes in the model field (18.g).
Document extensions clearly, so clients know which fields are portable across providers.
Health checks: two different questions#
LIVENESS "Is the process alive?" Fails → Kubernetes RESTARTS the pod.
READINESS "Should it get traffic?" Fails → the pod is taken out of the load balancer.
STARTUP "Has it finished starting?" Holds the other two off until it passes.vLLM does not open its port until weights are loaded, memory is profiled and graphs are
captured, so its /health answers “alive” and “ready” at once; it fails if the engine core
dies. A server that warms up after opening its port (20.h) needs a separate readiness signal.
Conflating them is a common and damaging mistake. If liveness starts failing during a 5-minute model load, Kubernetes kills the pod and it never finishes starting. Use a startup probe with a generous limit (19.e has a worked set of probes).
Health checks must be cheap. Never run a real generation on every probe. At a 5-second interval across 100 replicas that is 20 generations per second spent on checks.
6. Under the hood#
Where the API layer spends CPU for one request (rough figures for a Python server):
TLS + HTTP parse 50–200 µs
JSON decode 20–500 µs grows with message size
Validation 5–20 µs
Chat template 10–100 µs
Tokenization 50 µs – 5 ms grows with prompt length
Per token: detokenize + JSON + SSE write 20–100 µsThe last line repeats for every token of every stream. At 5,000 output tokens per second
across all streams it costs 0.1–0.5 of a CPU core. Fast JSON libraries (orjson, msgspec)
and sending a few tokens per event cut it.
Lesson 16.e follows a request through vLLM’s frontend, from JSON to token ids.
7. Performance implications#
- The API layer is rarely the bottleneck, until it is. At a few hundred tokens per second it is noise. At tens of thousands of streamed tokens per second on one node, per-token encoding and socket writes can saturate the single Python process in front of the engine; the GPU then waits for the CPU.
- Scale the front end separately. vLLM can run several API-server processes in front of one
engine (
--api-server-count); other stacks put a Rust or Go router in front that tokenizes. - Tokenization sits on the path to the first token. A 100,000-token prompt takes milliseconds to tokenize; count it in time to first token (2.c).
- Streaming granularity trades smoothness for CPU. One event per token is the most
responsive and the most expensive. vLLM’s
--stream-interval Nsends every N tokens (16.f). - Stateless chat resends history. Turn 20 of a long chat may upload 50,000 tokens of JSON. The prefix cache saves the GPU work (12.m), but the bytes, parsing and tokenization are paid every time.
8. Production implications#
- Be OpenAI-compatible. Test with the real
openaiclient library in CI, for Chat Completions and for Responses if you offer it. - Decide where conversation state lives before offering stateful Responses: who stores it, for how long, and how deletion works.
- Enforce every limit at the edge, with clear errors.
- Separate liveness, readiness and startup probes.
- Return
usagein the final streaming chunk. - Include
Retry-Afteron 429 and 503. - Log the request shape (input tokens,
max_tokens, model, tenant) for every request. It is the basis of all capacity analysis (23.b). - Version your API (
/v1/) and do not break it.
9. Common mistakes#
- Inventing your own schema. You lose the whole ecosystem.
- Conflating liveness and readiness. Restart loops during model load.
- Expensive health checks that run a generation.
- No limits on
normax_tokens. One client can consume the fleet. - Returning 500 for overload instead of 503. Clients retry at once and make it worse.
- No in-band error format for failures after streaming has started.
- Offering stateful Responses without a storage plan. Conversations pile up with no retention or deletion.
- Slow JSON handling on large messages, blocking the event loop.
10. Hands-on exercise#
A. Build an OpenAI-compatible endpoint. Implement /v1/chat/completions with streaming and
non-streaming modes. Test it with the real openai Python client: that is the compatibility
test that matters.
B. Compare the two shapes. Start vLLM and send the same prompt to /v1/chat/completions and
/v1/responses with streaming on. Print every event type you receive. Which carries the
reasoning text? Which carries usage?
C. Validation suite. Write tests for every limit in section 5. Check that each returns a clear 400 naming the limit.
D. Probe design. Implement liveness, readiness and startup probes. Simulate a 5-minute model load and check that Kubernetes-style probing does not kill the pod.
E. Measure the API cost. Profile the API layer at 500 requests/s with 2,000-token prompts. How many cores does it need? What is the biggest cost: parsing, tokenizing or streaming?
F. Error semantics. Implement 429 and 503 with Retry-After. Write a client that backs off
correctly for each, and check the behaviour differs.
11. Interview questions#
- Why implement the OpenAI-compatible API rather than your own?
- What changes for the server when clients use
previous_response_idinstead of resending history? - When would you use gRPC instead of HTTP with SSE?
- What is the difference between liveness and readiness, and what breaks if you conflate them?
- Which request parameters would you validate at the edge, and why is each a capacity control?
- How do you report an error after streaming has started?
- What is the difference between 429 and 503, and how should a client treat each?
- What per-request information would you log, and what would you use it for?
12. Further reading#
Checked on 12 November 2026.
- [REFERENCE] OpenAI: migrate to the Responses API — Chat Completions remains supported; Responses recommended for new projects;
storeandprevious_response_id. - [REFERENCE] Open Responses specification — the vendor-neutral version of the Responses API.
- [REFERENCE] OpenAI deprecations — Assistants API sunset, 26 August 2026.
- [REFERENCE] vLLM online serving: supported APIs
- [REFERENCE] Kubernetes liveness, readiness and startup probes
- [REFERENCE] RFC 9110, the
Retry-Afterheader - [FUNDAMENTAL] Google SRE Book: Handling Overload