Session Resource Scheduling and Quotas for LLM Services Under Compute Constraints
This article discusses how LLM chat services can manage session resources and quotas when GPU compute and memory are constrained. It covers the prefill/decode resource model, KV cache sizing and concurrency estimation, three session-state handling strategies, admission control and quota design, capacity planning, and practical recommendations for developers.
1. Background: Why Compute Determines the Pace of Service Availability
The concurrency ceiling of a conversational LLM service is usually determined jointly by GPU compute capacity and GPU memory capacity. The more tokens a service can generate per second, the more user requests it can complete per unit time. GPU memory determines how many session states can reside concurrently.
When demand grows faster than compute supply, service providers generally take three types of action: tighten admission for new users, limit usage per user, or pause sales of new plans. The essence of these actions is to allocate limited compute to requests that need it most and can be served reliably.
Understanding this helps developers plan resources in advance when designing their own services, rather than reacting passively when traffic peaks arrive.
2. Resource Model During Inference
2.1 Prefill and Decode Phases
Inference for a chat request is usually divided into two phases:
- Prefill: processes all input prompt tokens at once. It is compute-intensive and suitable for parallel execution.
- Decode: generates output tokens one by one. Each generated token requires reading the existing history state, so this phase is mainly limited by memory bandwidth.
Decode efficiency directly affects the output speed users perceive and the number of concurrent sessions a single GPU can serve. Under bandwidth constraints, increasing concurrency is often the main way to improve throughput.
2.2 KV Cache and Its GPU Memory Footprint
During decoding, the self-attention mechanism needs to store key (K) and value (V) vectors for historical tokens. This data is called the KV cache. Its size can be estimated with the following formula:
KV cache bytes per session ≈ 2 × layers × KV heads × head dimension × sequence length × bytes per element
The factor 2 corresponds to the two copies of data for K and V. The longer the sequence, the larger the cache. For common 16-bit floating point, each element takes 2 bytes.
The KV cache grows as the conversation grows, and it loses reuse value once the session ends. It is therefore the key object in session resource management.
2.3 Estimating the Concurrency Ceiling
Ignoring other overheads, the concurrency per GPU can be estimated as follows:
GPU memory available for KV cache = total GPU memory - model weights - runtime overheadConcurrency ceiling ≈ GPU memory available for KV cache / average KV cache per session
The key to this estimate is “average occupancy.” If short conversations dominate the workload, the average will be noticeably lower than the occupancy of long conversations, and actual concurrency can be higher. Conversely, if long-context scenarios increase, the concurrency ceiling drops quickly. Developers should estimate based on the real distribution of session lengths, not just a single example.
3. Three Strategies for Handling Session State
When GPU memory is insufficient, service providers can choose the following three strategies. They involve different trade-offs in cost, latency, and implementation complexity.
3.1 Resident in GPU Memory
Keep the KV caches of active sessions entirely in GPU memory. This approach has the lowest latency and requires no extra preparation when continuing a session, but it has the lowest concurrency ceiling. It is suitable for scenarios that are extremely latency-sensitive and have a limited number of sessions.
3.2 Tiered Offload
Move caches that have been inactive for a long time to host memory or local SSD, and load them back into GPU memory when needed. This approach can significantly increase concurrency. The cost is data movement latency when resuming a session, and it also requires managing capacity and eviction order across multiple storage tiers.
3.3 Discard and Recompute
Release the cache when a session is idle. When the user sends another message, re-run prefill from the saved conversation text. This approach saves storage, but the cost of restoring a session is proportional to the history length.
For one-off Q&A or conversations with long intervals, cache reuse is usually low, so discard-and-recompute is often a reasonable choice. For tight multi-turn interaction, tiered offload or resident caching is usually more cost-effective.
Below is a simplified illustration of tiered caching that shows eviction logic for hot and warm tiers. The code is only intended to explain the idea. A production environment would also need to handle concurrency safety, asynchronous data movement, and exception recovery.
from collections import OrderedDictfrom typing import Callable, Anyclass TieredSessionCache:"""Illustrative example: GPU memory is the hot tier, host memory is the warm tier, and sessions beyond capacity are discarded."""def __init__(self, hot_slots: int, warm_slots: int):self.hot = OrderedDict() # session ID -> KV cacheself.warm = OrderedDict() # session ID -> offloaded KV cacheself.hot_slots = hot_slotsself.warm_slots = warm_slotsdef get_or_rebuild(self, session_id: str, rebuild: Callable[[], Any]) -> str:"""Return the hit type and ensure the session cache is in the hot tier."""if session_id in self.hot:self.hot.move_to_end(session_id)return "hit_hot"if session_id in self.warm:kv = self.warm.pop(session_id)self._insert_hot(session_id, kv)return "hit_warm"# Miss: re-run prefill based on the saved conversation recordsself._insert_hot(session_id, rebuild())return "miss_rebuild"def _insert_hot(self, session_id: str, kv: Any) -> None:while len(self.hot) >= self.hot_slots:evicted_id, evicted_kv = self.hot.popitem(last=False)self._insert_warm(evicted_id, evicted_kv)self.hot[session_id] = kvdef _insert_warm(self, session_id: str, kv: Any) -> None:while len(self.warm) >= self.warm_slots:self.warm.popitem(last=False) # warm tier is also full; discard directlyself.warm[session_id] = kv
This code illustrates two points. First, the eviction order follows the least-recently-used principle, so sessions that have been idle for a long time are demoted first. Second, the warm tier has limited capacity. When it exceeds capacity, entries are discarded directly, and the next request triggers recomputation. In this way, service providers can use a fixed memory budget in exchange for controllable recovery latency.
4. Quotas and Admission Control
Cache strategy addresses “how to store,” while quotas and admission control address “who gets to use it and how much.”
4.1 Two-Dimensional Limits
Limiting only concurrency or only usage tends to produce biased results. A common practice is to set two dimensions at the same time:
- Concurrency dimension: the number of inference slots that can be occupied at the same moment, used to protect service response time.
- Usage dimension: the total number of tokens that can be consumed within a rolling time window, used to balance long-term occupancy across different users.
For example, a plan can be given a token cap within a five-hour window while also limiting the maximum number of concurrent requests per user. Together, these limits can prevent both short-term burst occupancy and long-term resource skew.
4.2 Managing Subscription State
Subscription-based services need to maintain several types of state: validity period, auto-renewal switch, plan version, and usage ledger. The following points should be considered during design:
- After a plan change, existing users should have clear transition rules for their entitlements, avoiding ambiguity in the UI about lost benefits.
- After a user turns off auto-renewal, a manual renewal entry should still be retained, along with a clear expiration notice.
- The upgrade path should state when it takes effect, such as immediately or from the next billing cycle.
- UI display and backend accounting should come from the same data source to avoid inconsistency between what is shown and what is actually deducted.
4.3 Queueing and Degradation
When resources are tight, admission control needs to decide how to handle requests beyond capacity. Common options include:
- Queue and wait: wait in a queue by arrival time or priority, and show users an estimated wait time.
- Degraded service: temporarily switch to a smaller model or limit the maximum output length to maintain basic availability.
- Reject with notice: clearly state that capacity is insufficient and provide a retry time.
Degradation plans need to be communicated to users in advance so that changes in output quality are not mistaken for failures.
5. Capacity Planning Methods
Capacity planning usually includes the following steps:
- Collect session distribution statistics: gather input length, output length, number of turns, and session intervals, and calculate averages and percentiles.
- Measure per-GPU throughput: under representative load, test time to first token and tokens per second at different concurrency levels.
- Set latency targets: based on business requirements, define acceptable first-token latency and overall response time limits.
- Calculate required resources: combine peak traffic, target latency, and per-GPU capacity to derive the required number of GPUs.
- Reserve buffer: reserve a certain percentage of headroom for traffic spikes, node failures, and version releases.
Capacity planning is an ongoing process. As model specifications, context length, and user behavior change, the assumptions above need to be reviewed periodically.
6. Practical Recommendations for Developers
- Monitor before scaling: record GPU memory usage, cache hit rate, queue time, and recompute ratio to identify the real bottleneck.
- Differentiate session types: set different cache durations and eviction policies for one-off Q&A and long-running collaboration.
- Control context length: set explicit upper limits for very long inputs and prompt users to condense content. This is the most direct way to reduce memory pressure.
- Design fallback paths: if the cache service fails, the system should be able to degrade to recompute mode rather than directly returning an error.
- Make quotas configurable: manage plan parameters, limits, and window lengths in a configuration center so they can be adjusted quickly without a release.
- Maintain transparent communication: resource adjustments should explain the reasons, impact scope, and expected recovery time through announcements, UI notices, and similar channels.
7. Summary
The concurrency capacity of online LLM services is constrained by compute and GPU memory. Understanding the bandwidth limits of the decode phase and the growth pattern of the KV cache is the basis for capacity estimation. Session state can be resident, tiered-offloaded, or discarded and recomputed, and the choice should be based on the reuse characteristics of sessions. Quotas, queueing, and degradation mechanisms are responsible for maintaining fairness and stability when resources are tight. Developers should continuously adjust these designs based on monitoring data so that limited compute delivers the greatest value.
