Large Language ModelsInference & Performance Optimization

How should production LLM serving systems reserve and grow KV-cache capacity when output lengths are unknown, balancing preemption risk against stranded memory?

Question 290 of 309 · Updated

On this page

The production problem#

An LLM server knows the prompt length when a request arrives. It does not know how many tokens the model will generate before it reaches an end-of-sequence token, a stop condition, or the configured output limit. Yet every generated token normally adds key/value (KV) state that must remain available for later decoding steps.

That creates a resource-allocation problem before generation has revealed the final demand:

  • Reserve too little: the request may run out of KV blocks while decoding. The scheduler may preempt it, pause it, swap state, or recompute prior work. Depending on the runtime and policy, this can increase time-to-first-token (TTFT), inter-token latency (ITL), and tail latency.
  • Reserve too much: memory sits idle for tokens the request may never generate. Fewer requests fit concurrently, queueing rises, and goodput falls.
  • Use one global estimate: short chat replies and long code or reasoning responses have different output-length distributions. A single reservation quantile can be wasteful for one class and unsafe for another.
  • Trust historical averages: prompt templates, user behavior, model versions, and traffic mix change. A previously safe estimate can become stale.

The engineering objective is not to guess every completion length correctly. It is to make a controlled decision under uncertainty, then adapt allocation as real tokens arrive, while keeping enough headroom to avoid repeated preemption.

This lesson focuses specifically on per-request output-length uncertainty and KV reservation policy. It is not a general explanation of paged attention, KV compression, cache fragmentation, admission control, or prefill pacing.

1. Understand what is being reserved#

For a decoder-only Transformer, KV memory grows approximately linearly with the number of resident tokens, subject to the model's attention architecture, layers, KV heads, data type, tensor-parallel layout, and any sliding-window or hybrid-attention behavior.

A simplified per-token estimate for one replica is:

LaTeX

where:

  • is the number of layers.
  • is the number of key/value heads per layer on the relevant device.
  • is the head dimension.
  • is bytes per stored element.
  • The factor 2 accounts for keys and values.

For a tensor-parallel deployment, calculate the per-GPU footprint using the actual sharding and replication behavior. Do not blindly divide by the tensor-parallel degree: some architectures replicate KV heads or shard them differently.

A real runtime allocates blocks/pages rather than an arbitrary number of bytes. If a block holds tokens, the reservation for additional tokens is approximately:

LaTeX

The actual allocation can include block rounding, in-flight tokens, speculative lookahead, prefix reuse, sliding-window retention, and runtime-specific metadata. Treat the formula as a planning model, then reconcile it with engine-reported block accounting.

Example: derive the memory cost#

Assume a hypothetical model deployment has a measured per-GPU KV footprint of 0.5 MiB per token. This is an illustrative deployment value, not a universal property of a 70B model.

A request with 1,000 prompt tokens and 2,000 generated tokens could eventually need:

LaTeX

If the request has already computed a reusable 400-token prefix, the engine may avoid allocating duplicate physical blocks for that shared prefix. However, do not subtract reusable tokens unless the serving engine confirms the blocks are resident, compatible, and reference-counted for this request. A cache hit is not a promise that those blocks will remain resident forever.

The key distinction is between:

  • current resident KV: blocks already allocated for computed tokens;
  • future growth demand: blocks likely to be needed as generation continues;
  • reservation/headroom: capacity held or protected against future growth;
  • reusable cached KV: shared state that may reduce new allocation, but has eviction and lifetime rules.

2. Why fixed reservation policies fail#

Common policies include:

  • Reserve the mean output length.
  • Reserve a fixed P90, P95, or P99 output length.
  • Reserve the full maximum output length.
  • Allocate one or a few blocks initially and hope the pool can grow later.
  • Use one reservation rule for every request.

Each can be useful in a narrow setting, but none is universally correct.

Mean reservation is cheap in memory but ignores the upper tail. A workload with a mean of 300 tokens and a long tail to 4,000 tokens will repeatedly surprise the scheduler.

