Model Serving & Inference · 90 minutes
Diagnose a slow first token
Split a slow first token into queue wait, prefill, and emit from a server trace, and choose a serving configuration per workload instead of by throughput alone.
1.5 h
Overview
Learn what happens after an application sends a request to a model, why responses vary in speed, and which trade-offs matter when choosing a serving approach. You practice by splitting slow first tokens from a fictional coding-practice platform's hint trace into queue wait, prefill, and emit.
Study time: 90 minutes
Interview format: Conceptual screen with a trace-reading exercise
By the end you can
- Distinguish inference from training, and a serving system from a model checkpoint
- Explain prefill and decoding, and split a server TTFT into queue wait, prefill, and emit
- Compare latency with throughput and say where each clock starts and stops
- Explain how KV memory and batching affect queueing and concurrency
- Describe quantization and caching without treating them as guaranteed speedups
- Choose a serving configuration per workload from latency, failure, quality, and cost evidence
Prerequisites
Helpful background: Comfort reading millisecond timings and percentiles helps.
This topic covers runtime scheduling, memory, and hardware. AI Application Integration covers streaming state in the client and server.
Inference and serving
Inference uses a trained model to produce outputs. Serving is the surrounding system that accepts requests, schedules computation, manages memory, streams results, and handles failures. A model checkpoint alone is not a reliable service.
Suppose a coding-practice platform runs an open-weight model on its own serving runtime. One learner asks for a short hint while another asks for a detailed code review. The same model may spend very different amounts of time on these requests because prompt length, output length, queueing, and concurrent demand differ.
Training updates learned parameters. Ordinary inference does not update them. Conversation history is supplied as context; the model does not learn it permanently.
A request lifecycle
The application validates and authorizes a request, prepares the prompt, and submits it to a model service. The service may hold the request in a queue until its scheduler admits it. It then processes the input and produces output tokens, often incrementally.
Record the actual model revision and inference configuration. A display name alone may not uniquely identify the deployed weights, tokenizer, template, or numeric precision.
Application latency includes more than model computation: authentication, retrieval, tools, network transfer, queueing, and client rendering may all contribute. Optimizing model kernels will not fix a slow retrieval query.
Prefill and decoding
For a common autoregressive decoder-only language model, prefill processes the whole prompt in one pass (or in chunks, on runtimes that use chunked prefill), builds the attention state (the KV cache), and yields the first output token. Decoding then generates each further token one step at a time, using the cached state and the tokens generated so far.
Long inputs increase prefill work. Long outputs require more decode steps. The bottleneck varies with architecture, hardware, batch size, and implementation, so avoid assuming that all requests are limited by the same resource.
Streaming makes partial output available earlier. It does not necessarily reduce the time required to finish the response. A broken stream is not proof of successful completion.
Metrics users experience
| Metric | Meaning | Common trap |
|---|---|---|
| Time to first token, TTFT | Time until the first generated token reaches the chosen measurement point | Measuring only GPU execution excludes queueing and network delay |
| Queue wait | Time from arrival at the runtime until the scheduler admits the request | Invisible inside TTFT unless admission is recorded |
| Prefill time | Time to process the prompt, ending when the first token's scores are ready (some runtimes, vLLM among them, end it when the first token is output, so their prefill includes emit) | Invisible inside TTFT unless recorded as its own span |
| Inter-token latency | Delay between successive output tokens | Network chunks may contain multiple tokens |
| End-to-end latency | Time from request start to terminal result | Counting interrupted responses as completed distorts the result |
| Throughput | Work completed per unit time | High aggregate throughput can coexist with slow individual requests |
| Error or rejection rate | Fraction failing or refused due to capacity | Reporting latency only for successful requests hides overload |
State where clocks start and stop. A frontend's first visible text and a server's first generated token are different measurements.
Percentiles describe the distribution: p95 is a threshold at or below which approximately 95% of observations fall, subject to the chosen percentile convention. It is not the average of the slowest 5%.
Worked timeline: one code-review request
Worked example
Suppose the same platform logs one code-review request on the serving runtime's monotonic clock. Times are milliseconds after the request arrived.
| Event | Server time (ms) |
|---|---|
| Arrives at the runtime | 0 |
| Admitted by the scheduler | 40 |
| Prefill of the 3,000-token prompt ends | 350 |
| First token written to the stream | 360 |
| Last of 481 output tokens written | 12,360 |
Split the first-token time into three parts that add up exactly. Emit covers sampling the first token and writing it to the stream.
TTFT = queue wait + prefill + emit
= (40 - 0) + (350 - 40) + (360 - 350)
= 40 + 310 + 10 = 360 ms
Prefill is the largest part (310 of 360 ms, 86%), which fits a 3,000-token prompt on a server with nothing waiting. After the first token, 480 more tokens took 12,000 ms: an average of 25 ms per token, or 40 tokens/s. End-to-end latency at the server is 12,360 ms, so streaming showed text early but did not make the review finish sooner.
The browser measured 450 ms from sending the request to showing the first text. Compare durations, not raw timestamps from two machines: the extra 90 ms is network, gateway, and rendering time that the server trace cannot see.
Batching
Batching processes multiple requests together to use hardware efficiently. Static batching forms a group that is processed as a unit. Continuous batching (iteration-level scheduling) can admit and remove sequences as generation proceeds, depending on the runtime.
Batching can increase throughput but can also introduce waiting or resource contention. Admitting more sequences at once can raise total tokens per second while each decode step takes longer. A batch with long and short outputs presents a scheduling problem. There is no universally optimal batch size.
For interactive hints, protect responsiveness. For overnight content generation, higher throughput may matter more than each request's latency. Separate service objectives help choose a policy.
Model memory
Memory is needed for model weights, attention state, temporary buffers, and runtime overhead. The key-value cache, usually called KV cache, stores attention keys and values so prior context need not be fully recomputed during each decode step.
KV usage generally grows with active sequence lengths and concurrency for ordinary full-attention decoder models. Architecture and cache policy affect the exact relationship. A model that loads successfully can still run out of memory when many long requests arrive.
Many runtimes admit a new sequence only when there is room for its KV cache. When room runs short, new requests wait in the queue, and some runtimes preempt a running sequence and recompute it later, which adds latency. Leave headroom and test representative traffic. Weight size alone is not a serving-capacity estimate.
Quantization
Quantization represents some values with fewer bits, which can reduce storage and memory traffic. Weight quantization and KV-cache quantization are separate choices.
Lower precision can change quality, and acceleration depends on compatible hardware and kernels. A smaller model file does not guarantee faster end-to-end responses. Evaluate exact code correctness, structured output, and long-context behavior after changing precision.
Record the deployed representation as part of the release. A benchmark of the original high-precision model does not establish the quality of a quantized artifact.
Three kinds of reuse
| Reuse | What is reused | Key consideration |
|---|---|---|
| Prefix caching | Computation for a matching prompt prefix | Requires compatible model and context state; reduces repeated prefill work only |
| Response caching | A previous final answer | Needs correct keys, freshness rules, and access isolation |
| Application caching | Retrieval or tool results | Must preserve permissions and data validity |
Prefix caching does not mean the service simply returns an old answer. It reuses compatible internal state (the KV cache) for identical leading prompt tokens. New output generation still has all its decode work to do, and requests that share no prefix gain nothing.
Do not use cross-user caches without an explicit security design. Similar prompts can refer to different private resources or permissions.
Overload, limits, and cancellation
Set input, output, concurrency, and queue limits. Bound waiting with deadlines. When demand exceeds safe capacity, explicit rejection can be better than allowing every request to time out after consuming resources.
Retries can amplify overload; Production & Reliability covers bounded retries. A client cancellation should propagate so the backend can stop unnecessary work, but stopping the browser alone does not prove computation has stopped.
For a hint feature, tell the learner that a hint failed, was rejected, or was interrupted. Do not display partial feedback as a complete assessment.
Trace exercise: four hint requests
Apply the timeline method to four hint requests from the same platform. Every hint prompt starts with the same instructions and problem statement, followed by the learner's code. H3 also carries the learner's full submission history, and H4 a long failing-test log. The product target is a server TTFT of at most 1,000 ms per hint.
Predict the outcome
Find the dominant delay in four hint requests
Use the trace rule: TTFT = queue wait + prefill + emit, all in server-side milliseconds on one clock, against the 1,000 ms hint target. For each request, name the dominant delay with its share of TTFT and what you would investigate first, before you reveal the answers.
| Request | Prompt and load | Parts (ms) | TTFT (ms) | Output rate after the first token (tokens/s) | Dominant delay | Investigate first |
|---|---|---|---|---|---|---|
| H1 | 700 prompt tokens, 0 queued at arrival | Queue wait 20, prefill 70, emit 10 | 100 | 40 | ? | ? |
| H2 | 650 prompt tokens, 14 queued at arrival | Queue wait 2,325, prefill 65, emit 10 | 2,400 | 33 | ? | ? |
| H3 | 18,000 prompt tokens (full submission history), 0 queued at arrival | Queue wait 30, prefill 1,860, emit 10 | 1,900 | 38 | ? | ? |
| H4 | 6,000 prompt tokens (long failing-test log), 6 queued at arrival | Queue wait 970, prefill 620, emit 10 | 1,600 | 35 | ? | ? |
Hosted and self-managed serving
A hosted API delegates much infrastructure work to a provider. Self-managed serving gives more control over deployment and hardware but adds capacity planning, upgrades, monitoring, and incident response.
Compare total lifecycle cost and operational requirements, not only a quoted token rate or GPU price. Consider supported models, required quality, data handling, traffic variability, team skills, and reliability targets. A smaller fallback model should not silently violate the product's required behavior.
Exercise: choose a configuration per workload
The platform tests two configurations of the same model revision on the same hardware and the same mixed workload. All figures are synthetic.
| Measure | Config A | Config B |
|---|---|---|
| Weights | 8-bit quantized | 16-bit (current release) |
| Maximum sequences per batch | 64 | 16 |
| Output throughput, all requests | 2,400 tokens/s | 1,600 tokens/s |
| p95 server TTFT | 2.8 s | 0.6 s |
| Requests whose first token missed 1 s | 21% | 3% |
| Requests failed or rejected | 0.4% | 0.4% |
| Quality checks on platform tasks | Not run yet | Passed (current release) |
Predict the outcome
Choose a configuration per workload
Using the measurements for configurations A and B, choose a configuration for each workload, show the arithmetic that matters, and name the extra evidence you would need, before you reveal the answers.
| Workload | What it needs | Choice | Why | Evidence still needed |
|---|---|---|---|---|
| Live interview hints | A learner is waiting; the first token should arrive within 1 s | ? | ? | ? |
| Overnight draft explanations | 5,000 drafts of about 800 output tokens each, reviewed by editors, finished within a 6-hour window | ? | ? | ? |
Completion checklist
- Split a server TTFT into queue wait, prefill, and emit from a trace.
- Say where each latency clock starts and stops, and why browser and server first-token times differ.
- Explain why a steady output rate says nothing about the wait before the first token.
- Name one memory reason requests queue while the model is loaded.
- Choose a configuration per workload without declaring a winner from throughput alone.
Sources
- DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving Describes the prefill and decoding phases and ties time to first token (TTFT) to prefill and time per output token to decoding.
- vLLM metrics design Example of a runtime that reports queue time, prefill time, decode time, TTFT, and KV cache usage as separate metrics.
- Efficient Memory Management for Large Language Model Serving with PagedAttention Explains that per-request KV cache memory is large and grows and shrinks dynamically, which limits how many requests can be batched.
- vLLM optimization and tuning Describes preempting and later recomputing requests when KV cache space is insufficient, and the latency cost of doing so.
- Orca: A Distributed Serving System for Transformer-Based Generative Models Introduces iteration-level scheduling, the idea behind continuous batching.
- vLLM automatic prefix caching Shows that reusing the KV cache of a shared prefix shortens prefill but not decoding, and gives no gain when prompts share no prefix.
The platform, trace, configurations, figures, targets, and rubric are original synthetic teaching material about a fictional coding-practice platform. No hardware benchmark was run, and the timings are not performance claims about any model, runtime, or GPU. Study times and readiness thresholds are editorial estimates. Product and library details are as of November 2026.
Related on CodeSnatch
Lessons, problems, and articles that build the skills this question uses.
AI Engineering
Ties prompt length to time to first token and prices prefix caching, the prefill side of a slow start.
System Design
Separates utilization from saturation, such as queue depth and wait time, and reads latency by percentile.
Community article
Explains traces as trees of timed spans, the habit of finding which stage a slow request spent its time in.
AI Engineering
Covers deadlines, capped backoff, and admission limits, so retries do not pile more work onto a full queue.
Practice the interview question
Answer it in your own words before you look at the reference answer.
