Chapter 18
Request Lifecycle, Metrics, and Workload Models
On this page
An LLM request is a long-lived operation whose state spans several components. Once a token reaches the user, it cannot be rolled back like an uncommitted database write. Measure queueing, model work, and delivery separately to locate delays and define safe retries.
The map starts here because every optimization in this part is judged against these measurements. For the running service the contract is concrete: p99 time to first token is at most 1.5 seconds, and p99 visible inter-token gap is at most 100 milliseconds. These percentile targets allow a tail beyond the thresholds; a hard maximum-gap guarantee would be a stronger contract.
Client-observed time to first token ends at receipt, not at the first GPU result. Inter-token gaps are measured between successive receipts. The processing path is schematic; decode and delivery repeat after the first token, and cleanup follows completion or cancellation.
The request path¶
A production request usually crosses these stages:
- authenticate, rate-limit, and validate the request;
- normalize the prompt, apply the chat template, and tokenize;
- route by model, adapter, tenant, locality, and capacity;
- wait in an admission or execution queue;
- allocate or reuse KV state and run prefill;
- sample and stream the first token;
- repeat scheduling, decode, postprocessing, and streaming;
- stop on an end token, length limit, constraint, cancellation, or error;
- release pages, adapter references, graph slots, and accounting state.
Each boundary needs an owner and a timestamp. Without this, a regression in tokenization, routing, queueing, networking, or client backpressure may be misdiagnosed as a slow GPU.
The request contract includes more than input text. It includes model and tokenizer versions, chat template, adapter, maximum context and output, stop rules, logits processors, random seed, sampling parameters, structured-output grammar, priority, deadline, streaming mode, and any approximation policy. These fields affect both semantics and execution shape.
Latency definitions¶
Let a be arrival at the service boundary, s the first model-service start, f the first token visible at that boundary, and o_i the visible time of output token i.
| Metric | Definition | What it reveals |
|---|---|---|
| Pre-model delay | s - a |
Preprocessing, routing, admission, and waiting before model execution |
| Time to first token | f - a |
Queueing, preprocessing, prefill, first sampling, and transport |
| Inter-token latency | o_i - o_(i-1) |
Per-step cadence and stalls |
| Time per output token | Usually (o_last - f) / (N - 1) |
Average generation speed after the first token |
| End-to-end latency | o_last - a |
Total user wait for a completed response |
Measure queue delay from explicit queue-entry and queue-exit spans; s-a also includes preprocessing and routing. Time per output token is defined only for N>1 and is an average: it can hide a one-second generation stall among many fast tokens. Report an inter-token latency distribution or a maximum-gap metric for interactive products. Distinguish final-token latency from terminal-response latency if cleanup or a final event follows. Also define whether the first token means sampled on the GPU, serialized by the server, received by the gateway, or observed by the client. A metric without a boundary is ambiguous.
For non-streaming clients, end-to-end latency matters most, but internal first-token and cadence metrics still locate faults. For streaming clients, a reasonable SLO often has separate thresholds for time to first token and inter-token latency.
Decompose the running service's budget before optimizing anything. An illustrative allocation might assign tens of milliseconds to transport and tokenization and tens to low hundreds to a 2,000-token prefill, leaving substantial allowance for queueing and scheduling. Those times are hypotheses to measure, not benchmark results. Component p99 values do not generally add to end-to-end p99, so validate the joint request trace. That measurement determines how much effort belongs in admission, batching, cache reuse, or prefill kernels.
Throughput, goodput, and capacity¶
Report input tokens per second and output tokens per second separately. They exercise different phases and cannot be added without context. Requests per second is meaningful only with a declared prompt/output distribution. Per-GPU token throughput is useful for efficiency, while per-user output rate describes interactivity.
Goodput is work that satisfies the product contract. One useful definition is:
goodput = requests meeting declared per-request acceptance limits / measurement interval
A request that eventually completes but violates its time-to-first-token or token-cadence requirement consumes capacity without contributing to goodput. This makes goodput a better autoscaling and architecture objective than raw throughput under strict latency objectives.
A percentile SLO belongs to a population and interval, not to one request. Define the request-level limits used for goodput separately. For cadence, state whether the population contains all token gaps, one summary per request, or one summary per session. Pooling gaps weights long answers more heavily. A p99 over all gaps below 100 ms does not mean 99 percent of requests avoid a gap above 100 ms: even under independent one-percent per-gap violations, a 300-token answer has about 1-0.99^299 = 95 percent probability of at least one violation. Real gaps are correlated, so measure the request/session experience directly rather than using that toy calculation as a predictor.
Capacity is not the peak point on a throughput curve. It is the highest sustained arrival process for which tail latency, error rate, memory reserve, quality, and fairness remain within contract. State the percentile and duration: for example, 99th-percentile first-token latency under a thirty-minute replay with a specified burst model.
Open-loop and closed-loop load¶
In a closed-loop test, each simulated client waits for completion before sending another request. When the service slows, offered load falls. This is useful for user-session modeling but can hide overload.
In an open-loop test, arrivals follow a process independent of completions. Queueing is visible because offered load does not retreat when latency rises. Use open-loop tests to find sustainable capacity, but choose realistic burstiness rather than only a smooth Poisson stream.
Avoid coordinated omission: a load generator that pauses arrivals while the server is slow fails to count requests that would have arrived during the stall. Record intended arrival time separately from actual send time, and include client-side queue delay if the generator cannot keep up.
A workload is a joint distribution¶
Average prompt length and average output length are insufficient. The service cost depends on their joint distribution and correlations with:
- arrival time and burst size;
- model, adapter, and tenant;
- sampling or structured-output policy;
- prefix-reuse probability and shared-prefix length;
- cancellation point and client backpressure;
- speculative acceptance;
- multimodal input size;
- priority and deadline.
Long prompts and long outputs create different pressure. A long prompt is a large prefill event; a long output holds KV memory and a decode slot for many iterations. A few long-tail requests can control memory reserve and tail latency even when token-weighted averages look benign.
Build at least three workload views: a stable production replay, a stress distribution that magnifies tails, and synthetic shape sweeps for causal explanation. Preserve request correlations in replay. Independently sampling each feature can create combinations that never occur or remove the bursts that matter.
Trace decomposition¶
Use a request identifier across gateway, scheduler, worker, and stream transport. A useful span model includes:
gateway -> tokenize -> route -> queue -> prefill -> first sample -> decode iterations -> stream flush -> cleanup
Within the worker, attach phase, batch composition, input/output token counts, allocated and reused KV tokens, model/adapter version, graph or engine variant, device group, and termination reason. Sample detailed traces if volume is high, but retain aggregate histograms for every request class.
Tail diagnosis should compare a slow request with the batch and node state around it. Per-request latency alone cannot reveal that a short decode waited behind a long prefill, a cache eviction triggered recomputation, or a peer stalled a tensor-parallel collective.
Benchmark protocol¶
A defensible benchmark declares:
- exact model, tokenizer, precision, engine, kernels, drivers, and hardware topology;
- prompt/output distributions, sampling policy, and dataset transformations;
- concurrency or arrival process, duration, warmup, and random seeds;
- inclusion boundaries for tokenization, network, queueing, and detokenization;
- cold-start and warm steady-state results;
- latency percentiles, inter-token gaps, throughput, goodput, errors, and memory;
- output correctness or quality checks.
Run both a component benchmark and an end-to-end replay. Component results explain a mechanism; the replay proves that scheduling, transport, memory pressure, and application features do not erase the gain.
Diagnose a misleading load report¶
A report claims 100 ms median TTFT and 90% success from the following one-second replay. The intended arrivals are fixed before execution. All times below use the client monotonic clock, and completion includes receiving the terminal response.
| Request | Intended arrival, ms | Actual dispatch, ms | First token, ms | Completion, ms | Result |
|---|---|---|---|---|---|
| A | 0 | 0 | 100 | 400 | Complete |
| B | 100 | 300 | 400 | 700 | Complete |
| C | 200 | 600 | 700 | 900 | Complete |
| D | 300 | 900 | none | 950 | Rejected |
Calculate intended-arrival TTFT, dispatch-relative TTFT, generator lag and useful completions per measurement interval. Use a 350 ms first-token threshold, a one-second end-to-end threshold, and a fixed [0,1000] ms window. Then decide whether increasing the worker's batch size is justified by this evidence.
Worked diagnosis¶
All three completed requests have dispatch-relative TTFT of 100 ms, which explains the attractive reported median. Their intended-arrival TTFT values are 100, 300 and 500 ms. Dispatch lag is 0, 200, 400 and 600 ms. The load generator is falling behind; subtracting its delay manufactures a service result for a different arrival process. Reporting the dispatch-relative metric is legitimate only if it is labeled and accompanied by the intended-arrival population.
Three of four requests complete, so completion success is 75%, not 90%. Only A and B meet the declared first-token and completion thresholds: useful output is two requests in one second, or 2 requests/s, with 50% offered-workload success. Request D remains in the denominator. There are too few samples to estimate p99; assigning a p99 label to the slowest of three completions would not establish the production target.
The trace does not locate the generator bottleneck. An independent dispatch worker, client CPU/connection measurements and server-receipt timestamps can separate client serialization from network delay and admission queueing. Increasing server batch size before checking those boundaries may leave the original problem untouched. If the generator caused the lag, repeat the test after fixing it while retaining the same intended arrivals and joint prompt/output distribution.
Transfer exercise: B's first token arrives at 400 ms but its second at 650 ms and third at 660 ms. Its two visible gaps are 250 and 10 ms. An average of 130 ms obscures the 250 ms stall; worker-side token timestamps can determine whether generation or output flushing created it. Do not combine unsynchronized client and worker clocks by direct subtraction.
An executed open-loop streaming measurement¶
examples/benchmarks/streaming_http.py launches a loopback SSE fixture with two concurrent response slots and independently scheduled arrivals every 10 ms. The fixture emits four synthetic tokens per admitted response; it is not a model server. The client records scheduled arrival, actual dispatch, each token event, completion, and HTTP status. First-token latency is measured from the intended arrival, so client dispatch delay remains visible.
In the recorded 16-request run, four requests completed and twelve received overload rejection; no request failed partially. Median TTFT among the four completions was about 28.7 ms. That number describes Python/HTTP scheduling on the local machine and cannot establish a GPU latency floor. The important result is the complete population: reporting only those four latencies would hide 75% rejection.
The JSON trace retains inter-token gaps separately from total completion time. Apply the same event schema to an actual engine's streaming endpoint, with its tokenizer and protocol identity recorded. The older closed-loop, non-streaming HTTP harness remains useful for completion throughput, but it cannot reconstruct TTFT or token gaps from one final response.