High-quantile reservation reduces under-reservation but can strand substantial memory when many requests terminate early. It can also be fragile under distribution shift: yesterday's P95 may not be today's P95.

Maximum-length reservation is safe only if the capacity cost is acceptable. If a client sets max_tokens=8,000 for flexibility but most responses end after 250 tokens, reserving the full maximum can destroy concurrency.

Tiny initial reservation with unrestricted growth improves initial packing but assumes future blocks will be available. Under burst load, many active requests can demand growth simultaneously. The system may then preempt work it already paid to compute.

The correct policy explicitly prices both errors: the cost of reserving too little and the cost of reserving too much.

3. Use request classes, not one global output-length distribution#

Start by grouping traffic into operationally meaningful classes. Do not create hundreds of classes before the data supports them.

Possible dimensions include:

  • Endpoint or product use case: chat, summarization, RAG, code generation, agent/tool orchestration.
  • Model and model version.
  • Tenant or service tier, where policy and privacy allow.
  • Requested output cap and decoding mode.
  • Prompt/template family, if it is stable and has enough observations.
  • Structured output versus free-form generation.

For each class, maintain a distribution of actual generated tokens, not merely configured max_tokens. Record truncation, stop reason, cancellation, and tool handoff separately. A response stopped by the client at 200 tokens is not evidence that the model naturally would have completed at 200.

Use robust statistics:

  • median and P90/P95/P99 output length;
  • tail exceedance rate above the active reservation;
  • output-length calibration by class;
  • sample count and confidence interval;
  • distribution drift over time.

Avoid over-segmentation. If a class has only 30 observations, its estimated P99 is not meaningful. Back off to a parent class or a conservative prior until enough data exists.

4. Choose a reservation quantile from the economics#

A useful conceptual model is a newsvendor-style decision. Let be the number of output tokens reserved at admission and be the eventual output length.

  • If , the system faces under-reservation cost: incremental growth pressure, possible preemption, recomputation, and SLO risk.
  • If , the system pays over-reservation cost: unused capacity held for the duration of the request.

Let:

  • = marginal cost of under-reserving;
  • = marginal cost of over-reserving.

A simplified optimal quantile is:

LaTeX

and the starting reservation is the -quantile of the class's output distribution.

This is a decision aid, not a production law. Real systems have shared GPU pools, time-varying arrivals, correlated request lengths, block rounding, queueing, and SLO constraints. Those effects make the full optimization more complex. But the formula explains the direction:

  • If preemption is extremely expensive, increase the reservation quantile.
  • If memory scarcity and queueing dominate, lower it and rely on safe, measured growth.
  • If the class has strict TTFT/ITL SLOs, include the expected latency cost of recomputation and queueing.
  • If the class is best-effort batch work, it may tolerate a more memory-efficient reservation and controlled preemption.

Do not select P95 simply because it sounds safe. Select a quantile because the measured cost of the two error types justifies it.

5. Numerical production example#

Consider a hypothetical serving pool with 100,000 KV token-slots available after model weights, runtime workspace, and safety headroom have been accounted for. For simplicity, assume one slot represents one token's KV footprint on the pool's accounting unit.

A traffic sample contains two stable classes:

  • Interactive chat: 80 requests, median output 180 tokens, P90 320, P99 700.
  • Code generation: 20 requests, median output 900 tokens, P90 1,800, P99 3,000.

Assume the current policy reserves 700 tokens for every chat request and 3,000 for every code request.

Initial reserved capacity is:

  • Chat: 80 × 700 = 56,000 slots.
  • Code: 20 × 3,000 = 60,000 slots.
  • Total: 116,000 slots.

The pool only has 100,000 slots. The server must queue or reject some requests even though many responses will finish far below their reservations.

Now assume the team evaluates a class-specific policy:

  • Chat reservation: 300 tokens.
  • Code reservation: 1,500 tokens.
  • Additional growth blocks are allocated in bounded increments as tokens are generated.

Initial reservation becomes:

  • Chat: 80 × 300 = 24,000 slots.
  • Code: 20 × 1,500 = 30,000 slots.
  • Total: 54,000 slots.

This leaves 46,000 slots for growth, other admitted traffic, and operational headroom. It does not mean the system can safely admit unlimited requests. The scheduler must estimate aggregate growth risk and protect a reserve for requests already in flight.

Suppose the observed output lengths in one batch are:

  • 70 chat responses average 180 tokens, 8 reach 320 tokens, and 2 reach 650 tokens.
  • 14 code responses average 900 tokens, 4 reach 1,700 tokens, and 2 reach 2,800 tokens.

The lower reservation policy needs growth for the requests that exceed 300 or 1,500 tokens. The system should allocate blocks as they are needed, but only when the shared pool has enough free capacity after accounting for the near-term growth of other active requests.

A dangerous implementation would admit the next 100 requests just because 46,000 slots are currently free. A safer scheduler asks: How much of that free capacity is already likely to be consumed by active requests over the next scheduling horizon?

If active requests have a forecast aggregate growth demand of 31,000 slots at the chosen risk level, the scheduler may expose only 15,000 slots for new growth/admission, preserving the remainder as a growth buffer. These numbers are illustrative; production thresholds must be learned from real traces and validated against SLOs.

6. Separate admission reservation from runtime allocation#

A robust design uses at least three distinct controls:

  1. Admission reservation: a probabilistic or policy-based estimate of future output demand used to decide whether a request can safely enter the running set.
  2. Incremental allocation: actual blocks allocated as tokens are produced, with bounded growth increments and an atomic capacity check.
  3. Global growth reserve: protected capacity for already-running requests whose output exceeds their initial reservation.

Do not physically pre-allocate every reserved token if the engine supports logical reservation or a separate reservation ledger. A logical reservation can prevent over-admission without committing all pages immediately. But the ledger must be enforced consistently across workers; otherwise it is only an optimistic counter.

A practical sequence:

  • On request arrival, compute prompt KV demand and class-specific output reservation.
  • Account for confirmed prefix-cache reuse using engine-provided residency and ownership semantics.
  • Check the request's context/output limit and block-rounded reservation.
  • Check aggregate reservations, current physical usage, and a protected growth watermark.
  • Admit, queue, or reject according to the endpoint's policy.
  • During decode, allocate additional blocks before the request exhausts its currently allocated capacity.
  • Release unused reservation immediately when generation ends, cancellation is confirmed, or a request is safely terminated.
  • Keep shared prefix blocks alive according to the cache manager's reference counts and eviction policy.

Admission reservation must not be confused with the actual max output limit. The max output limit is a product/API constraint. Reservation is a capacity estimate. A request may be permitted to generate up to 4,000 tokens while initially reserving only a class-specific quantile, provided the engine can safely grow and the scheduler accounts for the tail risk.

7. Make growth block-aware and proactive#

If a request is allowed to grow only after it has consumed every allocated block, it may stall at the worst possible time. Allocate ahead by a small number of blocks or a short token horizon.

For each active request, track:

  • computed tokens;
  • allocated KV tokens/blocks;
  • remaining blocks before another allocation is needed;
  • output tokens generated so far;
  • predicted remaining output distribution;
  • request deadline and latency class;
  • current shared-pool pressure.

A simple growth trigger is:

LaTeX

where is a small lookahead threshold measured in tokens or blocks. The threshold should cover the time needed for the allocator/scheduler to make a safe allocation decision, not be chosen arbitrarily.

Growth should be atomic at the pool level. Two workers must not both observe the same free blocks and over-commit them. In distributed serving, use a central allocator, a lease/reservation protocol, or a carefully designed partitioned pool with explicit quotas. Avoid a high-contention global lock on every generated token; allocate in block-sized increments.

When the pool is under pressure:

  • stop admitting new requests before starving existing ones;
  • prioritize imminent growth for requests already in flight;
  • apply endpoint-specific queueing or backpressure;
  • optionally move eligible work to another compatible pool;
  • preempt only according to an explicit policy with a measured recovery cost.

Do not silently reduce max_tokens to make the allocator fit. That changes user-visible behavior and may produce truncated answers.

8. Adapt to workload drift without chasing noise#

Output distributions shift. A new prompt template may increase response length; a model release may become more verbose; agent workflows may add tool-result context; a product launch may change the mix of code and chat requests.

Use a feedback loop:

  • update per-class histograms or quantile sketches continuously;
  • use a rolling window plus a slower baseline;
  • detect sustained changes in P90/P99 and exceedance rates;
  • require a minimum sample count;
  • smooth reservation changes and impose per-update bounds;
  • keep a conservative fallback for sparse or newly observed classes.

A simple controller might:

  • raise the reservation quantile or growth buffer when under-reservation and preemption exceed budget;
  • lower it gradually when over-reservation is high and growth failures remain low;
  • freeze adaptation during severe incidents to avoid reacting to corrupted data;
  • roll back to a known-good policy if the new policy increases SLO violations.

Avoid reacting to every long response. One unusual 10,000-token completion should not instantly change reservations for all users. Use robust windows, class separation, and hysteresis.

9. Production incident: the average stayed stable while the tail changed#

Scenario (illustrative): A code-assistant endpoint normally generates a median of 650 tokens and P95 of 1,500. The team reserves 1,600 output tokens per request and admits traffic based on that estimate.

A product release adds multi-file refactoring. Median output increases only slightly, to 720 tokens, but the P95 rises to 2,700 and the P99 to 4,600. The mean moves less dramatically than the tail.

At peak load, many active requests exceed their initial reservation at the same time. The growth allocator finds insufficient free blocks. The runtime begins preempting requests and recomputing them. The dashboard shows:

  • preemption count rising sharply;
  • TTFT increasing for re-admitted requests;
  • ITL spikes during periods of memory pressure;
  • goodput falling even though GPU compute utilization remains high;
  • queue depth increasing because reserved capacity is stranded in short responses while long responses need more blocks.

The first attempted fix is to double every request's reservation. This reduces preemption but halves the number of requests that can be admitted and makes TTFT worse.

Root cause: the reservation policy was based on a stale aggregate distribution and ignored the new request class. It optimized average memory use, not the joint cost of tail growth and queueing.

Engineering correction:

  1. Split the code-assistant traffic into stable task classes, such as short completions and multi-file edits, where the classifier has sufficient confidence.
  2. Re-estimate output-length distributions from uncensored completions, while separately recording user cancellations and max-token truncations.
  3. Increase the reservation quantile only for the long-output class.
  4. Keep a shared growth reserve sized from concurrent tail demand, not a single-request P99 multiplied blindly by all requests.
  5. Cap new admissions when projected near-term growth exceeds the reserve.
  6. Roll out the policy to a small traffic slice and compare preemption, goodput, TTFT, ITL, and memory efficiency against a control group.

The fix is not “reserve the maximum for everyone.” It is to identify which requests are likely to need more KV, reserve according to the cost of being wrong, and protect in-flight growth.

10. Pseudocode for a reservation-aware scheduler#

The following is conceptual pseudocode. Real implementations must use the serving engine's KV block manager and concurrency primitives; do not maintain a second, unsynchronized view of physical KV ownership.

PYTHON
def estimate_output_reservation(request, class_stats, policy): cls = classify_request(request) stats = class_stats.get(cls) if stats is None or stats.sample_count < policy.min_samples: stats = class_stats.parent_or_fallback(cls) quantile = policy.quantile_for( request.latency_class, under_reservation_cost=policy.preemption_cost(cls), over_reservation_cost=policy.memory_cost(), ) predicted_tokens = stats.quantile(quantile) predicted_tokens = min(predicted_tokens, request.max_output_tokens) # Add a bounded safety margin for quantile error and allocator delay. predicted_tokens += policy.margin_tokens(cls) return round_up_to_kv_block(predicted_tokens) def admit(request, engine, ledger, stats, policy): prompt_blocks = engine.estimate_prompt_blocks(request) output_tokens = estimate_output_reservation(request, stats, policy) output_blocks = blocks_for(output_tokens) reusable = engine.confirmed_reusable_prefix_blocks(request) incremental_prompt_blocks = max(0, prompt_blocks - reusable) reservation = incremental_prompt_blocks + output_blocks # The ledger includes current usage, outstanding reservations, # and protected growth capacity for running requests. if not ledger.can_reserve( reservation, keep_growth_reserve=True, keep_emergency_headroom=True, ): return "QUEUE_OR_REJECT" # Reservation and admission must be atomic across concurrent schedulers. lease = ledger.acquire(request.id, reservation) try: engine.enqueue(request, reservation_lease=lease) return "ADMITTED" except Exception: ledger.release(lease) raise def before_decode_growth(request, engine, ledger, policy): if engine.remaining_allocated_tokens(request) > policy.growth_trigger_tokens: return "CONTINUE" needed = policy.growth_chunk_blocks if ledger.try_extend(request.reservation_lease, needed): engine.allocate_kv_blocks(request, needed) return "CONTINUE" # Never assume capacity exists because it existed at a previous check. return policy.pressure_action(request) # queue, pause, migrate, or preempt

Important implementation safeguards:

  • The ledger and engine allocation must agree. If the ledger grants capacity but the engine cannot allocate it, reconcile the lease and surface an allocation failure.
  • If engine allocation succeeds but ledger update fails, the system can over-admit. Use transactional reservation semantics or a single authoritative allocator.
  • A request that is cancelled must release its private blocks and reservation; shared prefix blocks must follow reference-count semantics.
  • Growth must be bounded so one pathological completion cannot consume the entire pool.
  • Never count the same reusable prefix block as free capacity for multiple requests unless the engine's sharing model explicitly permits it.

11. Measure both sides of the trade-off#

A reservation controller can look healthy if it measures only preemption or only memory utilization. Track the full outcome.

Under-reservation and recovery

  • KV allocation failures and failed growth attempts.
  • Preemptions per 1,000 completed requests.
  • Recomputed tokens and recomputation GPU time.
  • Number of requests preempted more than once.
  • TTFT and ITL impact for preempted versus non-preempted requests.
  • Deadline/SLO misses attributable to KV pressure.

Over-reservation and capacity

  • Reserved-but-unused KV blocks over request lifetime.
  • Average and P95 reservation utilization.
  • Active requests per GPU at equivalent SLO.
  • Queue time and admission rejection rate.
  • Goodput: completed requests meeting their latency and quality constraints per unit time.
  • GPU memory pressure and actual KV block occupancy.

Forecast quality

  • Per-class quantile calibration: the fraction of outputs that exceed the reserved length.
  • Output-length distribution drift.
  • Sample count and confidence intervals.
  • Error by model version, tenant class, endpoint, and prompt family where policy allows.

Do not treat high GPU utilization as proof of efficient serving. A GPU can be busy recomputing preempted requests while user-visible goodput deteriorates.

12. Test the policy before production#

Build trace-driven tests with realistic request arrivals, prompt lengths, output lengths, cancellation patterns, and correlated bursts. Independent random output lengths can understate risk if a real event causes many requests to become longer together.

Test at least:

  • a normal traffic day;
  • a burst with a long-output mix shift;
  • a new prompt template with sparse history;
  • high cancellation rates;
  • a tenant that consistently requests long outputs;
  • a sudden model-version change;
  • prefix-cache hit-rate collapse;
  • allocator delay or worker loss;
  • many simultaneous growth requests near the memory watermark.

Compare fixed-mean, fixed-quantile, max-reservation, and adaptive policies using the same trace and hardware configuration. Evaluate the complete distribution of TTFT, ITL, goodput, preemption, and reserved-but-unused memory. A policy that wins on average but violates P99 SLOs is not a safe improvement.

Roll out in stages:

  1. Shadow mode: compute reservations without influencing admission.
  2. Offline replay: compare predicted reservations with actual token lengths and block demand.
  3. Small canary: enable the ledger and growth policy for a limited traffic share.
  4. Guarded ramp: increase traffic only if preemption, SLO, and goodput guardrails hold.
  5. Rollback: restore the previous reservation policy and preserve conservative admission limits if metrics regress.

13. Engineering trade-offs and common mistakes#

  • One global P99: ignores workload heterogeneity and can waste capacity for short responses.
  • Mean-only reservation: ignores tail growth and creates avoidable preemption.
  • Always reserve max_tokens: confuses an API ceiling with expected resource demand.
  • Use output predictions as guarantees: predictions are estimates; retain a safe fallback and a growth reserve.
  • Ignore censored outputs: user cancellations and max-token cutoffs bias the observed length distribution downward.
  • Multiply one-request P99 by concurrency: assumes independent tails and can be either too conservative or dangerously optimistic under correlated bursts.
  • Over-segment classes: creates noisy quantiles and unstable controllers.
  • Ignore block rounding: token-level arithmetic can understate real block demand.
  • Double-count prefix reuse: cached state is shared and evictable; only credit confirmed reusable blocks according to engine semantics.
  • Allocate only after exhaustion: makes growth failures and stalls more likely.
  • Allow unbounded growth: a single request can starve the pool.
  • Use a non-atomic reservation ledger: concurrent schedulers can oversubscribe the same free capacity.
  • Tune only for memory utilization: queueing and recomputation can destroy goodput while utilization looks high.
  • Silently truncate output: turns a capacity incident into a correctness and product incident.

14. How this relates to serving frameworks#

Paged KV managers allocate blocks as requests progress and can support reuse, eviction, and offloading. These mechanisms solve storage and reuse problems; they do not automatically choose the economically correct output reservation quantile for every workload.

vLLM documents preemption when KV space is insufficient and notes that recomputation can adversely affect end-to-end performance. Its scheduler configuration also exposes a watermark to retain free KV blocks when admitting waiting or preempted requests. These are useful runtime controls, but they do not remove the need to measure class-specific output-length uncertainty.

TensorRT-LLM describes KV blocks assigned to requests as needed, with cross-request reuse and prioritized eviction. Reuse can save memory and computation, but the cache still competes with active requests for finite GPU capacity. Verify the exact manager version and behavior of the deployed release before relying on any setting.

The operational design therefore has two layers:

  • the engine owns actual block allocation, sharing, and eviction;
  • the serving policy owns admission estimates, class-specific reservation, growth headroom, and SLO-aware decisions.

Do not build a parallel cache manager in application code unless the serving runtime explicitly exposes the required safe integration points.

15. Interview-ready answer#

“LLM output length is unknown at admission, but KV memory grows with every generated token. If I reserve too little, active requests can run out of blocks and be preempted or recomputed, increasing TTFT and inter-token latency. If I reserve too much, I strand GPU memory and reduce concurrency. I would measure actual, uncensored output-length distributions by endpoint or request class, choose reservation quantiles based on the relative cost of preemption versus unused memory, and use a shared growth reserve. The scheduler would atomically account for prompt KV, confirmed prefix reuse, outstanding reservations, and forecast concurrent growth. During decoding it would allocate blocks proactively in bounded increments and stop admitting new work before it starves active requests. I would monitor quantile exceedance, reserved-but-unused blocks, preemption, recomputed tokens, TTFT, ITL, queueing, and goodput. Finally, I would validate the policy with trace replay and a canary under correlated long-output bursts—not just average traffic.”

Related questions

Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents