Externalizing Distributed KV Cache for Stable LLM Inference

    This article explains how to externalize KVCache from compute nodes to improve LLM inference stability and cost control. It covers capacity estimation, Kubernetes role-group orchestration prerequisites and challenges, topology-aware scheduling, in-place upgrades and cache persistence, and practices for warmup, cross-request sharing, observability, and chaos testing. It also outlines a phased adoption roadmap and cases where externalization is not appropriate.

    1. Why Move KVCache Out of Compute Nodes

    As large language models are deployed at scale in scenarios such as customer service, code generation, and complex agents, the core problem in inference serving has shifted from “whether the model can run” to “how to control cost under latency and throughput constraints.” As model size grows, GPU memory pressure increases, and KVCache is often the largest dynamic consumer of memory.

    KVCache size is determined by both model architecture and context length and can be estimated with the following formula:

    KVCache bytes = 2 × layers × KV heads × head dimension × bytes per element × tokens

    For models using grouped-query attention (GQA), the number of KV heads is smaller, so the per-session footprint is clearly lower than that of multi-head attention models. When the context window extends to 128K, a single session’s KVCache can still reach several GB or more. Teams should measure with the target model rather than relying only on rules of thumb.

    If KVCache is recomputed for every request, or frequently swapped between GPU memory and host memory, the latency penalty quickly exceeds an acceptable range. An externalized architecture places KVCache in an independent distributed storage cluster, and compute nodes only handle inference. This approach mainly provides three capabilities.

    1. Cross-request cache sharing: In retrieval-augmented generation and long-document analysis, system prompts and document prefixes are often repeated. A cache cluster allows different sessions to reuse the KVCache for the same prefix, reducing repeated prefill. Sharing has prerequisites, as described in Section 4.
    2. Elastic scaling and fault isolation: The cache layer and compute layer scale independently. If a cache node fails, online service can degrade to recomputation, but cache loss still increases latency. Therefore, cache availability must be guaranteed through multiple replicas.
    3. Tiered storage: Hot and cold data can migrate among memory, local NVMe, and object storage to balance performance and cost.

    2. Prerequisites and Common Challenges Before Deployment

    One concept needs to be clarified first. Role-group orchestration is not a native Kubernetes API. Deployments and StatefulSets are designed around homogeneous replicas and cannot directly express the coordination among prefill, decode, and cache roles. Implementing role groups usually requires extending Kubernetes through custom resource definitions (CRDs) and an Operator, with a controller coordinating the lifecycle of each role.

    Before deployment, confirm the following conditions.

    • The Kubernetes cluster version matches the compatibility matrix of the selected Operator.
    • Permissions are available to install CRDs and the Operator, usually requiring cluster administrator involvement.
    • The scheduler supports topology constraints, such as node affinity and topology spread constraints.
    • The storage class supports persistent volume claims (PVCs) and can meet the bandwidth requirements for cache reads and writes.
    • The GPU device plugin is deployed, and drivers and runtimes are consistent across nodes.

    Deployment usually involves three types of challenges.

    • Topology affinity: When prefill nodes are too far from cache nodes, network hops increase and throughput may decrease. The scheduler needs to be aware of cache shard locations.
    • Lifecycle coordination: When cache nodes are rebuilt, compute nodes should not be restarted in a cascading manner, and vice versa.
    • Scaling differences: The cache cluster should scale based on hit rate and storage watermark, while compute nodes should scale based on queue length and GPU utilization. A unified policy can hardly satisfy both.

    3. Design Considerations for Role-Group Orchestration

    3.1 Role Definitions and Unified Management

    A role group brings prefill nodes, decode nodes, and cache nodes into the same orchestration object. The three roles share a lifecycle baseline and scheduling namespace while retaining their own replica counts and scaling configurations.

    The fields below are only for illustrating the design approach. Actual field names are subject to the documentation of the Operator in use.

    1. roles:
    2. - name: prefill
    3. replicas: 4
    4. topologyConstraint: sameZoneAsCache
    5. upgradeStrategy: rolling
    6. - name: decode
    7. replicas: 8
    8. upgradeStrategy: rolling
    9. - name: kvcache
    10. replicas: 3
    11. topologyConstraint: spreadAcrossRacks
    12. upgradeStrategy: inPlace
    13. persistence:
    14. volumeClaim: kv-nvme-pvc
    15. snapshotInterval: 5m

    The cache role can periodically persist KVCache to disk and load it directly after a node restart, avoiding full recomputation. The persistence scheme needs to clarify the following points.

    • Persistence frequency: This should be determined through stress testing. A shorter interval provides a fresher recovery point but incurs greater I/O overhead.
    • Consistency: Snapshots should be taken at a safe checkpoint of the engine. Capturing in the middle of a write may result in incomplete cache blocks.
    • Recovery boundary: Recovery can only return to the latest snapshot. Cache generated after the snapshot still needs to be recomputed.
    • I/O and latency overhead: Persistence consumes storage bandwidth and may affect online read/write latency. Rate limiting is recommended.

    The persistence scheme is not suitable for two scenarios. One is high-frequency write scenarios where every token needs to be written to disk. The other is scenarios that require full cache persistence. In these two scenarios, the cost of persistence may far exceed the cost of recomputation.

    3.2 Topology Awareness and Affinity

    A role group can declare the topology relationship between cache nodes and compute nodes as scheduling constraints. The scheduler places prefill nodes in appropriate availability zones or racks based on cache shard locations.

    Teams should verify the benefits of topology scheduling themselves. Tests need to record the following conditions: GPU and network hardware models, concurrency, cache hit rate, network hops between nodes, and separate P50 and P99 read latency statistics. Compare results between same-rack and cross-rack scenarios before deciding whether to enable hard constraints.

    3.3 In-Place Upgrades and Cache Keep-Alive

    Rolling upgrades are a major source of stability risk. Role groups support in-place upgrades to retain runtime state on nodes as much as possible and reduce cache rebuilds.

    Note that the retention scope of in-place upgrades is limited.

    • KVCache stored in local NVMe or PVCs can survive container replacement.
    • KVCache stored in process memory is lost after a container restart.
    • Hot updates or double buffering (new and old instances running in parallel, switching traffic, and then recycling old instances) can preserve memory state in some scenarios, but this depends on support from the inference engine.

    Before an upgrade, the system should automatically take a snapshot. The snapshot duration should be recorded and compared with the recovery time objective (RTO) to confirm that recovery can be completed within the agreed time. After the upgrade, check changes in cache hit rate and sample outputs for the same requests before and after the upgrade. If validation fails, roll back to the previous image version and restore the cache from the snapshot.

    4. Practical Path to Stability and Performance

    4.1 Cache Warmup and Graceful Removal

    Before traffic is cut over, KVCache for high-frequency prompt templates can be warmed up. Warmup content must be bound to the model version. After model weights or the tokenizer change, the old cache cannot continue to be used.

    When a cache node is taken offline, its shards should first be copied to other nodes or set to read-only. The node should be recycled only after all in-flight requests that depend on the shard have finished. This avoids large-scale recomputation caused by a node suddenly disappearing.

    4.2 Prerequisites and Risks of Cross-Request Sharing

    Before cross-request sharing, the following prerequisites must be met.

    • Same model weights.
    • Same tokenizer.
    • Same positional encoding configuration.
    • Same attention implementation and numerical precision.

    If these prerequisites are not met, the cache cannot be reused. Forced reuse will cause incorrect output.

    In multi-tenant environments, cache keys should include tenant identifiers, or only public system prompts should be shared. Cache content may contain user input, so it should be encrypted at rest and assigned a retention period. Before cross-tenant sharing, permission checks and privacy risk assessments must be completed.

    4.3 End-to-End Observability

    A distributed inference system needs to cover both the compute layer and the cache layer. The following metrics are common starting points. Thresholds need to be adjusted according to baselines and SLOs.

    Metric Collection path Example threshold (adjust per business)
    Cache hit rate Counters in the cache service A drop of more than 10 percentage points from baseline lasting 5 minutes triggers a P2 alert
    Cache read/write latency Client instrumentation and server-side histograms P99 exceeds the SLO and triggers a P1 alert
    Cross-node transfer volume and time Traffic statistics from network devices or the CNI Bandwidth usage exceeds 70% of link capacity and triggers a P3 alert
    Miss recompute frequency Prefill logs from the inference engine A sudden increase in recomputations per minute triggers a P2 alert
    P99 curve during upgrades Latency data from the gateway or service mesh Deviation from the pre-upgrade baseline exceeds the agreed value and triggers a P1 alert

    Dashboards can be organized into three groups: compute, cache, and network. Each group should contain trend charts, current values, and alert status. Operators should be able to quickly determine the source of performance degradation from the dashboard: insufficient compute resources, uneven cache distribution, or network congestion.

    4.4 Failure Drills and Chaos Engineering

    Drills should be conducted under controlled conditions rather than relying only on random outages. The following steps should be completed before execution.

    1. Approval: Complete change review, and have the on-call lead confirm the window.
    2. Limit the blast radius: Affect only a single availability zone or a subset of replicas for a single role each time.
    3. Set rollback conditions: If the error rate exceeds the threshold or P99 continues to worsen, stop the drill immediately and recover.
    4. Confirm backup availability: Check whether the latest snapshot is complete before the drill, and regularly validate the recovery process.

    Scenarios covered by drills include cache node outages, network partitions, and upgrade interruptions. After each drill, record recovery time, cache rebuild duration, and user impact scope, and update configurations accordingly.

    5. Phased Evolution Roadmap

    Teams can proceed in the following three stages, with clear exit criteria for each stage.

    Stage 1: Single-role externalization. Migrate only KVCache to an independent cache service, while compute nodes keep their existing deployment model. The exit criterion is that cache hit rate remains stably above baseline and read P99 is lower than the recomputation time for the same request.

    Stage 2: Multi-role orchestration adoption. Introduce role groups and enable topology constraints and in-place upgrades. The exit criterion is that P99 jitter during rolling upgrades stays below the agreed SLO, and cache loss can be quantified and tracked.

    Stage 3: Tiered storage and disaster recovery. Add hot/cold tiering and deploy cache replicas across availability zones. The exit criterion is that when a single availability zone fails, the service can recover within the agreed RTO, and the error rate during degradation remains within budget.

    The externalized architecture is not suitable for the following scenarios: services with short contexts, low concurrency, and persistently low cache hit rates, as well as teams lacking Operator operations capabilities. In these scenarios, single-node deployment with a simple recomputation strategy is usually easier to maintain.