Compute Bottlenecks and KV Cache Management in LLM Inference
This article explains where compute and memory bottlenecks arise during large language model inference, covering the distinct resource profiles of the prefill and decode phases, how to estimate KV Cache memory consumption and concurrency limits, three session caching strategies, and scheduling techniques such as continuous batching and chunked prefill that improve GPU utilization.
1. Background
In chat-oriented LLM serving, how many users a single accelerator card can serve concurrently often determines service cost and user experience more directly than the model’s parameter count. When resources are tight, operators must trade off between admitting more new requests and preserving response quality for existing sessions. Understanding this trade-off requires a clear picture of how different resources are consumed during inference.
2. The Two Phases of Inference and Their Resource Profiles
2.1 The Prefill Phase
The model reads the user’s input together with the conversation history in a single pass and computes the key-value vectors for every input token. This phase is compute-intensive, and its latency scales roughly linearly with input length. Because the attention computation grows quadratically with input length, time to first token rises noticeably for very long contexts.
2.2 The Decode Phase
The model generates output tokens one at a time. Producing each token requires reading the KV vectors of all preceding tokens. The per-step computation is small, but the volume of memory reads is large, so this phase is typically bounded by memory bandwidth and GPU compute utilization stays low.
This characteristic implies that keeping more decode requests in the batch at the same time is the primary way to improve hardware utilization.
2.3 The Role of KV Cache
The KV Cache stores previously computed key and value vectors, avoiding redundant recomputation of the history each time a new token is generated. It trades space for time: the cost is that memory usage grows linearly with context length and the number of concurrent sessions.
3. Estimating Memory Usage and the Concurrency Ceiling
The bytes occupied per token in the KV Cache can be estimated as:
KV bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element
The factor of 2 accounts for the separate key and value caches. The following is an example configuration, not the parameters of any specific model: 32 layers, 8 KV heads, head dimension 128, stored in 16-bit floating point. The per-token footprint is 2 × 32 × 8 × 128 × 2 = 131,072 bytes, about 128 KiB. A session with 4,096 tokens therefore occupies roughly 512 MiB of KV Cache.
From this, the concurrency ceiling can be roughly estimated:
Concurrent sessions ≈ (available memory − model weight footprint − runtime overhead) ÷ per-session KV footprint
Illustrative code:
def estimate_max_sessions(gpu_mem_gib, weight_gib, runtime_overhead_gib,layers, kv_heads, head_dim, bytes_per_elem, avg_context_tokens):bytes_per_token = 2 * layers * kv_heads * head_dim * bytes_per_elemper_session_gib = bytes_per_token * avg_context_tokens / (1024 ** 3)free_gib = gpu_mem_gib - weight_gib - runtime_overhead_gibif free_gib <= 0 or per_session_gib <= 0:return 0return int(free_gib // per_session_gib)# Example: 80 GiB of GPU memory, 16 GiB of weights, 4 GiB of runtime overhead,# average context of 4096 tokens# Per session is about 0.5 GiB, so the theoretical concurrency is 60 / 0.5 = 120
This result is only a theoretical upper bound. Real deployments must also account for memory fragmentation, traffic bursts, and scheduling overhead, so a safety margin is usually reserved.
The formula also shows that the concurrency ceiling is highly sensitive to average context length. Doubling the average context roughly halves the concurrency ceiling. As a result, the same hardware can serve several times more users under a “mostly short Q&A” workload than under a “mostly long-document conversation” workload.
4. Three Strategies for Session Caching
Session characteristics determine the value of caching. One-off Q&A has almost no reuse value. Multi-turn conversations with continuous interaction over a short period have high reuse value. For sessions that resume only after a long interval, the reuse window has usually expired.
| Strategy | Approach | Memory usage | Recovery latency | Suitable scenarios |
|---|---|---|---|---|
| Long-term retention | Session KV stays resident in GPU memory | High | Low | High-frequency continuous interaction |
| Tiered offloading | Cold data is moved to host memory or local SSD and loaded back when needed | Medium | Medium, depends on I/O bandwidth | Moderate reuse probability, moderate intervals |
| Evict and recompute | KV is released; on resumption, prefill is rerun over the history | Low | High, grows with history length | Infrequently accessed sessions with short histories |
The core trade-off among the three strategies: offloading trades I/O cost for memory, while recomputation trades compute cost for memory. Recomputation cost is proportional to history length, so recomputing long sessions is expensive. In practice, systems usually make decisions based on length thresholds—for example, recompute short histories directly and prefer offloading for long histories.
Below is illustrative code for tiered cache management, with concurrency control and error handling omitted:
from collections import OrderedDictclass SessionKVManager:def __init__(self, gpu_budget, host_budget):self.gpu = OrderedDict() # session_id -> (kv_blob, size), ordered by recencyself.host = OrderedDict()self.gpu_budget = gpu_budgetself.host_budget = host_budgetdef put(self, session_id, kv_blob, size):self._evict_gpu_if_needed(size)self.gpu[session_id] = (kv_blob, size)self.gpu.move_to_end(session_id)def _evict_gpu_if_needed(self, need):used = sum(s for _, s in self.gpu.values())while used + need > self.gpu_budget and self.gpu:sid, (blob, s) = self.gpu.popitem(last=False) # evict the least recently used sessionused -= sself._spill_to_host(sid, blob, s)def _spill_to_host(self, sid, blob, size):# Illustrative: a real implementation must check host_budget and,# when exceeded, spill to local storage or drop the dataself.host[sid] = (blob, size)def get(self, session_id, transcript_tokens, prefill_fn):if session_id in self.gpu:self.gpu.move_to_end(session_id)return self.gpu[session_id][0]if session_id in self.host:blob, size = self.host.pop(session_id)self.put(session_id, blob, size)return blob# Cache has expired; recompute from the conversation historyreturn prefill_fn(transcript_tokens)
5. Scheduling Techniques for Improving GPU Utilization
Caching strategy only addresses how memory is allocated. The scheduling layer determines how GPU compute time is allocated. Common techniques include:
- Continuous batching: as soon as a request finishes, a new request takes its place, avoiding the whole batch waiting on the slowest request.
- Chunked prefill: long inputs are split into chunks and executed interleaved with decode requests, reducing the blocking that long inputs impose on other users.
- Token budget: a total token limit is set for each scheduling step, balancing time to first token against generation throughput.
- Admission control: when memory usage exceeds a threshold, new requests are queued or rejected to prevent overall degradation of experience for existing sessions.
Evaluating the effectiveness of these techniques typically focuses on the following metrics:
- TTFT (time to first token)
