MLOpsModel Deployment & CI/CD Automation
How do you design cache-aware request routing for production LLM inference to reuse GPU KV-cache state without sacrificing load balance and tail latency?
Question 146 of 164 · Updated
On this page
- Short answer
- 1. First distinguish the caches
- 2. Why ordinary load balancing is not enough
- 3. Build a routing decision from compatible cache state and live load
- Beginner-friendly numerical example
- 4. Normalize load and cache benefit carefully
- 5. Cache-state discovery and freshness
- 6. Treat stale cache state as a routing hint, not truth
- 7. Prevent cache locality from becoming a hot-worker problem
- 8. Session affinity, cache affinity, and fairness
- 9. When prefill and decode are disaggregated
- 10. Numerical production example: queueing versus recomputation
- 11. Failure scenarios and debugging
- 12. Monitoring and alerting
- 13. Engineering trade-offs
- 14. Common mistakes
- 15. CI/CD, load tests, and operational acceptance
- 16. Practical operating sequence
Short answer#
Route LLM requests using both the reusable KV-cache state available on each worker and that worker's current ability to accept more work. A router that only maximizes cache hits can send every request sharing a popular system prompt to one GPU, creating a hot replica while other GPUs remain idle. A router that only balances request counts can scatter related prompts across workers and repeatedly recompute the same prefix. Production routing therefore needs a measured trade-off: estimate the useful cached-token match, account for active work and queue delay, enforce worker eligibility and hard load limits, and fall back safely when cache-state information is stale or unavailable.
This lesson is about *routing requests to the right inference worker based on GPU-resident or distributed LLM KV state*. It is distinct from Q143–Q145, which cover application-level prediction-result caching: reusing completed outputs, keeping them correct, surviving cache outages, and sizing that result-cache fleet. KV cache stores intermediate attention state for continuing generation; it is not a cache of completed predictions.
1. First distinguish the caches#
A production LLM serving stack may have several different kinds of cache:
- Application prediction/result cache: stores a completed response for an equivalent request. Q143–Q145 cover correctness, resilience, and capacity for this cache.
- Prefix/KV cache: stores attention key/value tensors for tokens already processed by an inference engine. A later request with a compatible token prefix can reuse those tensors and avoid some prefill computation.
- Worker-local state: GPU memory, host memory, or local NVMe holding KV blocks available only to one worker or node.
- Distributed/tiered KV storage: a shared or remote tier that can make KV blocks available across workers, usually with additional transfer and lookup costs.
These caches have different keys, lifetimes, compatibility rules, and failure behavior. A router must never treat an application result-cache hit as equivalent to a KV-prefix hit. A result cache may return a completed answer; KV reuse only avoids recomputing part of the prompt and the model must still generate the continuation.
KV state is reusable only when the relevant execution characteristics match. Depending on the serving engine, compatibility can depend on model and revision, tokenizer, token IDs, adapter/LoRA identity, cache block format, attention configuration, parallelism layout, and other execution metadata. A router should use authoritative cache metadata from the serving engine or cache controller rather than guessing from raw prompt text.
2. Why ordinary load balancing is not enough#
Round-robin routing is simple and distributes requests evenly over time, but it can destroy locality. If ten users submit prompts with the same 3,000-token system prompt and requests are spread randomly across four workers, each worker may compute the shared prefix independently.
Session affinity improves locality by sending a conversation back to the same worker. But affinity is only a hint: the worker may have evicted the relevant KV blocks, restarted, become unhealthy, or be overloaded. Sticky routing based only on a session ID can therefore direct a request to a worker that no longer has the state.
Cache-aware routing asks which worker actually has the most reusable KV state. KV-aware routing can use reported cache state rather than assuming that a previous request means the cache is still present. This avoids a common error in prefix-affinity systems: continuing to route to a worker after the relevant cache has been evicted.
However, cache-only routing creates a new failure mode. A popular prefix may make one worker the preferred destination for a large share of traffic. The worker queues, its p99 latency rises, and its peers remain underused. A production router must balance cache reuse against current load.
3. Build a routing decision from compatible cache state and live load#
A practical routing pipeline should apply hard eligibility checks before scoring candidates.
Step 1 — Identify eligible workers
Exclude workers that are unhealthy, draining, incompatible with the requested model/adapter/runtime, missing required capabilities, or above a hard admission threshold. A worker with a high cache match but no available KV memory or no capacity for another request is not a valid target.
Step 2 — Estimate reusable prefix state
For each eligible worker, obtain the longest compatible cached prefix or matched KV-token count from a cache index, engine event stream, or controller. The result should include enough metadata to identify the model/cache namespace and the freshness of the observation.
Step 3 — Estimate current load
Use signals more meaningful than request count alone where possible:
- In-flight requests and queued requests.
- Estimated remaining prefill and decode work.
- Prompt and expected output token counts.
- GPU/KV-cache utilization and preemption pressure.
- Queue wait time and predicted completion time.
- Per-worker throughput and latency under the active model.
A 30-token request and a 20,000-token prompt should not be treated as equal work just because each contributes one active request.
Step 4 — Score candidates
A simple teaching model is:
score(worker) = cache_match_fraction − β × relative_load
where:
- cache_match_fraction = compatible cached prompt tokens / total prompt tokens, bounded from 0 to 1;
- relative_load = (worker load − fleet mean load) / max(1, fleet mean load);
- β controls how strongly the router penalizes load imbalance.
This is a useful conceptual model, not a universal production formula. Real systems may add queue-delay estimates, worker capacity, KV headroom, cache-state confidence, tenant fairness, or separate prefill/decode-stage scores. Hard limits must remain hard limits; a high score must never override an admission-control decision.
Beginner-friendly numerical example#
Suppose a fleet has three compatible GPU workers. A new request contains 4,000 prompt tokens.
- Worker A has 3,200 compatible tokens cached: cache match = 3,200 / 4,000 = 0.80.
- Worker B has 1,000 cached tokens: cache match = 0.25.
- Worker C has no matching prefix: cache match = 0.
Assume the fleet's average normalized in-flight load is 10 units. A is at 20 units, B at 8, and C at 5. Relative loads are therefore:
- A: (20 − 10) / 10 = +1.0
- B: (8 − 10) / 10 = −0.2
- C: (5 − 10) / 10 = −0.5
With β = 0.5:
- A score = 0.80 − (0.5 × 1.0) = 0.30
- B score = 0.25 − (0.5 × −0.2) = 0.35
- C score = 0 − (0.5 × −0.5) = 0.25
The router selects B. It gives up some cache reuse compared with A, but avoids sending more work to a worker already carrying twice the fleet-average load. C is less loaded, but its lack of cache reuse makes it slightly less attractive than B.
Now increase β to 1.0:
- A = −0.20
- B = 0.45
- C = 0.50
C becomes the preferred worker. This policy favors balancing more strongly and accepts a complete prefill recomputation. The correct β depends on the cost of prefill versus queueing, the workload's prompt lengths, and the service's latency objective. Tune it with representative traces and online metrics, not intuition alone.
4. Normalize load and cache benefit carefully#
A scoring function is only useful if its terms are comparable.
- Normalize cache benefit by prompt length or estimated prefill work. A raw count of 2,000 cached tokens means something different for a 2,500-token prompt than for a 30,000-token prompt.
- Normalize load relative to fleet capacity, not just fleet mean request count. A GPU with a larger model or lower throughput may be saturated at fewer requests.
- Consider separate prefill and decode pressure. Prefill is sensitive to prompt length and KV allocation; decode is sensitive to output length and sustained token generation.
- Penalize cache matches with low confidence or stale observations.
- Include a hard maximum queue delay and a maximum KV-memory threshold. A score must not route into an unsafe queue simply because the cached prefix is large.
For heterogeneous fleets, use capacity-weighted load. For example, 12 active requests on a worker that sustains 30 concurrent equivalent requests is not the same as 12 on a worker that sustains 10. Normalize by measured sustainable capacity for the model and hardware combination.
5. Cache-state discovery and freshness#
The router needs a view of which worker holds which KV blocks. Common approaches include:
- Engine event reporting: inference workers publish block allocation, insertion, eviction, and release events to a controller or event stream.
- Periodic state snapshots: workers report a summary or index of cached prefixes at intervals.
- Prefix estimation: the router tracks recent request prefixes and estimates where they may have been computed. This is cheaper to implement but can be wrong after eviction, restart, or memory pressure.
- Distributed KV index: a controller tracks remote KV blocks and their locations for tiered or shared caching.
Event-driven state can be more current, but event loss, reordering, and controller lag must be handled. Periodic snapshots are simpler but inherently stale between updates. A robust design includes worker incarnation IDs or epochs so events from a previous process lifetime cannot resurrect invalid cache entries.
A useful cache-location record can include:
- Worker ID and worker incarnation/epoch.
- Model, tokenizer, adapter, and KV-format namespace.
- Prefix or block identity and token range.
- Last-confirmed time and event sequence number.
- Residency tier (GPU, host, local NVMe, remote tier).
- Approximate size and whether the block is pinned, evictable, or being transferred.
Do not store raw prompts in the router index unless there is a compelling, reviewed privacy and security reason. Use token/block hashes or opaque identifiers, apply tenant and model namespaces, and restrict access to routing metadata.
6. Treat stale cache state as a routing hint, not truth#
A cache index may say that worker A has a prefix even though A evicted it milliseconds ago. Or the index may say a worker lacks a prefix because the event that announced the insertion has not arrived yet.
This is a normal distributed-systems race. The serving engine remains authoritative at request execution time.
Design for it:
- Give cache-location records a bounded freshness window.
- Process events idempotently and reject older sequence numbers.
- Invalidate all state associated with a worker epoch when the worker restarts.
- Treat a reported cache miss as a normal outcome, not a correctness failure.
- Record predicted match versus actual matched tokens to measure index accuracy.
- Avoid blocking the request on a synchronous full-fleet cache probe if the probe costs more than the expected prefill savings.
- Fall back to load-aware routing when cache metadata is absent, stale, or unavailable.
A stale cache index should cause some lost optimization, not a failed inference request. Never return a prior user's KV state just because a key collision or namespace bug made it appear compatible.
7. Prevent cache locality from becoming a hot-worker problem#
Popular shared prefixes can attract a disproportionate share of requests. Examples include a common system prompt, a shared RAG document set, or a frequently used agent instruction template.
Use load-aware cache affinity rather than unconditional affinity:
- Keep a request on a warm worker while its queue and KV utilization remain healthy.
- Spill to a less-loaded worker when the warm worker exceeds a defined queue, utilization, or predicted-wait threshold.
- Prefer a worker with a partial cache match when the saved prefill is still meaningful and its load is acceptable.
- Use a least-loaded or power-of-two fallback when no worker has useful cache state.
- Apply per-tenant fairness so one tenant's popular prefix cannot monopolize a worker.
- Use admission control to prevent the router from overfilling GPU KV memory with new long prompts.
A two-choice policy can reduce coordination overhead: sample two eligible workers and choose the better score. It may not find the globally best cache holder, but it can reduce the cost of collecting exact load information from every worker. Whether that is appropriate depends on cache-index availability and fleet size.
8. Session affinity, cache affinity, and fairness#
These policies solve related but different problems:
- Session affinity preserves conversation locality by mapping a session to a worker. It is simple, but may keep routing to a worker after the cache has disappeared.
- Prefix/cache affinity directs requests to workers likely to hold shared prompt state. It can help across sessions, but popular prefixes can create hot spots.
- KV-aware routing uses observed KV state rather than only a session or prefix estimate.
- Load-aware KV routing explicitly trades cache reuse against queueing and worker load.
- Least-loaded routing protects latency and distributes work but may sacrifice cache locality.
For multi-turn conversations, session affinity may still matter for application state, tool state, or conversation sequencing even if KV state is distributed. Do not rely on GPU cache residency as the only store of conversation history. The application must be able to reconstruct the request independently.
Fairness should be explicit. Possible controls include per-tenant concurrency caps, weighted fair queues, request-cost estimates, reserved capacity for latency-sensitive traffic, and separate pools for large-context or batch requests. Cache affinity must not let a high-volume tenant monopolize the only worker holding a shared prefix.
9. When prefill and decode are disaggregated#
Some serving architectures use separate prefill and decode worker pools. The router then makes at least two related decisions:
- Select a prefill worker based on reusable prompt/KV state, prompt length, current prefill load, and available KV memory.
- Select a decode worker based on decode capacity, active sequences, expected output length, and transfer/connectivity constraints.
A cache-aware prefill decision does not automatically imply that the same worker should decode. The KV transfer path, supported cache layout, and decode worker's ability to consume the state must be compatible. In disaggregated systems, the cost of moving KV state can outweigh the benefit of a cache hit if the transfer is large or the destination is remote.
Measure end-to-end latency, including cache lookup, routing, KV transfer, prefill, and decode. Optimizing only the prefill stage can make the overall request slower if it creates an expensive transfer or congested decode queue.
10. Numerical production example: queueing versus recomputation#
Assume a service has four identical GPU workers. Each can sustain 100 units of measured prefill/decode work per second under the target latency SLO. A popular 6,000-token prefix is cached on worker A. During a traffic burst, 70 requests per second share this prefix, and cache-only routing sends nearly all of them to A.
Suppose A's safe capacity is 100 work units per second, but existing decode work already consumes 75 units. The new requests add 50 work units per second. A now receives 125 units against a safe capacity of 100, so queueing grows. Workers B, C, and D remain underutilized.
A load-aware router could keep 40 requests per second on A while spilling 30 to B, C, and D. Those spillover requests recompute the prefix, but queueing is bounded and total fleet capacity is used. If the shared prefix is expensive, the router may choose a higher cache-affinity weight; if the latency SLO is at risk, it should spill sooner.
This example uses abstract work units to avoid pretending every token has identical GPU cost. In a real deployment, derive the unit from measured prefill and decode throughput for the model, hardware, quantization, and context-length distribution. Verify the policy with production-shaped load tests.
11. Failure scenarios and debugging#
Scenario A: Popular system prompt overloads one GPU
- Symptom: one worker's queue and p99 latency rise while peers are idle; cache hit ratio is high.
- Cause: cache-only affinity overvalues a shared prefix.
- Debug: compare per-worker request share, matched tokens, queue delay, KV utilization, and cache-hit rate.
- Fix: enable load-aware scoring, set hard queue/KV limits, and tune cache-affinity weight with a replayed trace.
Scenario B: Router keeps selecting a worker after its cache was evicted
- Symptom: predicted cache hit is high, but actual matched tokens are low; prefill time rises.
- Cause: stale or incomplete cache index, lost eviction events, or missing worker epoch handling.
- Debug: compare event sequence, worker restart time, reported residency, and engine-reported match.
- Fix: expire stale entries, use monotonic event sequence/epochs, and fall back to load-aware routing when confidence is low.
Scenario C: Cache-aware routing is slower than round-robin
- Symptom: cache hit ratio improves but end-to-end p95/p99 gets worse.
- Cause: cache lookup and controller overhead, queueing on warm workers, or remote KV transfer costs exceed saved prefill.
- Debug: trace routing lookup, transfer, queue, prefill, and decode spans separately.
- Fix: reduce lookup fan-out, cache routing metadata briefly, spill earlier, and compare the saved prefill time with the total routing/transfer penalty.
Scenario D: Restarted worker receives requests for old KV state
- Symptom: router repeatedly predicts hits for a worker that has just restarted; actual cache misses surge.
- Cause: worker identity reused without an incarnation identifier or old events processed after restart.
- Debug: inspect worker epoch, event ordering, and cache index cleanup.
- Fix: assign a new epoch on each process lifetime and discard cache records from older epochs.
Scenario E: One tenant monopolizes a warm prefix
- Symptom: a single tenant's traffic dominates the worker holding the prefix; other tenants see high queue delay.
- Cause: routing optimizes global cache hits without tenant fairness.
- Debug: segment queue delay, cache reuse, and worker share by tenant and traffic class.
- Fix: enforce tenant concurrency/weight limits and reserve capacity for other classes. Avoid exposing another tenant's prompt or cache metadata.
Scenario F: Disaggregated prefill selects a warm source but transfer stalls
- Symptom: prefill compute is reduced, but request latency increases during KV movement.
- Cause: source/destination topology, transfer bandwidth, or decode admission is constrained.
- Debug: measure bytes transferred, transfer queue, source/destination utilization, and decode wait.
- Fix: include transfer cost and destination readiness in the route score; recompute when moving the KV state is more expensive than prefill.
12. Monitoring and alerting#
Measure routing decisions and actual execution outcomes together.
- Per-worker request share, in-flight work, queue depth, and queue-wait p50/p95/p99.
- Predicted cache-match tokens and actual reused tokens.
- Cache-index age, event lag, dropped/out-of-order events, and stale-record rate.
- Prefix/KV hit rate, matched-token ratio, KV block eviction, preemption, and GPU memory headroom.
- Prefill duration, decode tokens per second, time to first token, inter-token latency, and end-to-end latency.
- KV transfer bytes, duration, retries, and failures for remote/tiered or disaggregated deployments.
- Router lookup latency, score distribution, chosen-worker reason, fallback rate, and routing decision overhead.
- Per-tenant queue delay and capacity share, with privacy-safe aggregation.
Useful alerts include:
- A worker exceeds its queue or KV-memory safety threshold.
- Predicted-to-actual cache-match accuracy falls below its baseline.
- One worker receives a disproportionate share of traffic while other eligible workers are idle.
- Cache-index event lag exceeds the configured freshness budget.
- Cache hit ratio rises while p99 latency also rises, indicating locality is creating queueing.
- KV transfer time consumes a material share of the latency budget.
Do not alert on hit ratio alone. A cache hit is valuable only when it reduces total request cost or latency without harming fairness or reliability.
13. Engineering trade-offs#
- Cache locality vs load balance: stronger affinity saves prefill but can create hot workers; stronger balancing improves queueing but recomputes more prefixes.
- Exact cache state vs routing overhead: engine-reported KV metadata is more accurate but adds event/index complexity; estimated prefix maps are cheaper but can become stale.
- Global scoring vs sampled candidates: global scoring may find a better destination but requires more state collection; sampled choices scale more easily but may miss the best cache holder.
- Session stickiness vs cache-aware selection: stickiness simplifies conversation locality; actual cache-aware routing adapts to eviction and changing worker state.
- Remote KV reuse vs recomputation: remote reuse saves GPU prefill but adds transfer and coordination cost. Recompute can be faster for short prefixes.
- Fairness vs aggregate throughput: global cache efficiency can favor popular tenants; tenant-level quotas may reduce total hit ratio while improving predictable service.
- Router complexity vs simple fallback: advanced routing helps high-reuse workloads but should degrade to a tested load-aware or least-loaded policy when cache metadata is unreliable.
14. Common mistakes#
- Confusing completed prediction-result caching with intermediate LLM KV caching.
- Routing by raw prompt text without tokenization and execution-compatibility checks.
- Assuming a session-affinity mapping proves the KV blocks are still resident.
- Optimizing cache-hit ratio while ignoring queueing, p99 latency, or GPU preemption.
- Treating request count as a complete measure of worker load despite different prompt/output lengths.
- Using stale cache-index entries after worker restart or cache eviction.
- Allowing cache affinity to bypass hard admission limits or tenant fairness.
- Ignoring transfer latency in tiered or prefill/decode-disaggregated deployments.
- Logging raw prompts or sensitive cache identifiers in routing diagnostics.
- Failing to provide a non-cache-aware fallback when the controller is unavailable.
- Tuning the affinity weight on synthetic uniform prompts instead of realistic skewed production traces.
15. CI/CD, load tests, and operational acceptance#
Routing policy and cache-state integration should be tested as part of the model-serving release.
- Compatibility tests: verify that model, tokenizer, adapter, runtime, and KV-format mismatches never receive cache-hit credit.
- Event-order tests: deliver duplicate, delayed, reordered, and missing cache events; verify epochs and sequence numbers prevent stale state resurrection.
- Eviction tests: evict KV blocks after the router observes them; confirm the engine miss is handled normally and the router updates its estimate.
- Load-skew tests: send a burst of requests sharing one popular prefix; verify the router spills to healthy workers before queue SLOs are violated.
- Mixed-workload tests: mix short prompts, long contexts, long generations, and different tenant classes; confirm that request count alone does not dominate scoring.
- Fairness tests: flood one tenant or prefix and confirm per-tenant limits preserve service for other traffic.
- Controller-outage tests: stop or delay the cache index/controller; confirm routing falls back to a safe load-aware policy without blocking inference.
- Worker-restart tests: restart a worker and replay delayed events; verify old cache records are invalidated by epoch.
- Disaggregated-transfer tests: inject transfer latency and failure; confirm the router chooses another path or recomputation when it is cheaper.
- Regression benchmarks: compare round-robin, session-affinity, cache-only, and load-aware KV routing on the same trace. Record hit tokens, prefill time, queue delay, TTFT, p99, throughput, and GPU utilization.
- Canary rollout: deploy the new routing policy to a small traffic slice, compare against the baseline, and roll back if p99, fairness, or error budgets regress.
- Configuration validation: validate affinity weight, freshness TTL, worker eligibility, hard queue thresholds, and fallback behavior before deployment.
A release is acceptable only when the router demonstrates that it can exploit real cache locality, recognize stale state, avoid hot-worker overload, preserve tenant fairness, and meet end-to-end latency objectives under both normal and burst traffic.
16. Practical operating sequence#
- Enable and validate engine-side prefix/KV caching on the target model.
- Instrument actual matched-token counts, evictions, and per-worker load.
- Start with a simple load-aware baseline and establish latency/throughput measurements.
- Add cache-state discovery with worker epochs and bounded freshness.
- Introduce cache-aware scoring with hard admission and fairness controls.
- Replay skewed production traces and tune the cache-versus-load weight.
- Test controller delay, worker restart, eviction, and remote-transfer failures.
- Canary the policy and compare end-to-end outcomes against the baseline.
- Keep a tested load-aware fallback and document the operational runbook.
The objective is not to route every request to the worker with the most cached tokens. It is to minimize total serving cost and latency across the fleet while keeping workers balanced, state compatible, and users fairly served.
References
- 1.KV Cache Aware RoutingvLLM Production Stack Documentation
- 2.Load Aware RoutingvLLM Production Stack Documentation
- 3.vLLM Router load balancing policiesvLLM Project
- 4.KV caching and intelligent routingAWS Documentation
- 5.Amazon SageMaker AI real-time endpoints now support KV cache aware routingAWS Machine Learning Blog
- 6.System-level optimizationsAWS Prescriptive Guidance
Related questions
- How do you design dynamic batching, deadline-aware scheduling, and fair concurrency for production ML inference?
- How do you design safe prediction-result caching for production ML inference without serving stale or cross-tenant results?
- How do you design autoscaling and capacity planning for production ML inference services?
Explore other topics:Machine LearningRetrieval-Augmented GenerationAI Agents