Rate Limiting and Session Governance for LLM Services Under Compute Constraints
This article explains how to manage LLM serving capacity when compute is scarce. It covers how KV cache consumption depends on session length, how to classify and reclaim idle sessions in stages based on activity and priority, how to apply token bucket rate limiting at the entry point, how to estimate session capacity, and how to roll out and monitor these policies safely.
1. Background
LLM inference resource consumption does not scale linearly with request count. Two requests can differ greatly in cost. A longer context or more retained sessions consumes more GPU memory and compute. When available compute falls short of demand, a service typically faces two problems at once: new requests cannot get compute promptly, and many long-idle sessions still hold cache, squeezing the space available to active users.
A common engineering response is to limit concurrency at the entry point and reclaim session resources in tiers. On the surface, this shrinks functionality. In substance, it allocates limited resources to the requests that need them most. Doing this well requires first identifying where resource consumption comes from, then designing decision rules, and finally verifying the effect with capacity data.
2. Where Resources Go
For Transformer-based models, inference keeps a key-value (KV) cache for each session. Its size can be estimated with the following formula:
Cache size per session (bytes) ≈ 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per element
The factor of 2 accounts for the separate K and V caches. Doubling the sequence length roughly doubles the cache footprint. Long sessions are therefore the main source of resource pressure, so governance should focus on sessions that are both long and inactive. Short sessions, even when numerous, each take up little memory and usually are not the bottleneck.
Besides the cache, model weights, batching queues, and reserved system space also consume GPU memory. In capacity planning, these must be subtracted from the total first. Otherwise, the estimate will come out too high.
3. Activity-Based Tiered Governance
3.1 Activity Detection
Activity should be judged by the time of the most recent valid interaction, not by how long a connection stays open. An open connection does not mean the user is still active, because a long-lived connection can sit idle for a long time.
The detection window should be configured for each use case. Scenarios involving light Q&A can use a shorter window, while long-running collaborative tasks can use a longer one. The window length should be based on historical user behavior data rather than set by intuition.
3.2 Staged Reclamation
Reclamation should not delete data directly. Three stages are recommended:
- Cooling stage: once a session exceeds the soft threshold, move its context to a lower-cost storage tier to free GPU memory.
- Archiving stage: keep the session summary and essential metadata so the user can resume later.
- Purge stage: when a session exceeds the hard threshold and no recovery is requested, delete the raw data and write an audit log entry.
Staging makes each step observable and reversible. If the cooling stage triggers a clear increase in recovery requests, the soft threshold is probably too aggressive and can be adjusted promptly.
3.3 Priority Scheduling
Sessions differ in value. Priority can be assigned based on service tier, request source, and task type. When resource pressure rises, reclaim low-priority, long-inactive sessions first to avoid harming important tasks.
Priority rules should be public and explainable. They should depend only on business attributes and must not treat specific users differently in hidden ways.
4. Entry-Point Rate Limiting
Rate limiting answers the question of how many requests to admit. A token bucket is a common implementation. The system adds tokens to the bucket at a fixed rate. Each request takes tokens equal to its cost. When the bucket is empty, requests wait or get rejected.
Cost should be computed from input and output token counts, so long requests automatically consume more quota. A simplified implementation follows:
import timeclass TokenBucket:def __init__(self, rate_per_sec: float, capacity: float):self.rate = rate_per_sec # Tokens refilled per secondself.capacity = capacity # Maximum bucket capacityself.tokens = capacityself.updated = time.monotonic()def allow(self, cost: float) -> bool:now = time.monotonic()elapsed = now - self.updatedself.tokens = min(self.capacity, self.tokens + elapsed * self.rate)self.updated = nowif self.tokens >= cost:self.tokens -= costreturn Truereturn Falsedef estimate_cost(input_tokens: int, max_output_tokens: int) -> float:# Use the total token count as the request cost, with the output limit assumed at its worst casereturn float(input_tokens + max_output_tokens)
This code only demonstrates the core logic. Production systems must also handle quota sharing across instances, concurrency safety, and request timeouts. These are typically handled with a distributed cache or the rate-limiting features of a gateway layer.
Reclamation logic can be expressed in a similar way:
import timefrom dataclasses import dataclassSOFT_IDLE_SECONDS = 24 * 3600 # Soft threshold: after this, move to lower-cost storageHARD_IDLE_SECONDS = 7 * 24 * 3600 # Hard threshold: after this, enter the purge process@dataclassclass Session:session_id: strlast_active: float # Timestamp of the last valid interactioncontext_tokens: intpriority: int # Lower values mean lower prioritydef pick_action(session: Session, memory_usage: float, now: float | None = None) -> str:now = now or time.time()idle = now - session.last_active# Skip reclamation when memory pressure is low to avoid unnecessary migration overheadif memory_usage < 0.8:return "keep"if idle >= HARD_IDLE_SECONDS:return "purge"if idle >= SOFT_IDLE_SECONDS:return "offload"return "keep"
In deployment, thresholds should be read from configuration rather than hard-coded. Reclamation actions must also link to audit and recovery processes so that every purge can be traced.
5. Capacity Estimation
Governance results need to be verified with numbers. Estimate the sustainable session count with these steps:
- Measure the number of concurrent sessions during peak hours and the average context length of those sessions.
- Use the formula in Section 2 to calculate the cache footprint of a single session.
- Subtract model weights, system reserve, and batching overhead from available GPU memory to get the space usable for cache.
- Estimate the session capacity by dividing the usable cache space by the per-session cache footprint, then keep a margin for traffic bursts.
For example, if the space usable for cache is a fixed share of total memory, and per-session cache grows with context length, then the same hardware supports noticeably fewer sessions when long sessions dominate. This is why reclaiming long sessions by activity frees capacity.
Compare the estimate against online monitoring data. If actual peaks keep exceeding the estimated ceiling, the margin is insufficient. In that case, add capacity or tighten rate-limit parameters.
6. Rollout and Monitoring
Before launching a governance policy, roll it out to a small share of traffic first. Watch these metrics:
- Trends in active session count and average context length;
- Peak GPU memory utilization and how long it persists;
- Reclamation counts, tracked separately for cooling, archiving, and purging;
- Recovery request count and recovery failure rate;
- Share of requests rejected or queued due to rate limiting.
Alerting rules can notify on-call staff when GPU memory utilization stays above the threshold for a period, or when the recovery failure rate rises noticeably. Keep a one-click switch to disable the reclamation policy so you can roll back quickly during incidents.
7. User Communication and Compliance
Any change that reduces a user’s existing capabilities should be announced in advance. The notice should cover what the rule is, when it takes effect, how inactivity is determined, how long data is retained, and how users can recover their sessions. Losing user data without notice is both a user experience problem and a potential compliance risk.
For users with a genuine need for long-term use, provide a way to manually keep a session or extend its retention period. Rules should apply uniformly and not be adjusted ad hoc for individual users, so the service remains predictable.
8. Practical Recommendations
When resources are tight, the most effective approach is usually a combination of measures rather than a single one. Rate limiting controls new pressure, activity-based reclamation frees resources already in use, capacity estimation guides scaling decisions, and monitoring with gradual rollout keeps each step observable and reversible.
Teams should define business priorities first and then design the technical rules. Otherwise, the policy can conflict with user expectations during peak periods.
