KV Cache and Quota Management in LLM Inference
This article explains how KV cache growth drives inference cost in long conversations, why idle sessions consume GPU memory, and how quota and rate-limiting policies can be designed. It also covers client-side handling of performance degradation and outages, including jittered exponential backoff, idempotency, and circuit breakers, plus the engineering implications of non-persistent session state.
1. Why Long Conversations Increase Inference Cost
When a large language model generates each new token, the attention mechanism at the current position must look back at all previous tokens. If the keys and values of historical tokens were recomputed at every step, the amount of computation would grow rapidly with sequence length. Inference frameworks therefore usually cache these intermediate results and read them directly in the next step. This cache is called the KV cache.
The KV cache trades space for time, and the cost is GPU memory usage. Its approximate size can be estimated with the following formula:
Memory usage ≈ 2 × layers × KV heads × head dimension × sequence length × concurrent sessions × bytes per element
The coefficient 2 corresponds to the two data sets, K and V. Consider an assumed model with 32 layers, 8 KV heads, a head dimension of 128, and 2 bytes per element. When a single session reaches 32K tokens, the KV cache alone is approximately 2 × 32 × 8 × 128 × 32768 × 2 bytes, or 4 GiB. This number shows two things: cache size grows linearly with session length, and the number of concurrent sessions multiplies total occupancy linearly. GPU memory is limited, so the service provider must decide which sessions remain resident in GPU memory.
2. Why Idle Sessions Are a Resource Problem
After a user leaves, if the session’s KV cache is not released, it continues to occupy GPU memory while producing no computation. In high-concurrency services, this invalid occupancy reduces the space available to active requests, leading to longer queues and higher latency. In severe cases, requests may fail directly.
There are three common approaches:
- Idle reclamation: Release or swap out the KV cache for sessions with no activity beyond a configured duration. When the user returns, the server recomputes the cache from the saved conversation text.
- Tiered storage: Migrate the caches of cold sessions to larger, slower storage media and load them back into GPU memory when needed.
- Compression and truncation: Summarize historical content or use a sliding window that retains only recent context, thereby reducing the cache size per session.
Each approach has tradeoffs. Idle reclamation is simple to implement, but users returning to an old session may experience noticeable first-token latency. Tiered storage can preserve the session experience, but it introduces migration bandwidth and data consistency issues. Compression loses detail and requires balancing answer quality against resource cost.
3. Common Quota and Rate-Limiting Strategies
Quota control makes resource allocation rules explicit. It is usually designed across the following four dimensions.
- Single-input limit: Limit the number of tokens or characters in a single request to prevent one request from monopolizing resources.
- Session lifecycle: Set an idle timeout after which the session is no longer continued.
- Time-window quota: Limit the number of calls or total tokens per day or per minute to handle burst traffic.
- Priority scheduling: When resources are tight, prioritize active requests and inference demand from critical business functions.
These strategies aim to protect overall availability, but their impact on user experience needs to be evaluated during design. A single-input limit may force users to split long documents. A daily quota may suddenly run out at a certain time of day, catching users off guard. Service providers should therefore explain the reason for the limit and the quota reset time in their prompts, and avoid vague system messages.
Below is illustrative logic for session reclamation. It is intended only to show the idea, and the threshold is an example value:
IDLE_TIMEOUT_SECONDS = 24 * 3600 # Example value; actual value should be determined by GPU memory headroom and business scenarioclass Session:session_idlast_active_tskv_cache_bytesresident = True # Whether the cache is still resident in GPU memoryfunction reclaim_idle_sessions(sessions, now):reclaimed = []for s in sessions:if s.resident and (now - s.last_active_ts) > IDLE_TIMEOUT_SECONDS:s.resident = False # In a real system, this triggers cache swap-out or releasereclaimed.append(s.session_id)return reclaimed
When implementing quotas, the server usually uses a token bucket or fixed-window counters. The client should also record usage locally and block obviously over-limit requests in advance to reduce invalid calls.
4. Failure Types and Client-Side Handling
Failures in inference services fall roughly into two categories:
- Performance degradation: Slower responses, higher first-token latency, and occasional request failures. The service is still available, but the experience is noticeably degraded.
- Partial or total outage: An endpoint or function is unavailable, and in severe cases all requests return errors.
Developers need to distinguish these two cases before adopting different strategies.
For transient errors such as timeouts or temporary service unavailability, use exponential backoff with jitter. Continuous, dense retries amplify pressure on the server and may cause an avalanche. Jitter spreads out large numbers of retry requests issued at the same moment, preventing them from hitting the service simultaneously again.
function call_with_backoff(fn, max_retries, base_delay, max_delay):for attempt in 0..max_retries:try:return fn()catch TransientError:if attempt == max_retries:raisedelay = min(max_delay, base_delay * 2^attempt)sleep(delay * random_uniform(0.5, 1.0)) # Random jitter
Automatic retries are only suitable for idempotent or safely replayable requests. If a conversation generation request has already incurred billing or side effects, deduplicate by request ID to prevent the same intent from being executed repeatedly.
A circuit breaker is another common mechanism. When the failure rate of an endpoint within a statistical window exceeds a threshold, the circuit breaker directly returns a degraded result for a period instead of forwarding requests. It then probes recovery at a low frequency and gradually releases traffic after successful probes. A circuit breaker protects downstream services and also allows upstream applications to return a clear prompt quickly instead of hanging for a long time.
5. Session State and Context Engineering
The server does not guarantee that a session will remain resident permanently, so the client should not assume that cached context will always be available.
