# LLM Inference Compute Bottleneck: KV Cache and Scheduling in Practice

    Chat inference rate limits are often not a FLOPS problem but a ceiling on how many active sessions the system can sustain. This article breaks down the four constraints that set that ceiling—VRAM capacity, compute and memory bandwidth, batch scheduling, and SLO targets—and shows how to estimate a usable concurrency limit with a small set of formulas. It profiles the prefill and decode phases and explains when decode is bandwidth-bound and when it becomes compute-bound. Finally, it covers the conditions under which KV cache can be safely evicted, concrete patterns for admission control, eviction with fallback, and context reload, plus a capacity planning checklist and the key parameters of dynamic batching.

    What “Compute Pressure” Really Means

    When a chat service starts rate limiting, it usually isn’t because a GPU is “too slow” to do the math. It’s because the number of concurrent active sessions the system can sustain has hit its ceiling. That ceiling isn’t set by GPU FLOPS alone. At least four constraints apply at the same time:

    • VRAM capacity: weights, activations, and KV cache must all fit in GPU memory, and KV cache grows linearly with concurrency and context length.
    • Compute and memory bandwidth: prefill and decode make fundamentally different demands on compute versus bandwidth.
    • Batch scheduling: the scheduling window, max batch size, priority, and preemption policy directly determine effective throughput on the same hardware.
    • SLO targets: time to first token (TTFT) and time per output token (TPOT) are hard constraints. Meeting latency targets means giving up some theoretical throughput.

    Two rough formulas make the picture concrete (all numbers below are illustrative; benchmark your own):

    1. VRAM-bound concurrency = (per-GPU VRAM - weights - framework/activation overhead) / (KV bytes per token × avg. context length)
    2. Compute-bound concurrency = per-GPU decode throughput (tokens/s) × TPOT target (s/token) # from Little's Law
    3. Peak usable concurrency ≈ min(VRAM-bound, compute-bound) × efficiency derating factor

    A quick example: 80 GB of VRAM, 16 GB of weights, and 8 GB for framework and activations leave 56 GB for KV. At 128 KB of KV per token and an average context of 4,000 tokens, one session costs about 512 MB, so one GPU can theoretically hold around 110 sessions. In reality, you need headroom for mixed long and short requests, VRAM fragmentation, and bursty peaks. So in practice, apply a derating factor of roughly 0.6–0.8 and provision for the worst case, not the average. Skip this step and you end up baffled: monitoring shows VRAM isn’t full, yet the service has already started rate limiting.

    Prefill vs. Decode: Two Very Different Performance Profiles

    Autoregressive generation emits one token per step and appends it to the input to produce the next step. It typically breaks into two phases:

    Dimension Prefill Decode
    Compute profile Processes the entire prompt in one pass with large matrix multiplications; compute-bound Token-by-token and sequential; usually memory-bandwidth-bound
    Key metrics TTFT, prefill throughput (tokens/s) TPOT, decode throughput (tokens/s)
    Main bottleneck Compute, kernel launch overhead, queuing of long prompts Repeated reads of weights and KV cache, batch size, scheduling
    Scaling focus Compute capacity, chunking strategy, queue length VRAM capacity and bandwidth, concurrency ceiling
    Common optimizations Chunked prefill, prefix cache, quantization PagedAttention, dynamic batching, KV cache quantization, speculative decoding

    One common claim needs correcting: decode is not always limited only by memory bandwidth. When the batch is small and sequences are short, reading weights dominates the cost, so decode shows up as bandwidth-bound. But as the batch grows, weight reads get amortized, and once arithmetic intensity passes the hardware’s ridge point, decode becomes compute-bound. Other factors can also make decode compute-bound or scheduler-bound rather than bandwidth-bound:

    • Sampling and logits computation over large vocabularies
    • Expert routing and gather in Mixture-of-Experts (MoE) models
    • Long-context attention
    • Dequantization in quantized kernels
    • The verification stage of speculative decoding
    • Kernel launch and Python scheduling overhead

    To find out which regime you’re in, use three checks:

    1. Batch-size sensitivity: if per-step latency rises roughly linearly as you increase the batch, you’re leaning compute-bound. If latency barely changes while throughput rises linearly, you’re leaning bandwidth-bound.
    2. Arithmetic intensity and roofline: use a profiler to compare achieved arithmetic intensity with the hardware’s ridge point, and watch achieved GEMM/GEMV efficiency and MFU.
    3. Per-step timing breakdown: time prefill, decode, sampling, scheduling, and H2D/D2H copies separately. Find the largest contributor, then pick an optimization direction.

    When It’s Safe to Drop KV Cache

    KV cache avoids recomputing over long contexts, but it consumes a lot of VRAM. In a chat service, it can be proactively evicted because conversation patterns have three relevant properties:

    • One-shot question-answer exchanges are the majority.
    • Cross-day returns to long-running conversations are sparse, so there are long cooldown gaps between sessions.
    • Recovery cost is manageable: at worst, reload the context from the persistent layer or recompute the prefill.

    But “can be dropped” should be rewritten as a conditional statement. It applies only when all of the following hold:

    1. The context can be persisted or recomputed, and the recovery path is proven to work.
    2. The extra latency from recovery is acceptable (recomputing prefill pushes up TTFT, so it must be accounted for in the SLO budget).
    3. The business semantics allow degradation, for example, non-real-time completion where one extra wait is tolerable.
    4. When personal data or compliance-sensitive content is involved, you must first desensitize it, encrypt it at rest, and support verifiable deletion and access auditing.

    If these conditions aren’t met, for example financial risk-control conversations or medical Q&A that strictly depend on context, pin those sessions so they’re never evicted, or isolate them on dedicated instances.

    Graceful Degradation When Compute Is Tight

    Core idea: keep the online experience intact while pushing requests through as quickly as possible and discarding cache as soon as it’s no longer needed.

    Request Queuing and Admission Control

    1. def schedule(request, gpu_slots):
    2. if len(gpu_slots.running) >= gpu_slots.max_concurrent:
    3. if len(gpu_slots.queue) >= gpu_slots.max_queue:
    4. return reject(429, retry_after=backoff_with_jitter(request)) # fail fast
    5. gpu_slots.queue.append(request) # queue when over capacity
    6. return
    7. gpu_slots.admit(request) # schedule immediately when a slot is free

    Common questions, short answers:

    • How to set the queue limit: derive it from your queuing latency budget: Q_max ≈ arrival rate × acceptable wait time (s). Once a request waits longer than the budget, it has effectively failed, so failing fast is better.
    • What to return when over the limit: HTTP 429 or 503, with Retry-After and an estimated wait time. Ban unlimited client-side retries and enforce a retry budget.
    • How to differentiate new from returning users: avoid a crude split by registration date. Use SLA-based priority queues with quotas so paying customers and critical workloads always have a guaranteed path.
    • How to prevent cascading failures: use a bounded queue, a token bucket rate limiter, a circuit breaker, exponential backoff with jitter, and a per-request timeout cap. Together, these prevent a retry storm from amplifying itself.
    • Degradation must be communicated: queuing and rejection are experience losses, so the product UI should clearly show the current state and expected wait time to discourage users from resubmitting repeatedly.

    KV Cache Eviction and Reload

    1. MAX_EVICT_PER_CYCLE = 4 # cap on evictions per cycle, prevents an eviction storm
    2. MIN_IDLE_SEC = 120 # cooldown threshold; sessions still generating are never evicted
    3. def evict_when_pressured(cache, store, limit, metric):
    4. freed = 0
    5. for _ in range(MAX_EVICT_PER_CYCLE):
    6. if cache.memory_used <= limit:
    7. break
    8. victim = cache.pick_idle_session(min_idle_sec=MIN_IDLE_SEC)
    9. if victim is None: # nothing to evict -> exit instead of spinning forever
    10. break
    11. try:
    12. store.save(victim.session_id, victim.context,
    13. encrypt_key=store.kms_key, ttl_s=store.ttl_s) # encrypt + TTL + access control
    14. except StoreError:
    15. metric.inc("kv_persist_failed") # persistence failures must trigger alerts
    16. victim.mark_reload_by_recompute() # fallback: recompute prefill on the next turn
    17. continue
    18. cache.release(victim, zeroize=True) # free VRAM and clear residual buffers
    19. freed += victim.bytes
    20. if cache.memory_used > limit:
    21. metric.inc("kv_evict_exhausted") # eviction can no longer relieve pressure -> trigger rate limiting
    22. return freed

    Actionable notes for this code:

    • Keep the loop bounded: cap both the number of evictions per cycle and the total time spent. Otherwise you get an eviction storm (“evict → recompute → evict again”) that turns VRAM pressure into amplified compute load.
    • Always have a fallback: if persistence fails, degrade to “recompute next time” and alert on the failure rate. Reloads also need a timeout; on timeout, fall back to recomputation or rejection rather than waiting forever.
    • Clear sensitive context when freeing VRAM: zeroize residual buffers to prevent session content from leaking across requests. Concurrent evictions of the same session must be idempotent and deduplicated.
    • Keep persisted content compliant: context may contain personal data, so use encrypted storage at rest, least-privilege access, TTLs, and audit logs. Support verifiable deletion on user request, and check data residency and cross-border requirements.
    • Eviction isn’t free: it raises TTFT on recovery, so account for that explicitly in your SLOs. Track eviction and reload rates separately in monitoring.

    Reloading Context from Persistent Storage

    Use a tiered setup (VRAM → RAM → local or remote storage) backed by object storage or high-performance local disks. That turns “drop” into “demote to a slower storage tier” instead of “lose.” Combining this with a prefix cache that reuses stable prefixes, such as system prompts, can significantly lower reload costs.

    Capacity Planning: A Quantifiable Checklist

    Don’t provision based on average traffic. Size for the worst case with headroom. Fill in each item:

    • Peak concurrency target (including factors for promotions and traffic hotspots) and the arrival rate curve.
    • Average and P95 input length, average output length, and the output length distribution.
    • Per-GPU prefill throughput (tokens/s) and per-GPU decode throughput (tokens/s), with test conditions documented: batch size, sequence length, quantization precision, and so on.
    • KV cache memory per token: 2 × num_layers × num_kv_heads × head_dim × bytes_per_element (under GQA/MQA, num_kv_heads is much smaller than the number of attention heads).
    • TTFT and TPOT targets, each with its own P95 definition.
    • Load testing approach: step load plus soak tests. Record the throughput-latency curve and its inflection point to find the maximum concurrency before SLOs break.
    • Headroom strategy: reserve capacity for bursts, eviction and reload overhead, and fault-domain redundancy (so a single availability zone or machine failure doesn’t break the overall SLO).

    Runtime capabilities matter just as much. Integrate with a container platform and autoscaling: scale out at peak and reclaim capacity in troughs to lower cost per request. Set up monitoring and tiered alerts for GPU utilization, VRAM usage, queue length and wait time, TTFT, TPOT, cache hit rate, eviction rate, and reload failure rate, so you get early warnings instead of firefighting after the fact.

    Key Parameters for Dynamic Batching

    Dynamic batching merges multiple requests into the same decode step, making it one of the main levers for raising output per unit of compute. Badly chosen parameters, however, cause head-of-line blocking:

    • max_num_seqs: max sequences per batch, bounded by the VRAM-bound concurrency. Calculate the upper bound with the VRAM formula first, then apply the derating factor.
    • max_num_batched_tokens: max tokens per batch. Setting it too high raises TTFT, so derive it from your TTFT budget.
    • Scheduling window (batch timeout): the maximum wait time spent assembling a batch. Use a small value for latency-sensitive workloads and a larger one when throughput is the priority.
    • Timeouts and priority: set a total timeout and a priority for each request, and use preemption to protect critical traffic.
    • Avoiding head-of-line blocking: enable chunked prefill.