Large Language ModelsInference & Performance Optimization
How do you use feedback-driven token-window pacing and tail-calibrated prefill budgets to prevent decode jitter and inter-token latency SLO violations in production LLM serving?
Question 289 of 309 · Updated
On this page
- 1. The problem: a fast average can still feel slow
- 2. Understand iteration-level interference
- 3. Define a latency budget with explicit tail headroom
- 4. Why tail calibration matters more than average calibration
- 5. Token-window pacing: regulate admitted prefill work
- 6. Closed-loop control: use measured feedback
- 7. Numerical production example
- 8. What happens when the prefill queue grows?
- 9. Production incident: decode jitter after a traffic ramp
- 10. Implementation sketch
- 11. Operational metrics and alerts
- 12. Common mistakes
- 13. Rollout checklist
- 14. Interview-ready answer
- 15. Further reading
1. The problem: a fast average can still feel slow#
A streaming LLM response is not experienced as one completion-time number. Users see a first token, then a sequence of tokens. If one GPU iteration runs long, every active stream in that batch can experience a pause. A service can therefore report acceptable average tokens per second while users see irregular output, stalled streams, and poor tail latency.
The two central latency measures are:
- Time to first token (TTFT): time from request arrival until its first generated token.
- Time between tokens (TBT), also called inter-token latency (ITL): time between consecutive generated tokens for a stream.
Prefill processes the input prompt and is generally compute-intensive and batch-friendly. Decode repeatedly advances active sequences, often with memory-bandwidth and KV-cache access constraints. Both phases may share the same GPU iteration. Admitting too much prefill work can lengthen an iteration and delay the next decode step for every active sequence.
The scheduling problem is not merely to choose the next request. It is to regulate how much new prefill work enters each iteration while protecting the tail of decode iteration time.
This lesson focuses on closed-loop token-window pacing and tail-calibrated prefill budgeting. It is distinct from general overload admission (#250), request deadline propagation (#253), head-of-line blocking (#252), chunked-prefill fundamentals (#184), and modality-aware scheduling (#288).
2. Understand iteration-level interference#
A simplified iteration may contain:
- Decode work for active sequences.
- A prefill chunk from one or more waiting prompts.
- Scheduling, synchronization, memory movement, and host-side overhead.
The iteration duration is not a fixed sum of independent averages. It depends on batch composition, prompt lengths, active decode count, KV-cache pressure, hardware, kernel selection, and runtime behavior.
If an iteration takes 60 ms, a streaming sequence that needs one token from that iteration cannot receive it sooner than the relevant work completes. In a batch, one slow iteration can affect many sequences simultaneously.
This is why a scheduler that fills every iteration up to its predicted average capacity can still violate a P95 or P99 TBT target. A small number of underestimated or unusually expensive iterations create correlated pauses across many users.
3. Define a latency budget with explicit tail headroom#
Suppose the service has a TBT objective of 50 ms at P99. Do not set the scheduler's target iteration duration to 50 ms. That leaves no room for host stalls, communication, synchronization, measurement error, or runtime variation.
Partition the budget conceptually:
TBT target = decode/iteration budget + safety headroom
The safety headroom should be calibrated from observed tail behavior, not chosen as an arbitrary fixed percentage.
For each iteration, estimate:
- Decode-only or decode-dominant execution time.
- Incremental prefill cost for the candidate chunk.
- Host and scheduler overhead.
- Communication and synchronization overhead.
- Prediction uncertainty under the current batch shape.
A conservative estimate can be written:
Here, M_tail is a safety margin derived from residuals between predicted and measured iteration times. It should adapt to the current hardware, model, batch shape, and traffic regime.
If the predicted iteration would exceed the safe budget, reduce or defer the prefill chunk. Do not remove active decode work simply to admit another prompt unless the product's service policy explicitly allows that trade-off.
4. Why tail calibration matters more than average calibration#
Assume a predictor estimates an iteration at 38 ms. Historical measurements show that prediction errors are usually small, but a small fraction of iterations take much longer because of host scheduling stalls, large prefill chunks, KV pressure, or batch-shape changes.
A mean residual of 2 ms does not mean a 2 ms safety margin is safe. A P99 residual of 11 ms means that the scheduler needs to account for much larger tail uncertainty if it wants a P99-level guarantee.
A practical approach:
- Record predicted and actual iteration duration.
- Compute residuals: actual minus predicted.
- Maintain rolling residual distributions by model, GPU type, batch shape, and operating regime.
- Select a quantile consistent with the desired risk budget.
- Add this calibrated residual to the next iteration estimate.
- Recalibrate when the model, runtime, kernel, GPU, or traffic distribution changes.
Use a sufficiently large sample window. A P99 estimate from a few dozen observations is not reliable. For very high-percentile objectives, use confidence bounds or conservative upper estimates rather than treating a noisy empirical percentile as a guarantee.
A simple model is:
where q is chosen from the tolerated late-iteration probability and operational risk. This assumes the residual distribution remains representative; monitor drift and use regime-specific estimates.
5. Token-window pacing: regulate admitted prefill work#
A batch-size limit counts sequences. A token budget counts prompt work. Neither alone fully captures runtime cost, but a token window is a more useful control variable for variable-length prompts.
At each scheduling tick, maintain a maximum amount of new prefill work that may be admitted into the next iteration or a short rolling window. This is the prefill token window.
The scheduler:
- Observes recent decode iteration times and TBT.
- Measures queue depth and waiting prompt tokens.
- Estimates the cost of candidate prefill chunks.
- Increases the token window when there is stable headroom.
- Shrinks it when decode latency approaches its safe boundary.
- Keeps the window bounded to avoid oscillation and unbounded admission.
The token window is not necessarily the model's maximum context length, the maximum number of tokens in a request, or the number of active sequences. It is a scheduler-controlled allowance for new prompt tokens over a defined interval.
Token count is only a proxy. A thousand tokens can have different costs depending on model architecture, attention implementation, prefix reuse, multimodal expansion, batch composition, and hardware. Calibrate token-to-time cost using actual execution measurements.
6. Closed-loop control: use measured feedback#
A fixed prefill-token budget may work for one traffic mix and fail when active decode count or prompt lengths change. A feedback controller adapts to current conditions.
Useful feedback signals:
- P50/P95/P99 iteration duration.
- P95/P99 TBT or ITL.
- Fraction of iterations exceeding the safe duration.
- Active decode sequences and KV-cache occupancy.
- Prefill queue token count and oldest wait time.
- Predicted versus actual iteration cost.
- GPU utilization and memory pressure, interpreted alongside latency.
A simple controller can use a target error:
e(t) = safe_iteration_budget − observed_or_predicted_iteration_cost
If the error is positive and stable, the scheduler may cautiously increase the prefill window. If the error is negative or tail violations rise, it reduces the window.
Avoid responding to one noisy sample with a large control change. Use:
- Exponential smoothing or robust rolling quantiles.
- Separate increase and decrease thresholds (hysteresis).
- Bounded step sizes.
- Minimum and maximum token windows.
- A cooldown period after large changes.
- Faster decreases than increases when protecting an SLO.
The asymmetry is intentional: reducing prefill admission can protect ongoing streams quickly, while increasing it should be gradual to avoid reintroducing jitter.
7. Numerical production example#
Consider a streaming endpoint with a 50 ms P99 TBT objective. During a baseline traffic period, the measured decode-dominant iteration time is:
- Median: 31 ms.
- P95: 39 ms.
- P99: 47 ms.
The scheduler also admits a 1,024-token prefill chunk into some iterations. Under that mixed load:
- Median iteration: 39 ms.
- P95 iteration: 51 ms.
- P99 iteration: 66 ms.
The average may still look acceptable, but the 66 ms tail exceeds the 50 ms objective. Because the iteration is shared, many active streams pause together.
After collecting prediction residuals, the scheduler estimates that the tail uncertainty for the current operating regime is 8 ms. It reserves this headroom and targets a predicted execution component no greater than 42 ms:
50 ms target − 8 ms tail margin = 42 ms schedulable estimate
Suppose the current decode work is predicted at 34 ms and fixed overhead at 2 ms. The remaining estimated prefill allowance is:
42 − 34 − 2 = 6 ms
The measured prefill cost model estimates 0.008 ms per token for this particular shape and batch regime. The initial safe prefill allowance is therefore:
6 ms ÷ 0.008 ms/token = 750 tokens
The scheduler does not automatically dispatch 750 tokens. It applies a conservative chunk cap, checks the actual batch shape and KV headroom, and may dispatch a smaller chunk.
Now the active decode count rises. Predicted decode time increases from 34 ms to 38 ms. The available prefill time falls to:
42 − 38 − 2 = 2 ms
At the same calibrated rate, the prefill allowance becomes 250 tokens. The scheduler shrinks the token window rather than allowing the new prompt work to push iteration time beyond the safe region.
During a quiet period, decode time falls to 25 ms. The controller can gradually raise the prefill window, provided measured tail latency remains stable.
These values are illustrative, not a universal conversion between tokens and milliseconds. Production cost models must be fitted to the actual runtime and workload.
8. What happens when the prefill queue grows?#
A latency-protective scheduler can make TTFT worse if it indefinitely defers new prompts. The goal is not to freeze prefill; it is to regulate it.
Use a combination of:
- Bounded prefill deferral: keep a maximum wait or age threshold.
- Chunked prefill: serve a long prompt in smaller pieces where supported.
- Shortest predicted safe chunk: choose work that fits the current iteration budget.
- Aging or service guarantees: prevent long prompts from being postponed forever.
- SLO-aware admission: do not accept more interactive work than can plausibly meet its TTFT objective.
- Separate queues: move batch or best-effort requests to a lower service class when appropriate.
Aging should not force a huge prompt into an iteration that would break every active stream. Instead, it should increase the prompt's scheduling opportunity over future safe iterations or trigger a clear defer/reject decision when its deadline is infeasible.
9. Production incident: decode jitter after a traffic ramp#
Symptom: After a launch, request volume rises by 35%. Median TTFT improves slightly because the scheduler fills large batches, but P99 TBT rises from 44 ms to 79 ms. Users report that responses start quickly and then pause unpredictably.
Root cause: The scheduler uses a fixed prefill-token budget tuned under a lower active-decode count. A new wave of long prompts enters continuous batching. The scheduler continues admitting the same prefill chunk even as decode work becomes more expensive. Its iteration predictor is calibrated to mean latency and underestimates tail overruns. One slow iteration delays every active sequence in that batch.
Containment:
- Reduce the prefill token window.
- Preserve active decode progress.
- Route best-effort batch prompts to a separate queue.
- Cap the maximum prefill chunk and stop retry amplification.
- Watch P99 TBT and iteration duration while the queue drains.
Permanent fix:
- Fit a batch-shape-conditioned iteration-time predictor.
- Calibrate residual quantiles by GPU and runtime regime.
- Introduce feedback-driven token-window pacing.
- Add hysteresis, bounded changes, and minimum prefill service.
- Include TTFT feasibility and queue age so that prefill is not starved.
- Replay the traffic ramp in load tests before rollout.
Verification: Compare P50/P95/P99 TBT, TTFT, iteration-time tails, prefill wait, completed tokens per second, SLO goodput, and queue age. Check both the busiest interval and recovery after the burst. A scheduler that fixes TBT by leaving prompts queued forever is not a successful fix.
10. Implementation sketch#
PYTHONdef choose_prefill_chunk(state, predictor, residual_quantile): # Protect ongoing decode before adding new prefill work. decode_ms = predictor.decode_cost(state.active_sequences, state.kv_pressure, state.batch_shape) overhead_ms = predictor.overhead_cost(state) tail_margin_ms = residual_quantile.for_regime(state.regime) safe_prefill_ms = ( state.tbt_budget_ms - decode_ms - overhead_ms - tail_margin_ms ) if safe_prefill_ms <= 0: state.controller.decrease_window() return None token_window = state.controller.current_window candidate = state.prefill_queue.next_chunk( max_tokens=token_window ) if candidate is None: return None predicted_prefill_ms = predictor.prefill_cost( candidate, state.batch_shape, state.kv_pressure ) if predicted_prefill_ms > safe_prefill_ms: smaller = predictor.largest_chunk_fitting( candidate, safe_prefill_ms, token_window ) candidate = smaller if candidate is None: state.controller.decrease_window() return None return candidate def update_controller(state, measured_iteration_ms, predicted_ms): residual = measured_iteration_ms - predicted_ms state.residual_model.observe(residual, state.regime) p99_tbt = state.metrics.rolling_p99_tbt() violation_rate = state.metrics.iteration_overrun_rate() if p99_tbt > state.tbt_target_ms or violation_rate > state.max_overrun_rate: state.controller.decrease_fast() elif state.metrics.stable_for_window(): state.controller.increase_slowly() state.controller.apply_hysteresis_and_bounds()
This is conceptual pseudocode. A production scheduler needs concurrency-safe batch accounting, robust predictors, safe runtime integration, and controller state that behaves predictably during worker restarts.
11. Operational metrics and alerts#
Decode experience
- P50/P95/P99 TBT and inter-token latency.
- Per-stream maximum token gap.
- Percentage of streams with one or more TBT violations.
- Decode iteration duration distribution.
- Correlated batch-wide stalls.
Prefill progress
- TTFT by prompt-length bucket.
- Prefill queue tokens, age, and wait percentiles.
- Tokens admitted per iteration and per second.
- Chunk sizes, deferrals, and starvation/aging events.
Predictor and controller
- Predicted versus actual iteration duration.
- Residual quantiles and calibration drift.
- Current token window and rate of change.
- Number of controller increases/decreases.
- Time spent at minimum or maximum window.
- SLO violations following window increases.
Capacity
- Active decode sequences.
- KV-cache occupancy, allocation failures, and preemption.
- GPU memory and compute utilization.
- Host scheduler stalls and communication overhead.
Alert on sustained tail violations and predictor drift, not just high average GPU utilization.
12. Common mistakes#
- Using mean iteration time: rare overruns dominate streaming experience.
- Targeting the entire TBT budget: leaves no room for tail uncertainty.
- A fixed token window: ignores changing decode concurrency and batch shape.
- Treating tokens as equal-cost work: token count is only a calibrated proxy.
- Overreacting to one slow iteration: creates control oscillation.
- Increasing the window too quickly: causes repeated bursts of decode jitter.
- Protecting decode by starving prefill: TTFT and queue age become unacceptable.
- Ignoring KV pressure: a compute-safe batch can still fail memory constraints.
- Using fleet averages: hides the long-prompt or particular-GPU regime that causes overruns.
- Claiming a hard guarantee from a percentile predictor: empirical tail calibration is not a formal worst-case execution-time proof.
13. Rollout checklist#
- Instrument iteration duration and per-stream TBT at sufficient resolution.
- Record predicted and actual costs for each batch.
- Build regime-specific residual distributions with adequate samples.
- Shadow-compute safe prefill budgets without changing scheduling.
- Compare predicted overrun decisions with actual outcomes.
- Enable conservative token-window caps for a small traffic slice.
- Add closed-loop decreases first; enable gradual increases only after stability.
- Track TTFT and queue age as guardrails against prefill starvation.
- Test bursts, long prompts, high decode concurrency, KV pressure, and host stalls.
- Expand gradually and recalibrate after runtime, model, or hardware changes.
14. Interview-ready answer#
I would protect decode latency at the GPU-iteration level, not just with a request priority. I would predict decode cost, candidate prefill cost, and runtime overhead, then subtract a tail-calibrated residual margin from the TBT budget to obtain a safe prefill allowance. A token-window controller would increase or decrease the amount of new prompt work based on measured iteration tails, TBT violations, queue age, and active decode load.
The controller needs hysteresis and bounded changes to avoid oscillation. It must also preserve prefill progress through chunking, aging, and TTFT-aware admission. I would validate it using mixed-load replay and monitor P99 TBT, TTFT, iteration overruns, prefill wait, SLO goodput, and predictor calibration. The objective is stable streaming latency without turning the prefill queue into an unbounded waiting room.
15. Further reading#
- VelServe: Taming Decode Jitters in LLM Inference with Tail-Calibrated Scheduling (2026): studies decode iteration overruns, tail-calibrated prefill admission, and shortest-waiting-prompt selection.
- Stable Token-level Scheduling for Serverless LLM Inference (2026): introduces feedback-driven token-window pacing using inter-token latency, queue depth, and workload characteristics.
- Formal schedulability analysis for LLM inference: TTFT and TBT deadline guarantees via response-time theory (2026): formalizes admission against TTFT and TBT constraints and explains decode-first scheduling with chunked prefill.
- Large-Scale LLM Inference with Heterogeneous Workloads: Prefill-Decode Contention and Asymptotically Optimal Control (2026): models prefill/decode contention and constrained resource allocation.
The key principle: protect every decode iteration with measured tail headroom, and let feedback—not a fixed batch or token limit—control how much prefill work enters the system.
References
- 1.
- 2.
- 3.
- 4.
Related questions
- How do you optimize GPU utilization across mixed interactive and batch LLM inference workloads while preserving latency isolation?
- We need to serve our model for two different use cases: a low-latency chatbot that needs a fast Time-to-First-Token (TTFT), and a high-throughput batch summarization job. How do these two workloads stress the GPU differently, and what fundamental tradeoff are you managing?
- How do prefill/decode disaggregation and KV-cache transfer affect TTFT, inter-token latency, and throughput?
Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents