Large Language ModelsInference & Performance Optimization
How do you prevent KV-cache thrashing and make preemption productive for long-output LLM requests?
Question 291 of 309 · Updated
On this page
- The problem: a request can be preempted repeatedly without making progress
- 1. Understand the three distinct costs
- Lost computation
- Data movement
- Lost opportunity to make progress
- 2. Recognize KV thrashing in traces
- 3. Decide when to recompute and when to preserve KV state
- Recompute
- CPU offload and restore
- Partial preservation or snapshotting
- 4. Calculate the break-even point
- 5. Select victims using more than cache size
- Remaining-length prediction
- 6. Make recovery productive with bounded waiting and protected decode
- Why age-based readmission matters
- Why protection must be bounded
- 7. Use snapshots and contiguous host storage carefully
- 8. Numerical example: compare three recovery strategies
- 9. Production incident: high GPU utilization, poor completion time
- 10. Scheduler pseudocode
- 11. Metrics that reveal whether preemption is productive
- 12. Test for thrashing before rollout
- 13. Common mistakes
- 14. How this relates to current serving systems and research
- 15. Interview-ready answer
The problem: a request can be preempted repeatedly without making progress#
During autoregressive decoding, each generated token adds key/value (KV) state that the serving engine retains so later tokens can attend to the full context without recomputing it. Long-output reasoning, coding, and agentic requests can therefore occupy substantial GPU memory for a long time.
When the GPU KV pool becomes full, the scheduler may preempt a running request to free blocks for other work. Depending on the engine, it can discard the request's KV state and recompute it later, or preserve the state in host memory and restore it when the request resumes.
Preemption is not automatically bad. It is a useful safety mechanism that lets a server keep accepting work rather than failing when memory is oversubscribed. The failure mode is KV-cache thrashing:
- Request A is preempted and its GPU blocks are released.
- Other active requests grow and consume those blocks.
- A waits for capacity, then is finally restored.
- Before it generates meaningful new output, it is preempted again.
- The system repeatedly spends time restoring or recomputing old state instead of producing new tokens.
A request can therefore spend a large fraction of its lifetime stalled while the GPU remains busy serving other requests. Aggregate utilization may look healthy even though completion latency and useful throughput are poor.
The engineering objective is not simply to minimize the number of preemptions. It is to ensure that when preemption is necessary, the interrupted request preserves valuable work, returns within a bounded time, and receives enough protected decode time to make measurable forward progress.
This lesson focuses on recovery and scheduling after KV pressure causes preemption. It builds on Question 290's output-length-aware reservation and growth policy, but does not repeat reservation quantile selection, general admission control, KV-cache compression, or cache fragmentation diagnosis.
1. Understand the three distinct costs#
A preemption policy must account for three separate costs.
Lost computation#
If the engine discards a request's KV state, resuming it may require recomputing the prompt and previously generated tokens. This consumes GPU compute and can delay other requests.
Let:
- = time to recompute the lost KV state;
- = time to save the state to host memory;
- = time to restore it to GPU memory;
- = time waiting for GPU capacity;
- = time needed to produce useful new decode tokens after resumption.
A simplified recovery cost is:
These equations are deliberately simplified. Transfers can overlap with compute, waiting time depends on scheduler policy, and recomputation cost depends on prompt length, attention implementation, batch shape, and hardware.
Data movement#
Saving KV state avoids recomputation, but moving a large cache from GPU to CPU and back can be expensive. A request with a large context may have gigabytes of KV state. Host-device bandwidth, pinned-memory availability, copy-engine contention, NUMA placement, and synchronization all matter.
Offload is not automatically faster than recomputation. A runtime may rationally choose recomputation when the KV state is small or the transfer path is slow.
Lost opportunity to make progress#
The most subtle cost is repeated interruption. Suppose a request spends 20 seconds waiting for a restore, then decodes 25 tokens, then is preempted again. It has technically resumed, but the user sees little progress.
The scheduler must measure not only how many requests were preempted, but also:
- how long each request waited;
- how much new output it generated after recovery;
- how frequently it was interrupted again;
- what fraction of its lifetime was spent stalled or recovering.
2. Recognize KV thrashing in traces#
Consider a request timeline:
| Event | Time | New output since prior recovery |
|---|---|---|
| First decode segment | 0–18 s | 1,100 tokens |
| First preemption and wait | 18–42 s | 0 |
| Restored decode segment | 42–45 s | 28 tokens |
| Second preemption and wait | 45–71 s | 0 |
| Restored decode segment | 71–74 s | 31 tokens |
| Third preemption and wait | 74–96 s | 0 |
The request has generated 1,159 tokens, but its last 51 seconds have yielded only 59 new tokens. If the system reports only total GPU utilization or total tokens generated, the problem can be hidden.
A useful request-level progress measure is:
This is not a replacement for TPOT or end-to-end latency. It is a diagnostic signal that helps distinguish a productive preemption from repeated recovery with little output.
A second metric is the re-preemption interval: elapsed time or number of fresh tokens between a request's recovery and its next preemption. A short interval combined with a long wait is a strong thrashing signal.
3. Decide when to recompute and when to preserve KV state#
There is no universally best recovery method.
Recompute#
Discard the preempted KV state and reconstruct it when the request resumes.
Advantages:
- avoids host-memory capacity and allocation complexity;
- avoids GPU-to-CPU and CPU-to-GPU KV transfers;
- can be efficient for short contexts and fast prefill paths;
- may be the simplest supported behavior in a serving runtime.
Disadvantages:
- repeats already-paid computation;
- can be very expensive for long prompts or long generated histories;
- can create large prefill bursts when several requests resume together;
- can worsen tail latency if the same request is repeatedly evicted.
CPU offload and restore#
Copy the preempted request's KV state to host memory, release the GPU blocks, and restore the state when the request is scheduled again.
Advantages:
- preserves previously computed KV state;
- can reduce repeated prefill/recomputation for long contexts;
- can be useful when GPU capacity is scarce but host memory and transfer bandwidth are available.
Disadvantages:
- transfers can be large and synchronization-sensitive;
- pinned host memory is finite and must be budgeted;
- CPU NUMA placement and PCIe/NVLink topology affect performance;
- simultaneous restores can saturate interconnects;
- offloaded requests still need GPU capacity to resume.
Partial preservation or snapshotting#
A system may preserve selected KV state or periodically create a fixed-length snapshot rather than continuously copying every update. This can reduce storage waste and allow bulk transfers, but introduces a recovery gap: tokens generated after the snapshot may need to be recomputed or otherwise reconstructed.
The correct choice depends on the measured break-even point, not a blanket preference for swap or recompute.
4. Calculate the break-even point#
Suppose a hypothetical request has 8 GiB of KV state. The effective measured transfer bandwidth is 32 GiB/s in each direction, and fixed synchronization/setup costs total 25 ms per transfer.
Approximate one-way transfer time:
Saving and restoring the full state costs approximately:
Assume recomputing the state would take 1.8 seconds on the current GPU under the observed workload. Ignoring overlap and queueing, preservation saves approximately 1.25 seconds of direct recovery work.
Now change the scenario:
- KV state is 512 MiB.
- Effective transfer bandwidth remains 32 GiB/s.
- Fixed setup cost remains 25 ms per transfer.
- Recompute takes 40 ms.
Each transfer takes roughly 41 ms, so save plus restore costs around 82 ms. Recompute at 40 ms is cheaper.
These are illustrative numbers, not benchmark claims. In production, measure:
- actual bytes transferred, not nominal cache size;
- achieved bandwidth under concurrent traffic;
- copy setup and synchronization overhead;
- recomputation time for the same model, sequence length, and batch conditions;
- overlap with useful GPU work;
- the delay before a restored request can actually decode.
The decision should compare end-to-end recovery time and resource opportunity cost, not just raw transfer bandwidth.
5. Select victims using more than cache size#
A naive victim policy evicts the request with the largest KV cache because it frees the most blocks. That can be a poor decision: a large request may be close to completion, while a smaller request may have a very long decode ahead.
A better victim score can consider:
- KV blocks released by preempting the request;
- estimated remaining output length;
- probability of completion soon;
- time already spent waiting;
- latency class and deadline;
- cost to recompute or restore its KV state;
- number of previous preemptions;
- whether the request is in a protected recovery period.
A conceptual score:
This ratio is only a starting point. A production scheduler should incorporate deadline and fairness constraints rather than maximizing one scalar score blindly.
Remaining-length prediction#
If the serving stack exposes suitable decoder hidden states or other low-overhead signals, a predictor may estimate how much output remains. This can help avoid evicting requests that appear close to completion.
However:
- hidden-state predictors are model- and workload-dependent;
- reasoning models can change output length unpredictably;
- prediction errors can systematically disadvantage certain request types;
- running a large predictor on every decode step may cost more than it saves.
Use sparse refresh, calibrated uncertainty, and fallback rules. If the estimate is unreliable, prefer robust age and service-history signals over false precision.
6. Make recovery productive with bounded waiting and protected decode#
A key scheduler design is to separate eligibility to resume from permission to immediately preempt again.
When a request is preempted:
- Record its preemption timestamp, output position, and preserved-state location.
- Place it in a recovery queue with an age or deadline.
- Restore its KV state when capacity becomes available.
- Give it a protected decode opportunity.
- Count fresh generated tokens as progress.
- Only after the protection condition is met should it return to the normal victim pool.
A simple protection rule might require one of:
- at least fresh tokens generated;
- a bounded decode-time quantum completed;
- a smaller request-specific progress threshold;
- completion or cancellation.
Do not count KV reload, prefix matching, or recomputation as fresh output progress. They restore prior work; they do not advance the response.
Why age-based readmission matters#
Without an age-based rule, a preempted request can wait indefinitely because newly active requests continually consume released blocks. This is starvation even if the scheduler is nominally fair among currently running requests.
Aging raises the priority of a request as its wait grows. A bounded-wait objective might be:
This is an operational target, not a mathematical guarantee unless the scheduler also reserves capacity or enforces a feasible service bound. If the GPU is fully saturated and all requests have unbounded KV growth, no priority formula alone can guarantee a finite wait.
Why protection must be bounded#
If a resumed request is protected forever, it can monopolize GPU capacity and force other requests into the same starvation pattern. Protection should be a finite decode quantum, followed by re-evaluation.
A useful policy:
- give the oldest eligible request a recovery slot;
- protect it until it generates a minimum fresh-token quantum or reaches a time cap;
- then return it to normal scheduling;
- ensure other waiting requests continue aging.
7. Use snapshots and contiguous host storage carefully#
A host-side KV store can become a second memory-management problem. A practical design should account for:
- pinned versus pageable host memory;
- exact snapshot size and block alignment;
- contiguous extents versus scattered allocations;
- metadata for request-to-block mapping;
- reference counts and lifetime;
- checksums or integrity validation where appropriate;
- cleanup after cancellation, timeout, worker failure, or client disconnect.
A snapshot has a fixed length at the moment it is created, even though the live request may continue to grow after it resumes. That makes exact-size host allocation possible. A contiguity-first allocator can reduce fragmentation and make large transfers easier to batch, but it needs a policy for reclaiming space when the host pool is full.
Bulk transfer can gather scattered GPU KV blocks into staging buffers, transfer contiguous ranges, and scatter them into new GPU blocks during restore. Double buffering can overlap one transfer with preparation of another. But overlap is beneficial only if it does not starve decode kernels or saturate the same memory subsystem.
Never assume that CPU RAM is a free extension of GPU memory. It is a bounded tier with its own contention, bandwidth, NUMA, and latency costs.
8. Numerical example: compare three recovery strategies#
Assume a serving pool is handling long reasoning requests. One request has:
- 12,000 tokens of accumulated context;
- 6 GiB of live KV state;
- estimated recomputation time of 1.4 seconds;
- measured save and restore time of 0.22 seconds each;
- 18 seconds of waiting before it can resume.
Compare three approaches:
| Strategy | Recovery work | Main risk |
|---|---|---|
| Recompute | 1.4 s + 18 s wait | repeated GPU compute |
| Offload/restore | 0.44 s + 18 s wait | host-memory and transfer contention |
| Snapshot + protected recovery | snapshot/restore cost plus wait, then protected decode quantum | snapshot staleness and protection capacity |
For this request, preserving the state saves about 0.96 seconds of direct recovery work versus recomputing, before considering overlap. But all strategies still incur the 18-second wait. The largest user-visible improvement may therefore come from bounded re-admission and protection, not from optimizing the copy by another 10%.
Suppose the scheduler restores the request, lets it generate 256 fresh tokens, and then re-evaluates it. If the request is preempted again, it has at least received a meaningful decode opportunity. The 256-token threshold is an illustrative policy choice; production thresholds should be tuned against latency class, decode speed, and memory pressure.
9. Production incident: high GPU utilization, poor completion time#
Scenario (illustrative): A reasoning endpoint launches a new model version. Its average output length increases, and a portion of requests now generate 10,000–20,000 tokens. The GPU KV pool stays near full.
The scheduler repeatedly preempts a set of long requests. Some requests wait 30–60 seconds, resume, generate a few dozen tokens, and are preempted again. The team observes:
- high GPU utilization;
- high aggregate tokens per second;
- rising P99 completion time;
- long gaps in streaming output;
- repeated preemption warnings;
- a growing tail of requests that remain unfinished long after most others complete.
The first mitigation increases the maximum concurrency cap downward. This reduces preemption but shifts delay to the admission queue and makes TTFT much worse.
The second mitigation enables CPU offload. Transfer overhead falls below recomputation for some long contexts, but simultaneous restores saturate host-device bandwidth and still do not guarantee that a restored request can keep decoding.
Root cause: the scheduler treated preemption as a one-time memory reclamation event. It had no bounded recovery queue, no protection after resume, and no progress-aware measurement. Requests repeatedly lost their turn.
Correction:
- Classify requests by latency class and expected output-length regime, using the reservation policy established in Question 290.
- Measure recompute versus offload break-even by context size and actual transfer load.
- Preserve KV for requests where the measured recovery savings justify host-memory use.
- Use age-based recovery priority to stop indefinite waiting.
- Give resumed requests a bounded fresh-decode quantum before they become eligible for another preemption.
- Limit concurrent restores to protect decode bandwidth.
- Monitor per-request stall duration and fresh tokens between preemptions.
- Canary the policy on long-output traffic and compare tail completion time and goodput.
The fix is not simply “turn on swapping” or “disable preemption.” It is a coordinated policy for victim selection, state preservation, re-admission, and guaranteed useful work.
10. Scheduler pseudocode#
The following is conceptual pseudocode, not a drop-in implementation. The serving engine must remain the authoritative owner of physical KV blocks and synchronization.
PYTHONdef choose_victim(running_requests, now, policy): candidates = [ r for r in running_requests if not r.in_recovery_protection and not r.non_preemptible ] for r in candidates: r.remaining_tokens = estimate_remaining_output(r) r.recovery_cost = estimate_recovery_cost( kv_bytes=r.kv_bytes, recompute_ms=r.recompute_ms, transfer_ms=r.transfer_ms, ) r.wait_age = max(0, now - r.last_resume_time) # Preserve near-complete requests where possible; among the rest, # free useful capacity without repeatedly selecting the same victim. return min( candidates, key=lambda r: policy.victim_score( blocks_freed=r.kv_blocks, remaining_tokens=r.remaining_tokens, recovery_cost=r.recovery_cost, previous_preemptions=r.preemption_count, deadline=r.deadline, ), ) def preempt(request, engine, host_pool, recovery_queue, policy): snapshot = None if policy.preserve_kv(request): snapshot = host_pool.try_store_snapshot( request.id, engine.export_kv_snapshot(request), ) if snapshot is None: engine.discard_kv(request) engine.release_gpu_kv_blocks(request) recovery_queue.enqueue( request_id=request.id, snapshot=snapshot, preempted_at=clock.now(), output_tokens_at_preemption=request.output_tokens, priority=policy.initial_recovery_priority(request), ) def recover_next(engine, host_pool, recovery_queue, policy): request = recovery_queue.oldest_eligible( age_weight=policy.age_weight ) if request is None: return None if request.snapshot is not None: restored = host_pool.restore_snapshot(request.snapshot, engine) else: restored = engine.recompute_request_state(request) if not restored: recovery_queue.defer_with_reason(request, "restore_capacity_unavailable") return None engine.mark_recovery_protected( request.id, max_fresh_tokens=policy.protected_token_quantum, max_protection_ms=policy.protection_time_cap_ms, ) return request.id def after_decode_step(request, engine, policy): if not request.in_recovery_protection: return fresh_tokens = request.output_tokens - request.output_tokens_at_resume if ( fresh_tokens >= policy.protected_token_quantum or request.protection_elapsed_ms >= policy.protection_time_cap_ms or request.is_finished ): engine.clear_recovery_protection(request.id)
Implementation requirements:
- Make state transfer and block release ordered. Do not free source blocks before the preservation copy has completed successfully.
- Restore into newly allocated GPU blocks; never assume a previous block address is still valid.
- Bound host snapshots and concurrent transfers.
- Handle partial copy failures, worker restarts, cancellation, and timeouts without leaking pinned memory.
- Make recovery queue operations durable enough for the failure model, or explicitly accept and test the consequences of losing in-memory queue state.
- Do not let protection bypass tenant quotas, deadlines, or hard safety limits.
- Ensure that a request which cannot be restored eventually receives a defined fallback: retry, recompute, route to a compatible pool, or fail with a clear terminal error.
11. Metrics that reveal whether preemption is productive#
Measure the full request lifecycle, not just the preemption counter.
Preemption
- preemptions per 1,000 requests;
- preemptions per request distribution;
- GPU KV blocks reclaimed per event;
- victim selection by request class and remaining-length estimate.
Recovery
- time from preemption to re-admission;
- KV save and restore bytes and duration;
- recomputation tokens and GPU time;
- restore failures and fallback counts;
- concurrent restore queue depth and transfer bandwidth.
Progress
- fresh output tokens after each recovery;
- time to first fresh token after restore;
- re-preemption interval;
- longest stall per request;
- fraction of request lifetime spent stalled or recovering;
- requests preempted repeatedly before producing a configured progress quantum.
User-facing outcomes
- P50/P95/P99 TPOT;
- P50/P95/P99 end-to-end completion time;
- TTFT, because recovery and admission policies can shift waiting earlier;
- goodput under the defined latency SLO;
- completion rate and timeout/cancellation rate.
Resource cost
- pinned host-memory occupancy;
- host-device bandwidth and copy-engine utilization;
- GPU compute spent recomputing;
- GPU KV occupancy and free-block watermark;
- CPU utilization and NUMA-local memory pressure.
A falling preemption count is not sufficient proof of improvement. A policy can reduce preemptions by delaying all requests before their first token. Compare queueing, TTFT, completion latency, and goodput together.
12. Test for thrashing before rollout#
Use trace replay with realistic arrival patterns and long-output tails. Include correlated bursts: many requests may become long together after a product launch or a new reasoning prompt.
Test:
- short conversational outputs mixed with long reasoning responses;
- very long prompts and long generated histories;
- repeated preemption of the same request;
- CPU memory pressure and pinned-memory exhaustion;
- PCIe/NVLink contention from other transfers;
- simultaneous restore storms;
- allocator fragmentation and partial snapshot failures;
- cancellation while preempted or while transferring;
- worker restart during save or restore;
- a request that repeatedly exceeds its output-length estimate;
- a request close to completion competing with a much longer request.
Compare at least:
- recomputation-only recovery;
- offload-and-restore recovery;
- offload with age-based re-admission;
- offload with age-based re-admission and bounded decode protection.
Use identical traces, model versions, hardware, and SLO definitions. Report tail metrics and confidence intervals. Do not compare one policy on short outputs with another on long outputs.
Roll out in stages:
- Instrument current preemption and recovery behavior.
- Replay historical traces offline.
- Run shadow victim selection and recovery scoring.
- Enable preservation for a small, long-output cohort.
- Add age-based recovery and protection behind independent feature flags.
- Increase traffic only if tail completion time, TPOT, TTFT, and goodput improve without exhausting host memory or transfer bandwidth.
- Retain a kill switch that returns to the engine's supported baseline recovery mode.
13. Common mistakes#
- Optimizing only the number of preemptions: fewer interruptions can simply mean more queueing before TTFT.
- Assuming swap is always better than recompute: transfer and synchronization costs can exceed the cost of rebuilding KV.
- Assuming recompute is always cheaper: long contexts and long generated histories can make repeated reconstruction very expensive.
- Choosing the largest KV request as the victim every time: it may be near completion and costly to recover.
- Restoring a request without protecting progress: it can be evicted again before producing meaningful output.
- Protecting a resumed request indefinitely: other requests can starve instead.
- Ignoring host-memory capacity: pinned memory is not unlimited and can harm the rest of the node.
- Launching all restores at once: transfer storms can damage decode latency for the entire pool.
- Counting restored tokens as new progress: only fresh generated output advances the user-visible response.
- Using a remaining-length predictor as ground truth: prediction uncertainty and distribution shift must be accounted for.
- Ignoring cancellations and worker failures: stale snapshots and recovery-queue entries can leak resources.
- Tuning only for average TPOT: repeated long stalls are a tail phenomenon; inspect per-request timelines.
14. How this relates to current serving systems and research#
The vLLM optimization documentation describes preemption when KV space is insufficient and notes that recomputation can adversely affect end-to-end latency. It documents monitoring preemption counts and tuning concurrency or memory allocation. The current V1 documentation identifies recomputation as the default preemption mode because it has lower overhead than swapping in that architecture. This is a runtime-specific statement, not a universal result for every model, context length, or hardware configuration.
The vLLM Ascend Preempt Offload guide documents a different path: preserve preempted decode-side KV blocks in CPU DRAM and restore them when the request is scheduled again, with recomputation as fallback when offload is unavailable. This illustrates that preservation can be integrated into a serving engine, but support and performance depend on the exact backend and deployment topology.
The November 2026 preprint *Making Preemption Productive in Long-Output LLM Serving* introduces Stint. It combines remaining-length-aware victim selection, a contiguous CPU snapshot pool, bulk KV transfer, age-based readmission, and protected fresh decoding. In its reported Qwen3-32B/H200 olympiad-math replay, the authors report 12.0% higher throughput and 50.7% lower P99 time per output token versus recomputation in the same engine, with no request pausing more than 50 seconds. These are results from the paper's evaluated workloads and setup, not a guarantee for other models or production traffic. The authors also report trade-offs: higher first-token and pooled inter-token latency tails, more pinned host memory, and no gain on some short-output workloads.
The lesson is that KV recovery is a scheduling problem as much as a storage problem. Preservation can save work, but bounded waiting and guaranteed fresh decode are what stop repeated recovery from becoming a starvation loop.
15. Interview-ready answer#
“When GPU KV memory is exhausted, a serving engine may preempt requests and either recompute their KV state later or offload it to CPU memory. Repeated eviction and recovery can cause KV thrashing: a request waits a long time, resumes briefly, generates very few tokens, and is evicted again. I would first measure per-request stall time, recovery cost, fresh tokens between preemptions, and the recompute-versus-transfer break-even point. Then I would select victims using released capacity, remaining work, recovery cost, and fairness; preserve KV only when measured transfer cost is lower than recomputation; and use bounded host-memory and restore concurrency. Most importantly, I would put preempted requests in an age-based recovery queue and protect each resumed request for a bounded decode quantum so it produces fresh tokens before becoming preemptible again. I would validate the policy with trace replay and monitor TPOT, TTFT, completion tails, goodput, restore bandwidth, and host-memory pressure.”
References
- 1.
- 2.vLLM Optimization and Tuning — Preemptiondocs.vllm.ai
- 3.vLLM Ascend Preempt Offload Guidedocs.vllm.ai
- 4.
Related questions
- How do you prevent head-of-line blocking when LLM requests have widely different prompt and output lengths?
- How should production LLM serving systems reserve and grow KV-cache capacity when output lengths are unknown, balancing preemption risk against stranded memory?
- How do you use the waiting request queue to schedule shared-prefix LLM requests and protect the KV cache from predictable eviction?
Explore other topics:Forward Deployed EngineeringDeep LearningRetrieval-Augmented GenerationAI Agents