Learning objectives
By the end of this module, you should be able to:
- Explain the role of an inference server independently of the model itself.
- Describe request schema, model selection, synchronous responses and streaming responses.
- Differentiate time to first token from total response time at a conceptual level.
- Use status codes, timeouts and cancellation as part of an operational API contract.
🎓 Learning Coach follows this block when it is centered in your browser
The inference server turns an API request into model execution
The inference server sits between clients and the model runtime. It accepts requests, validates parameters, prepares inputs, schedules work, invokes the model and formats results back into the API contract.
This layer is where production systems can add batching, concurrency controls, request cancellation, metrics and hardware-aware scheduling.
- Accept and validate requests.
- Prepare/tokenize input as required by the model/runtime.
- Queue and schedule execution.
- Run inference on CPU/GPU resources.
- Return or stream structured output.
Common beginner misconceptionThe model file itself is not an HTTP server. A serving/runtime layer exposes it to applications.
🎓 Learning Coach follows this block when it is centered in your browser
Synchronous and streaming responses feel very different
With a non-streaming response, the client waits until generation is complete and receives the finished payload. With streaming, the server sends incremental pieces as they become available, allowing the user to start reading earlier.
Streaming improves perceived responsiveness but introduces client complexity: partial output, disconnects, cancellation and end-of-stream handling all matter.
- Non-streaming: simpler client, whole result arrives later.
- Streaming: first output arrives sooner, client handles incremental events.
- A broken stream can leave partial output that must not be mistaken for a completed transaction.
- Cancellation should stop unnecessary generation where supported.
Common beginner misconceptionThe important thing is to understand the boundary and evidence before memorizing implementation details.
🎓 Learning Coach follows this block when it is centered in your browser
Time to first token and total latency answer different questions
Time to first token (TTFT) measures how long the user waits before generation becomes visible. Total latency measures until the response finishes. Token generation rate describes how quickly output proceeds after generation begins.
A service can have slow TTFT but normal generation speed when the queue is overloaded. That is why one latency number is often not enough.
- TTFT: request accepted → first generated output becomes visible.
- Generation duration: first output → final output.
- Total latency: request start → completion.
- Queue time can dominate TTFT under saturation.
Common beginner misconceptionHigh total latency does not prove the model itself is generating slowly.
🎓 Learning Coach follows this block when it is centered in your browser
A production API contract includes failure and cancellation behavior
An API is not complete when only the happy-path JSON is documented. Clients need to know how long to wait, how failures are represented, whether requests can be cancelled, how authentication works and which retry behavior is safe.
Retries require care because some operations are expensive and user cancellations should not become invisible orphaned generation.
- Explicit client and server deadlines.
- Machine-readable error classes/status codes.
- Cancellation/disconnect behavior.
- Authentication and authorization expectations.
- Request limits for prompt size, output length and concurrency.
Common beginner misconceptionThe important thing is to understand the boundary and evidence before memorizing implementation details.
Worked examples
Non-streaming versus streaming
NON-STREAMING
request ───────────────► complete JSON
user waits
STREAMING
request ──► chunk ─► chunk ─► chunk ─► done
user can start reading
- Streaming changes perceived responsiveness and client behavior.
- The client still needs an explicit completion signal.
Latency decomposition
queue/prefill 2.8 s
first token ← TTFT ~2.8 s
generation 1.5 s
-----------------------
total 4.3 s
- A high TTFT can dominate the experience before token generation starts.
- Later modules will connect this to batching, concurrency and GPU capacity.
Try it · core lab · account-free
Run and measure a tiny streaming inference API
Goal: See request validation, queue delay, first output and streamed completion using only Python's standard library.
Before you start
- Python 3 only. The service generates deterministic teaching tokens; no model download or API key is required.
STEP 1Run the automated self-test
python3 public/labs/llmops/04_inference_api_streaming.py --self-test
STEP 2Start the teaching server
python3 public/labs/llmops/04_inference_api_streaming.py --serve
STEP 3Request a stream
curl -N -s http://127.0.0.1:18081/v1/stream -H 'Content-Type: application/json' -d '{"prompt":"explain batching","queue_ms":700}'
STEP 4Increase queue delay and compare
Repeat with queue_ms=2500. Observe that the first chunk arrives later even though the chunk-to-chunk interval is unchanged.
Verify
- The self-test prints TTFT and total duration separately.
- Increasing queue_ms increases TTFT.
- The stream contains an explicit done event.
- Invalid JSON or an empty prompt returns a client error instead of pretending inference succeeded.
Expected outcome
- You can explain why queue delay and generation speed are separate.
- You understand streaming as a sequence of protocol events, not magic typing animation.
Break / fix · diagnose
- If curl buffers output, keep -N/--no-buffer so chunks are displayed as they arrive.
- If port 18081 is occupied, stop the teaching server cleanly and investigate the listener before changing code.
- If TTFT and total look identical, verify that the client is reading incrementally rather than buffering the whole response.
Production viewLater, the same metrics help distinguish queue saturation, slow prefill and slow token generation on real inference servers such as vLLM.
Avoid these traps
Common mistakes
- Calling a model file an inference server.
- Assuming streaming reduces the total amount of compute required.
- Measuring only total latency and losing the distinction between queueing and generation.
- Retrying every failed request without considering overload, policy errors or cancellation.
Knowledge check
Reason about the system, not just the vocabulary.
Answer before opening each explanation. Opening all four answers records knowledge-check activity in My Learning.
1What is the inference server responsible for?
Accepting/validating requests, preparing and scheduling inference work, running the model through its runtime and returning structured output.
2What does streaming improve most directly for the user?
Perceived responsiveness because output can be consumed before the entire response is finished.
3TTFT rises sharply while generation rate remains stable. What does that suggest?
Delay before generation—often queueing/capacity or prefill—not necessarily slower token decoding.
4Why should cancellation be part of an inference API contract?
Generation is expensive; when a client no longer needs the response, cancellation can prevent unnecessary compute and reduce orphaned work.