KV Cache Growth vs. Quota-Based Rate Limiting in LLM Inference

    This article examines the trade-off between KV cache memory growth and quota-based rate limiting in large language model inference services. It explains why KV cache dominates GPU memory during autoregressive generation, how to estimate per-token memory usage, and why idle and long-running sessions cause memory to keep expanding. It then compares four throttling strategies—session reclamation, input length caps, quota control, and tiered scheduling—along with their benefits, costs, and risk of impacting legitimate users. A code example illustrates admission control and idle session reclamation, and the article closes with capacity planning formulas and monitoring metrics to help calibrate thresholds through load testing and gradual rollout.

    1. Background: Why Inference Services Need Rate Limiting

    When a large language model serves external traffic, compute resources and GPU memory are both finite. A single accelerator card has a fixed memory capacity; model weights consume most of it, and the remaining space must hold the intermediate state of many concurrent requests. Service operators must balance throughput, latency, and fairness.

    During traffic spikes, without constraints, a handful of long sessions can exhaust GPU memory. The result is slower responses for most users, or outright request failures.

    This article uses “rate limiting” as an umbrella term for all mechanisms that control request rate, concurrency, and resource consumption. “Quota limiting” is one category within it—constraining usage per user or tenant. “Quota control” is the concrete mechanism that implements quota limiting, for example by counting tokens per billing period and deciding whether to admit a request. The rest of this article follows this terminology.

    Quota limiting is fundamentally a resource allocation mechanism. It serves three main goals: preserve response quality for active users, prevent individual requests from degrading the whole service, and reserve limited GPU memory for sessions that actually need inference.

    To understand this mechanism, we first need to know what is actually stored in GPU memory.

    2. KV Cache: The Main Memory Consumer in Inference

    2.1 Why caching is needed

    During autoregressive generation, each new output token must attend to all previous tokens. The Key and Value vectors at every historical position are reused. If they were recomputed at every step, the compute cost would grow rapidly with sequence length.

    Inference frameworks therefore store these vectors in GPU memory and read them directly at the next step. This data is called the KV cache.

    The KV cache trades space for time. The per-step compute cost becomes largely independent of history length, at the price of memory usage that grows linearly with sequence length.

    2.2 Estimating memory usage

    The number of bytes a single token occupies in the KV cache can be estimated with the following general formula:

    Bytes per token ≈ 2 × num_layers × num_kv_heads × head_dim × bytes_per_element

    The factor 2 accounts for the Key and Value data. Consider a set of example parameters: 32 layers, 8 KV heads, head dimension 128, and half precision (2 bytes per element).

    Each token occupies about 2 × 32 × 8 × 128 × 2 = 131072 bytes, or 128 KiB.

    A session with 32768 tokens consumes roughly 4 GiB for its KV cache alone. If dozens of such long sessions are served concurrently on the same card, memory is quickly exhausted.

    The code below computes the usage for a single sequence using the formula:

    1. def kv_cache_bytes(num_layers, num_kv_heads, head_dim, seq_len, dtype_bytes=2):
    2. """Estimate KV cache memory usage for a single sequence (in bytes)."""
    3. per_token = 2 * num_layers * num_kv_heads * head_dim * dtype_bytes
    4. return per_token * seq_len
    5. size = kv_cache_bytes(num_layers=32, num_kv_heads=8, head_dim=128, seq_len=32768)
    6. print(f"{size / 1024**3:.2f} GiB") # Output: 4.00 GiB

    The formula and example estimate only the KV cache itself. In real deployments, several additional points matter:

    • Layer count, KV head count, and head dimension must come from the specific model configuration; do not reuse the example values.
    • Models using grouped-query attention (GQA) or multi-query attention (MQA) have fewer KV heads than attention heads, so per-token usage drops noticeably.
    • The KV cache can be quantized to lower-precision formats such as FP8 or INT8, reducing bytes per element, but the accuracy impact must be evaluated separately.
    • Paged memory management such as PagedAttention mainly reduces memory fragmentation; it does not change bytes per token.
    • Batching increases the number of concurrent sequences but does not change the KV footprint of a single sequence.
    • Frameworks also consume memory for activations, temporary buffers, and reserved space, so actual usage is usually higher than the KV cache estimate.
    • Some models use sliding-window attention, which truncates cache length. Such models need to be re-estimated according to their own caching rules.

    Thresholds must be determined through load testing. Setting rate limiting thresholds directly from formula outputs can easily impact legitimate users, or leave the service exceeding memory during peak traffic because the estimate was too low.

    2.3 Why long sessions keep growing

    In multi-turn conversations, history is continuously appended to the context. Each new input and output round expands the KV cache, and two issues are easily overlooked.

    First, idle sessions still occupy memory. When a user stops sending messages, as long as the session state remains in GPU memory, the KV cache is not released. Memory usage does not drop when there are no server-side requests. A user who leaves for ten minutes may occupy the same amount of memory as when active.

    Second, long contexts keep appending. Systems typically retain the full history, so each conversation turn lengthens the context. The longer the context, the larger the cache that must be read at each generation step, and the higher the memory usage. Even if each turn’s input is short, after dozens of accumulated turns a single session may occupy several GiB.

    Summary: KV cache usage is determined by two things—how long the session is, and whether the session is still resident in GPU memory. Every quota rate limiting strategy revolves around these two factors.

    3. Trade-Offs in Quota Rate Limiting Strategies

    There are four common strategies: session reclamation, input length caps, quota control, and tiered scheduling. They act on different objects and carry different costs.

    3.1 Session reclamation

    Session reclamation releases a session’s KV cache after it has been idle for some time. The session’s text history is retained, and the cache is recomputed on the next request.

    The benefit is fast memory release, which is especially effective under high concurrency. The cost is that resuming a session requires reprocessing the full history, raising time-to-first-token. If the idle threshold is set too short, normal user thinking pauses may trigger reclamation, causing unexpectedly slow responses.

    3.2 Input length caps

    Input length caps limit the number of new input tokens per request. They directly constrain the peak usage of a single request, preventing one overly long request from filling GPU memory.

    The cost is that legitimate long-document requests are rejected. A better approach is to offer chunked processing or a summarization alternative, and explain the reason in the response.

    3.3 Quota control

    Quota control tracks usage by user, tenant, or plan—for example, the number of tokens per billing period, or the number of concurrent sessions. Requests exceeding the quota are rejected or queued.

    Its purpose is fairness: preventing a single user from monopolizing resources. The cost is that quotas set too tight hurt active users, while quotas set too loose fail to protect the service. Quota values must be determined together with billing plans and capacity planning.

    3.4 Tiered scheduling

    Tiered scheduling assigns requests to different queues or instance pools by priority. High-priority requests get more stable latency, while low-priority requests wait when resources are tight.

    It fits scenarios that serve both paying and free users, or that mix interactive requests with offline batch processing. The risk is that low-priority requests wait too long or are starved indefinitely. Therefore a maximum wait time should be set, and long-waiting requests should be gradually promoted.

    3.5 Strategy comparison

    Strategy Primary function Benefit Cost Risk of impacting users Applicable boundary
    Session reclamation Release KV cache of idle sessions Fast memory release, higher concurrency Recompute history on resume, higher time-to-first-token Normal users with longer pauses are reclaimed unexpectedly When text history can be fully reconstructed
    Input length caps Limit peak usage of a single request Prevent a single request from filling memory Legitimate long inputs are rejected Long-document users are affected When chunking or summarization alternatives are available
    Quota control Allocate usage by user or tenant Fair distribution, prevent single-user monopolization Tight quotas hurt active users Normal requests are rejected during peaks When clear billing or plan boundaries exist
    Tiered scheduling Order queues by priority Stable latency for high priority Longer waits for low priority Low-priority requests are starved When max wait and priority promotion mechanisms are in place

    Risk note: overly strict rate limiting thresholds hurt active users, while overly loose thresholds can bring down the service. Before launch, run canary tests on a small traffic fraction, observe rejection rates and latency changes, then gradually expand. Rate limiting logic should run server-side; do not rely solely on client-side checks.

    4. Code Example: Admission Control and Session Reclamation

    The pseudocode below shows three things: admission decisions, long-session count control, and idle reclamation. It is a structural illustration; a real system needs to connect to actual cache statistics and a scheduler.

    1. import time
    2. from dataclasses import dataclass, field
    3. MAX_INPUT_TOKENS = 4096 # Max new input tokens per request
    4. MAX_CONTEXT_TOKENS = 32768 # Max context tokens per session
    5. IDLE_TIMEOUT_S = 600 # Idle timeout before reclaiming KV cache
    6. LONG_SESSION_TOKENS = 16384 # Context length threshold for long session
    7. MAX_LONG_SESSIONS = 8 # Max concurrent long sessions per instance
    8. @dataclass
    9. class Session:
    10. sid: str
    11. context_tokens: int = 0
    12. last_active: float = field(default_factory=time.time)
    13. kv_resident: bool = True # Whether KV cache is still resident in GPU memory
    14. def admit(session, input_tokens, sessions):
    15. """Return admission decision: accept, reject, or need_evict."""
    16. if input_tokens > MAX_INPUT_TOKENS:
    17. return "reject"
    18. projected = session.context_tokens + input_tokens
    19. if projected > MAX_CONTEXT_TOKENS:
    20. return "reject"
    21. if projected >= LONG_SESSION_TOKENS:
    22. long_count = sum(
    23. 1 for s in sessions.values()
    24. if s.kv_resident and s.context_tokens >= LONG_SESSION_TOKENS
    25. )
    26. if long_count >= MAX_LONG_SESSIONS:
    27. return "need_evict"
    28. return "accept"
    29. def reclaim_idle(sessions, now=None):
    30. """Reclaim KV cache for sessions idle beyond the timeout. Text history is retained. Returns number of freed tokens."""
    31. now = now or time.time()
    32. freed = 0
    33. for s in sessions.values():
    34. if s.kv_resident and now - s.last_active > IDLE_TIMEOUT_S:
    35. freed += s.context_tokens
    36. s.kv_resident = False
    37. return freed

    Note: reclaim_idle returns a token count. To convert to bytes, multiply by the per-token byte estimate from the previous section. need_evict means the scheduler must first reclaim other sessions or queue the request.

    5. Capacity Planning and Monitoring Metrics

    5.1 Capacity estimation

    Capacity estimation can proceed as follows:

    Required KV cache ≈ concurrent sessions × average context length × bytes per token

    Total demand must also include model weights, activations, and a reserve ratio. The reserve ratio covers burst peaks and memory fragmentation; its value should be determined through load testing.

    As a hypothetical example: at 128 KiB per token and an average context of 4096 tokens, a single session occupies about 512 MiB. If 40 GiB is available for KV cache, about 80 such sessions can theoretically fit. After deducting the reserve ratio, the actual number is lower.

    5.2 Monitoring metrics

    • GPU memory usage: KV cache occupancy ratio and memory fragmentation rate, to judge proximity to the limit.
    • Queue latency: P50, P95, and P99 percentiles, tracked separately for high- and low-priority queues.
    • Rejection rate: categorized by reason—input over limit, context over limit, insufficient quota, and insufficient capacity. When rejection rate spikes, first check whether thresholds are too strict.
    • Session lifetime: distribution of time from KV cache write to release, to judge whether the reclamation threshold is reasonable.
    • Post-reclamation recompute rate: the proportion of reclaimed sessions that are later resumed. A high ratio indicates reclamation is too aggressive and will raise time-to-first-token.
    • Concurrent long sessions: the number of concurrently resident sessions whose context exceeds the threshold, to compare against the MAX_LONG_SESSIONS setting.

    6. Conclusion

    KV cache memory usage grows with session length, and idle sessions hold onto that space for extended periods. Session reclamation, input length caps, quota control, and tiered scheduling act on different parts of the pipeline, each with its own costs and risk of impacting legitimate users. Thresholds should be based on model configuration and load testing results, and continuously calibrated through canary rollout and monitoring metrics.