Large Language ModelsInference & Performance Optimization
How do you use the waiting request queue to schedule shared-prefix LLM requests and protect the KV cache from predictable eviction?
Question 293 of 309 · Updated
On this page
- The key idea
- 1. Why cache-aware scheduling can still thrash
- 2. The waiting queue is a predictive data structure
- 3. Combine cache hits with future queue demand
- 4. A concrete numerical example
- 5. Co-design admission and eviction
- 6. Fairness: avoid starving singleton requests
- 7. Scheduling pseudocode
- 8. Where to build the integration
- 9. Failure scenarios and safeguards
- 10. Metrics that prove the policy helps
- 11. Production rollout plan
- 12. What recent research demonstrates
- 13. Interview-ready answer
The key idea#
A production LLM scheduler usually sees a queue of requests and a KV cache containing prefixes already computed by the serving engine. It may use first-come-first-served (FCFS), longest-prefix-match (LPM), or a cache policy such as least-recently-used (LRU).
There is a valuable signal between those two systems: the waiting queue itself reveals which prefixes are about to be reused.
If 20 queued requests share the same 4,000-token system prompt, admitting one request can pay the prefill cost once and allow the remaining requests to reuse that prefix. But if the scheduler interleaves unrelated requests, the shared prefix may be evicted before its siblings run. The cluster then pays the same prefill cost repeatedly.
The solution is not simply “use prefix caching.” It is to coordinate three decisions:
- Admission order: which waiting request should run first so that its siblings can reuse the work?
- Eviction protection: which cached blocks should remain resident because queued requests are likely to need them?
- Fairness: how do we prevent cache-locality optimization from indefinitely delaying requests with unique prompts?
This lesson focuses on queue-informed scheduling and eviction. It is different from basic prefix-cache eviction, cache-aware routing, or KV preemption: the input signal is the structure of requests that are waiting right now.
1. Why cache-aware scheduling can still thrash#
Assume a GPU can hold only one 2,000-token prefix in its available KV-cache budget. Eight requests arrive in this order:
- A1, B1, C1
- A2, B2, C2
- A3, B3
All A requests share prefix A, all B requests share prefix B, and all C requests share prefix C. The three groups are independent.
An arrival-order scheduler may do this:
- Prefill A for A1.
- Evict A and prefill B for B1.
- Evict B and prefill C for C1.
- Evict C and prefill A again for A2.
- Repeat.
The scheduler sees a cache miss for each request because the working set does not fit simultaneously and the requests are interleaved. Yet the queue contains enough information to avoid the repeated work.
A cluster-first order is:
A1, A2, A3, then B1, B2, B3, then C1, C2.
Now each distinct prefix is prefetched once and reused by its siblings before the cache moves to the next cluster.
For this deliberately simple example:
- Arrival-order execution performs 8 prefix prefills.
- Cluster-first execution performs 3 prefix prefills.
- Prefix prefill work falls by 62.5%.
This is an illustrative capacity-constrained example, not a guarantee for arbitrary traffic. Real schedulers must account for different prefix lengths, partial cache hits, decode memory growth, request deadlines, and concurrent batches.
2. The waiting queue is a predictive data structure#
A practical approach is to maintain a compressed radix tree (or prefix trie) over waiting prompts.
Each request is tokenized and inserted along its token-prefix path. Internal nodes track how many waiting requests share that prefix. A leaf or terminal marker identifies the request whose prompt ends there.
For example:
shared system prompt
/ \
product docs support docs
/ \ / \
R1 R2 R3 R4If a node has a pending count of four, four queued requests depend on that prefix. A deeper shared node identifies a more specific cluster.
Useful per-request signals include:
- Longest prefix match (LPM): how many prompt tokens are already present in the engine cache.
- Cluster size: how many queued requests share the request's deepest shared prefix.
- Ancestor demand: how much queued demand exists along the request's prefix path.
- Arrival age: how long the request has waited.
- Estimated prefill cost: the work avoided if this request's prefix becomes resident.
- Memory footprint: expected KV blocks consumed during prefill and decode.
- Deadline / priority class: the request's latency contract and service class.
A pending tree should be maintained incrementally:
- Insert a request when it enters the waiting queue.
- Remove it when admitted, cancelled, expired, or otherwise no longer pending.
- Update subtree counts along the changed path.
- Reconcile with the engine's actual cache state before scheduling.
A full rebuild on every scheduling tick wastes CPU and increases scheduling latency. An incremental tree keeps queue structure current at lower overhead.
3. Combine cache hits with future queue demand#
A scheduler that sorts only by current LPM is reactive. It knows what is cached now, but not how many waiting requests will benefit if a particular prefix is computed next.
A useful ranking is a policy, not a universal formula:
One interpretable score is:
For a request with a 3,000-token uncached shared prefix and 9 queued siblings, the potential avoided prefill is approximately 27,000 tokens after the pioneer computes the prefix, assuming all siblings have the same compatible prefix and the prefix remains resident. The first request is the pioneer; the others are siblings.
The exact score must avoid double-counting. If some tokens are already cached, count only the incremental shared suffix. If a sibling has a different adapter, model revision, tenant sharing domain, or other incompatible cache identity, do not count it as reusable demand. Queue structure must be built over compatible cache identities, not merely similar-looking text.
A useful priority order often distinguishes:
- Warm requests: already have a substantial reusable prefix in cache.
- Pioneers: first request in a high-demand uncached cluster; running it creates future reuse.
- Siblings: requests that can benefit from a pioneer’s newly computed prefix.
- Singletons: requests with no meaningful queued prefix sharing.
This classification is a starting point. It must be combined with resource feasibility and fairness.
4. A concrete numerical example#
Suppose a service has:
- 12 queued requests.
- 4,096 tokens of common system and policy prefix.
- Three document-specific branches, each with four requests.
- 2,048 tokens of unique suffix per request.
- A cache budget that can retain one branch's common prefix plus active decode state, but not all three branches at once.
A naive interleaved order may repeatedly evict branch A while serving B and C. The system may prefill the 4,096-token shared branch prefix four times instead of once.
A queue-aware schedule groups the requests by compatible prefix and serves one cluster at a time. If each branch-specific prefix is prefetched once:
- Naive: 12 × 4,096 = 49,152 prefix tokens of work.
- Clustered: 3 × 4,096 = 12,288 prefix tokens of work.
- Avoided prefill: 36,864 tokens, or 75%.
These are prefix-only calculations. They exclude unique suffix tokens, decode, cache transfer, scheduling overhead, and any partial hits. The production benefit must be measured in GPU time and SLO-compliant goodput, not inferred from token arithmetic alone.
If decode requests keep the cache occupied so that a prefix is evicted before the fourth sibling arrives, the realized savings will be lower. This is why admission and eviction must use the same demand signal.
5. Co-design admission and eviction#
A frequent design mistake is to add a queue-aware scheduler but leave eviction completely independent.
The scheduler may intentionally run a pioneer to create a reusable prefix. Then an LRU policy can evict that prefix because it was not touched recently, even though ten queued siblings are waiting for it.
The pending tree can inform both decisions:
Admission
- Prefer a pioneer when its prefix cluster has strong demand.
- Keep siblings reasonably close in scheduling order.
- Account for existing cache hits and estimated KV growth.
- Re-evaluate after each admission because the cache and queue have changed.
Eviction
- Identify cached blocks that are ancestors of pending shared prefixes.
- Estimate how many queued requests depend on each candidate block.
- Evict blocks with no pending demand before blocks with high pending demand.
- Preserve fairness and capacity for active decode, not only queued prefill.
A simple conceptual eviction score is:
where is the waiting queue and reflects request priority, age, or deadline. A block with high demand should be protected more strongly, provided it is valid and compatible with those requests.
A depth-weighted variant can give extra value to a block that is an ancestor of a large, deep shared subtree. But do not assume every ancestor block is equally valuable: a shallow block may be large, expensive to recompute, and shared by many branches, while a deep block may have only one dependent request.
The production implementation should use the cache engine's block metadata and reference accounting. It must never free a block that is pinned by an active sequence or in-flight transfer.
6. Fairness: avoid starving singleton requests#
Cluster-first scheduling has a failure mode: a large shared-prefix cluster can continually attract priority while a unique request waits.
A production scheduler needs a fairness lane.
One simple design maintains two ordered lanes:
- Locality lane: requests ranked by cache hits and expected prefix reuse.
- Fairness lane: requests ordered by arrival age, with deadline and priority adjustments.
Admissions are interleaved. For example, a controller may initially allocate 70% of scheduling opportunities to locality and 30% to fairness, then increase the fairness share as the oldest singleton approaches its waiting-time SLO.
Those percentages are configuration examples, not universal defaults. A controller should use observed queue age, singleton fraction, and deadline pressure, with smoothing and hard minimum service guarantees.
A useful invariant is:
> Every eligible request must have a bounded maximum wait, even when it has no reusable prefix.
Do not use a fairness lane that is only advisory. Enforce it in the admission mechanism, and test it under an adversarial workload where a large shared cluster keeps receiving new arrivals.
7. Scheduling pseudocode#
The following is an illustrative policy sketch. It omits engine-specific batching, CUDA stream coordination, distributed locking, and exact block allocation.
PYTHONdef on_arrival(request): request.cache_identity = resolve_compatible_cache_identity(request) pending_tree.insert( key=(request.cache_identity, request.prompt_tokens), request_id=request.id, arrival_time=request.arrival_time, ) waiting_queue.add(request) def scheduling_tick(cache, active_batch, now): candidates = [] for request in waiting_queue: hit_tokens = cache.longest_compatible_prefix( request.cache_identity, request.prompt_tokens, ) cluster = pending_tree.cluster_for( request.cache_identity, request.prompt_tokens, ) candidates.append({ "request": request, "hit_tokens": hit_tokens, "cluster_size": cluster.pending_count, "ancestor_demand": cluster.depth_weighted_demand, "age": now - request.arrival_time, "deadline_slack": request.deadline - now, "estimated_kv_bytes": estimate_kv_growth(request), }) if not any(c["cluster_size"] > 1 for c in candidates): return baseline_scheduler(candidates, active_batch) locality = rank_by_compatible_hit_and_reuse_value(candidates) fairness = rank_by_age_and_deadline(candidates) fairness_share = bounded_fairness_controller( singleton_fraction=fraction_of_singletons(candidates), oldest_wait=max_singleton_age(candidates), deadline_pressure=measure_deadline_pressure(candidates), ) ordered = stride_interleave( locality, fairness, fairness_share=fairness_share, ) admitted = [] for item in ordered: request = item["request"] if not memory_budget.can_admit( request, active_batch, reserve_decode_headroom=True, ): continue admitted.append(request) if batch_limits_reached(admitted): break for request in admitted: waiting_queue.remove(request) pending_tree.remove( request.cache_identity, request.prompt_tokens, request.id, ) return admitted def choose_eviction_victims(cache, pending_tree, bytes_needed): victims = sorted( cache.evictable_blocks(), key=lambda block: ( pending_tree.compatible_demand(block), block.recompute_cost, block.last_access_time, ), ) return take_until_enough_bytes(victims, bytes_needed)
Important production refinements:
- The compatibility identity must include all dimensions that affect KV validity and sharing permission.
- Do not mutate the pending tree before an admission is committed; roll back if allocation fails.
- Account for blocks already referenced by active sequences.
- Reserve decode headroom so a locality-optimized prefill does not trigger avoidable preemption.
- Recompute scores when a large admission changes the queue or cache.
- Bound scheduler CPU time and fall back safely when the queue is too large or the tree is stale.
8. Where to build the integration#
The queue-aware layer belongs at the boundary where the scheduler can inspect pending prompts and the engine can expose cache state.
A practical integration needs:
- Queue observer: receives request arrival, cancellation, deadline, and admission events.
- Pending-prefix index: incremental radix tree partitioned by compatible cache identity.
- Cache adapter: reports longest compatible prefix, block residency, refcounts, and evictable candidates.
- Admission policy: combines current cache hits with pending demand and fairness.
- Eviction hook: protects blocks with queued demand and selects low-value victims.
- Telemetry: records queue structure, scheduling decisions, cache outcomes, and SLO effects.
Avoid copying full prompts into a second scheduler service if token-prefix metadata is sufficient. Keep sensitive prompt content out of logs and metrics. If the scheduler is distributed, ensure the pending queue view is consistent enough for the policy: stale counts can protect blocks no request needs or evict blocks that are about to be reused.
A central scheduler may have a complete queue view but can become a bottleneck. A per-replica scheduler is cheaper but sees only local demand. A two-level design can route compatible prefix clusters to a replica, then schedule within that replica. That is a separate routing decision; do not conflate it with the local admission algorithm.
9. Failure scenarios and safeguards#
A. Cluster-first starvation
- Symptom: high cache hit rate while singleton P99 queue wait grows.
- Cause: locality dominates arrival age.
- Safeguard: fairness lane, oldest-request bound, deadline override, starvation alerts.
B. False prefix grouping
- Symptom: cache hit accounting claims reuse, but cached tensors are incompatible.
- Cause: grouping by token text alone while ignoring model revision, adapter, tenant domain, tokenizer, or KV representation.
- Safeguard: build clusters by the same compatibility identity used by the cache key.
C. Demand changes before execution
- Symptom: scheduler protects a prefix for a cluster that has since cancelled.
- Cause: stale queue-tree entries.
- Safeguard: update on cancellation and expiry; verify request membership at scheduling and eviction time.
D. Decode memory pressure
- Symptom: grouping improves prefill reuse but increases preemption or inter-token latency.
- Cause: too many cluster requests admitted without reserving decode headroom.
- Safeguard: joint admission budget for active KV, expected growth, and protected reserve.
E. Scheduler overhead
- Symptom: CPU scheduling time grows with queue length and delays dispatch.
- Cause: rebuilding or repeatedly traversing all prompt paths every tick.
- Safeguard: incremental compressed trie, bounded candidate set, cache-state short-circuit when no sharing exists, and baseline fallback.
F. No exploitable prefix structure
- Symptom: sophisticated policy produces no cache benefit.
- Cause: mostly unique prompts or incompatible prefixes.
- Safeguard: detect low sharing and fall back to FCFS or the engine's baseline policy.
G. Unbounded cluster growth
- Symptom: new arrivals continually extend a popular cluster and delay other work.
- Cause: locality policy treats the cluster as an unlimited batch.
- Safeguard: cap per-cluster admissions per scheduling window and interleave fairness opportunities.
10. Metrics that prove the policy helps#
Measure by workload class and model/cache identity:
- Prefix-cache hit rate and hit tokens, not just request hit count.
- Prefill GPU milliseconds avoided.
- TTFT P50/P95/P99.
- Time per output token (TPOT) and inter-token latency tails.
- End-to-end completion time.
- SLO-compliant goodput.
- Queue wait by cluster size and singleton status.
- Maximum and percentile wait of the oldest singleton.
- KV blocks protected due to pending demand.
- Evictions of blocks that were subsequently requested.
- Cache thrash rate: repeated recomputation of the same compatible prefix within a short window.
- Scheduler CPU time, tree update cost, and scheduling-cycle duration.
- Active decode memory headroom and preemption rate.
A cache hit-rate improvement alone is insufficient. If a policy doubles cache hits but violates P99 TTFT or starves unique requests, it is not a production win.
Use a controlled replay or shadow evaluation before rollout. Compare FCFS, cache-only LPM, and queue-informed scheduling under identical request traces, arrival times, model revisions, and KV budgets. Include workloads with strong shared prefixes, weak overlap, singleton-heavy traffic, bursts, cancellations, and mixed prompt lengths.
11. Production rollout plan#
- Instrument first. Build the pending-prefix index in observe-only mode and compare its predicted clusters with actual cache hits.
- Replay traces. Use real arrival order, cancellation, prompt lengths, decode lengths, and cache budgets.
- Enable locality ordering for a small cohort. Keep a hard fairness lane and a baseline fallback.
- Enable queue-aware eviction separately. Verify that protected blocks are actually reused before increasing protection.
- Canary under cache pressure. Test at realistic concurrency and memory headroom, not only warm-cache microbenchmarks.
- Compare SLOs. Require improvement in goodput or cost per compliant request without worsening tail latency or fairness beyond agreed limits.
- Expand gradually. Retain per-workload kill switches and automatic fallback when sharing disappears or scheduler overhead rises.
12. What recent research demonstrates#
PEEK (2026) studies this exact queue-visibility gap. It maintains an incremental radix tree over pending prompts, matches queued requests against the engine cache, admits prefix-sharing pioneers before siblings, protects cached blocks with pending demand, and adds a fairness lane for singleton requests.
Its reported experiments cover SGLang and vLLM, including shared-prompt chat, long-prefix RAG, multi-GPU workloads, and workloads with little exploitable prefix structure. The paper reports up to 3.0x/2.6x cache-hit improvement, 7.9x/7.1x TTFT improvement, and 3.6x/4.5x throughput improvement over the respective baselines on selected prefix-rich workloads. It reports near-baseline behavior on its tested low-sharing workloads. These are paper-specific experimental maxima, not universal production guarantees.
The practical takeaway is not to copy a paper's score weights or fairness percentages blindly. It is to expose pending queue structure to both admission and eviction, then validate the policy against your own traffic distribution and SLOs.
13. Interview-ready answer#
I would treat the waiting queue as a prediction of near-future KV-cache demand. I would maintain an incremental prefix trie over pending requests, partitioned by cache compatibility identity. At each scheduling cycle, I would combine each request's current longest-prefix hit with its queued cluster size and depth-weighted demand. I would admit a pioneer before its siblings so the prefill is reused, and use the same demand index to protect cache blocks those siblings will need. I would interleave a fairness lane based on age and deadline so unique prompts cannot starve. Finally, I would measure prefill work avoided, TTFT, TPOT, goodput, eviction regret, singleton wait, scheduler overhead, and decode memory headroom. I would roll out only if the policy improves SLO-compliant throughput without worsening fairness or tail latency.
References
- 1.
- 2.PEEK implementationgithub.com
- 3.vLLM Automatic Prefix Cachingdocs.vllm.ai
- 4.vLLM Prefix Caching Designdocs.vllm.ai
- 5.SGLang RadixAttentiongithub.com
Related questions
- How do you design modality-aware admission control and scheduling to prevent expensive image, audio, and video requests from starving latency-sensitive text and real-time speech inference?
- How do you design admission control and backpressure to prevent overload in production LLM inference?
- What is prefix-cache eviction, and how does cache memory pressure affect LLM inference performance?
Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents