Handling Long Sessions That Fill GPU Memory: KV Cache Eviction and Rate Limiting Strategies
When long-running conversations consume most of your GPU memory, the root cause is usually inactive session state held in VRAM as KV cache. This article explains why KV cache grows with context length and how to estimate its cost, then walks through a practical governance framework: idle session eviction, input and context length limits, quotas and rate limiting, and priority-based degradation. A conceptual Python implementation of idle cache reaping is included, along with engineering tips on observability, fairness, and rollout communication.
Handling Long Sessions That Fill GPU Memory: KV Cache Eviction and Rate Limiting Strategies
1. Why Long Sessions Become a Resource Bottleneck
In large language model (LLM) inference services, GPU memory (VRAM) is one of the scarcest resources. Model weights occupy a fixed amount of memory once loaded, and the remaining space must serve a large number of concurrent sessions. The longer a session runs, the more memory it consumes — this is the starting point for understanding the entire resource governance problem.
Users experience “long conversations” directly: the deeper the discussion goes, the more context accumulates. But what the server sees is a different set of numbers — the number of tokens each session has accumulated, and the intermediate computation results associated with those tokens. These results must stay in VRAM for the duration of the session.
Resource conflicts typically show up in three ways:
- New requests queue for longer, and time-to-first-token increases.
- Some requests are rejected or fail due to insufficient memory.
- Overall service throughput drops, with intermittent timeouts becoming more frequent.
The root cause is usually not a lack of compute power, but rather VRAM being occupied by a large number of long-inactive session states. Governance therefore comes down to answering two questions: which states are worth keeping, and for how long.
2. How KV Cache Works and What It Costs
When a Transformer generates text, producing each new token requires computing attention over all previous tokens. Attention depends on the Key and Value vectors of every historical token. Recomputing these vectors at every step would make cost grow rapidly with context length.
For this reason, inference frameworks cache the already-computed Key and Value vectors in VRAM and read them directly in subsequent steps. This cache is called the KV cache. It trades memory for time, avoiding massive redundant computation.
The size of a KV cache can be estimated with a general formula:
Bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element
The factor of 2 accounts for the two sets of vectors, Key and Value. As an illustrative example — not the real parameters of any specific model — assume:
- Layers: 32
- KV heads: 8
- Head dimension: 128
- Data type: FP16, 2 bytes per element
A single token then occupies roughly 2 × 32 × 8 × 128 × 2 = 131,072 bytes, or 128 KB. A single 32K-token session would require a KV cache of nearly 4 GB. This shows that even a handful of long sessions can fill the available memory of an entire GPU.
Note that KV cache size scales linearly with context length and keeps growing as a session continues. When a session goes idle, its cache is not released automatically — the server must actively evict it.
3. A Framework for Governance
To address long sessions occupying VRAM, engineering teams typically work at four levels. Each level solves a different problem, and combining them works better than relying on any single one.
3.1 Idle Session Eviction
The idea behind idle eviction is simple: if a session has received no new requests for a period of time, its KV cache is released and the memory is returned to active requests. The key parameter here is the idle timeout.
Choosing the timeout involves a trade-off. Set it too short, and users who pause briefly lose their context, hurting the experience. Set it too long, and memory reclamation has limited effect. A common practice is to tune timeouts based on workload characteristics — for example, different thresholds per user tier or session type — and to log eviction events for later tuning.
After a session is evicted, a new request from the same user requires recomputing the KV cache for the entire context — the prefill stage. Prefill latency grows with history length, adding to time-to-first-token. Eviction policies should therefore be paired with user-facing messaging that explains why resuming a session takes a moment.
3.2 Per-Request and Session Length Limits
Length limits are the most direct control mechanism. They apply on two dimensions:
- Per-request input limit: caps the length of text a user can submit at once, preventing a single request from instantly claiming a large amount of memory.
- Total session length limit: caps the cumulative context tokens in a session. Once exceeded, the system can prompt the user to start a new session, or handle the history via summarization or compression.
These limits should be calculated jointly from the model’s maximum context window, target concurrency, and total available VRAM. Limits set too conservatively interfere with normal usage; set too loosely, they lose their protective effect.
3.3 Quotas and Rate Limiting
Quotas control a user’s total usage within a time window, for example per day or per hour. When a user hits the quota, the system should return a clear error code and message rather than cutting off service abruptly.
Rate limiting protects the service at the request-rate level. Common algorithms include the token bucket and leaky bucket. Using both together constrains burst traffic and long-term volume simultaneously.
The wording of quota and rate limit messages deserves attention. A clear notice — explaining the reason for the limit, the expected reset time, and possible alternatives — significantly reduces user frustration. Vague messages are easily misread as a service outage.
3.4 Tiered Degradation and Priority Scheduling
When the system as a whole is under pressure, resources can be allocated by priority. Active sessions get VRAM and compute first, while idle sessions’ caches can be swapped out to host memory or slower storage and reloaded when needed. This is known as KV cache offloading, and it requires balancing bandwidth against latency.
Degradation strategies also include disabling non-core auxiliary capabilities under high load while preserving core conversation functionality. That way, even if some features are unavailable, the main service path keeps running.
4. Code Sketch for Session KV Cache Eviction
The example below shows the basic logic of idle eviction and length validation. It is a conceptual reference implementation — real inference engines have far more complex cache management, involving block-based allocation, reference counting, and concurrency safety.
import threadingimport timeclass SessionKVCache:def __init__(self, idle_ttl: float, max_context_tokens: int, release_fn):self.idle_ttl = idle_ttl # idle timeout in secondsself.max_context_tokens = max_context_tokensself._release_fn = release_fn # callback to free VRAM blocksself._sessions = {} # session_id -> session stateself._lock = threading.Lock()def acquire(self, session_id: str, new_tokens: int):"""Register a new request, validate length, and refresh last-active time."""now = time.monotonic()with self._lock:entry = self._sessions.setdefault(session_id,{"tokens": 0, "last_active": now, "blocks": None},)if entry["tokens"] + new_tokens > self.max_context_tokens:raise ValueError("Session context exceeds length limit")entry["tokens"] += new_tokensentry["last_active"] = nowreturn entrydef reap_idle(self):"""Evict sessions idle beyond the timeout; return evicted session IDs."""now = time.monotonic()with self._lock:expired = [sid for sid, entry in self._sessions.items()if now - entry["last_active"] > self.idle_ttl]for sid in expired:entry = self._sessions.pop(sid)self._release_fn(entry["blocks"])return expired
In usage, a background thread can call reap_idle periodically, and acquire can be called whenever a request arrives. A few points to keep in mind:
- Length validation must happen before allocating VRAM, so that invalid requests never consume resources.
- Eviction and registration share the same lock to keep state consistent. In a real system, lock granularity should be finer to avoid becoming a performance bottleneck.
- The release callback must be idempotent — releasing the same blocks twice should not cause errors.
5. Engineering Considerations
5.1 Observability
Once governance policies are live, monitor the following metrics continuously:
- Distribution of VRAM utilization, including peaks and tail behavior.
- Eviction frequency and average session duration.
- Percentage of requests rejected due to length limits or quotas.
- Prefill latency and time-to-first-token when resuming evicted sessions.
These metrics help teams judge whether thresholds are reasonable and catch anomalies early.
5.2 User Experience and Fairness
Resource governance is fundamentally an allocation problem. If policies only protect heavy users, infrequent users may never see the value of the service. Design for fairness — for example, reserve a baseline quota for all users, and set clear expectations for how long resuming an evicted session will take.
5.3 Incidents and Stability
Memory pressure makes service failures more likely. Teams should define degradation plans in advance, including trigger conditions, blast radius, and recovery steps. During post-incident reviews, correlate incident records with resource metrics to find root causes, rather than documenting symptoms alone.
5.4 Changes and Communication
Adjusting limit policies is a user-facing change. Explain the reason, scope, and rollback plan ahead of time. Well-crafted announcements and clear error messages reduce confusion and complaints.
6. Key Takeaways
The resource problem with long sessions is essentially a trade-off between the time cost and the space cost of VRAM. KV caching speeds up inference, but it makes idle sessions expensive. The governance playbook can be summarized as: use idle eviction to release long-unused state, use length and quota limits to constrain individual sessions, use rate limiting and degradation to protect overall stability, and use observability to keep tuning parameters over time.
For developers, understanding the KV cache cost model matters more than memorizing any specific threshold. Only by knowing where the cost comes from can you make sound trade-offs across different workloads.
