AI Engineering
/
Model Serving & Inference
/

Diagnose a slow first token

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.

Easy
Conceptual

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

MetricMeaningCommon trap
Time to first token, TTFTTime until the first generated token reaches the chosen measurement pointMeasuring only GPU execution excludes queueing and network delay
Queue waitTime from arrival at the runtime until the scheduler admits the requestInvisible inside TTFT unless admission is recorded
Prefill timeTime 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 latencyDelay between successive output tokensNetwork chunks may contain multiple tokens
End-to-end latencyTime from request start to terminal resultCounting interrupted responses as completed distorts the result
ThroughputWork completed per unit timeHigh aggregate throughput can coexist with slow individual requests
Error or rejection rateFraction failing or refused due to capacityReporting 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.

EventServer time (ms)
Arrives at the runtime0
Admitted by the scheduler40
Prefill of the 3,000-token prompt ends350
First token written to the stream360
Last of 481 output tokens written12,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

ReuseWhat is reusedKey consideration
Prefix cachingComputation for a matching prompt prefixRequires compatible model and context state; reduces repeated prefill work only
Response cachingA previous final answerNeeds correct keys, freshness rules, and access isolation
Application cachingRetrieval or tool resultsMust 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.

RequestPrompt and loadParts (ms)TTFT (ms)Output rate after the first token (tokens/s)Dominant delayInvestigate first
H1700 prompt tokens, 0 queued at arrivalQueue wait 20, prefill 70, emit 1010040??
H2650 prompt tokens, 14 queued at arrivalQueue wait 2,325, prefill 65, emit 102,40033??
H318,000 prompt tokens (full submission history), 0 queued at arrivalQueue wait 30, prefill 1,860, emit 101,90038??
H46,000 prompt tokens (long failing-test log), 6 queued at arrivalQueue wait 970, prefill 620, emit 101,60035??

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.

MeasureConfig AConfig B
Weights8-bit quantized16-bit (current release)
Maximum sequences per batch6416
Output throughput, all requests2,400 tokens/s1,600 tokens/s
p95 server TTFT2.8 s0.6 s
Requests whose first token missed 1 s21%3%
Requests failed or rejected0.4%0.4%
Quality checks on platform tasksNot run yetPassed (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.

WorkloadWhat it needsChoiceWhyEvidence still needed
Live interview hintsA learner is waiting; the first token should arrive within 1 s???
Overnight draft explanations5,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

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.

Practice the interview question

Answer it in your own words before you look at the reference answer.