How to Design Session Retention and Rate Limiting for LLM Services Under Compute Constraints
This article explores how to manage compute resources for Large Language Model (LLM) services during periods of resource scarcity. It covers the impact of token consumption on resource limits, common constraints like session storage and rate limiting, and provides design patterns for hierarchical session management, token-based input validation, and tiered rate limiting. It also includes capacity planning formulas and communication strategies for implementing these technical constraints effectively.
1. Why Free Services Hit Resource Limits First
LLM inference resource consumption is primarily related to the number of input and output tokens. A longer context in a request increases the computation during the prefill phase and requires more KV (key-value) cache for historical content during inference. The cache occupies GPU memory, which directly limits the number of concurrent requests a server can handle.
Therefore, the actual bottleneck is usually not “the number of users” but “the average number of tokens consumed per request” multiplied by “the total volume of requests.” When daily active users (DAU) grow rapidly while hardware expansion takes weeks or months to procure and deploy, a supply-demand gap emerges quickly.
Free users exacerbate this gap. The cost of paid users can be covered by subscription fees, whereas the calls from free users are entirely operational costs. When resources are insufficient, service providers must control consumption through technical means, which often directly impact free users.
2. Three Common Constraints and Their Technical Implications
When resources are tight, service providers typically tighten three sets of parameters simultaneously, each corresponding to different resources.
2.1 Session State Storage and Indexing
Long conversations require saving complete message histories, and some systems also save summaries, retrieval indices, and intermediate states. The more active sessions there are, the higher the storage and indexing costs.
A common practice is to set a Time To Live (TTL) limit on the idle duration for sessions that have not been accessed for a long time. The key here is the judgment criterion: it should be based on the “last active time” rather than the creation time.
2.2 Single Input Length Limit
The input length limit directly relates to the context window, GPU memory usage, and initial response latency. When setting limits, counting should be done by tokens, not by characters or words. The token-to-character ratio varies significantly across different languages and symbols; setting limits by word count can easily lead to situations that “look reasonable but are actually overloaded.”
2.3 Call Frequency Quotas
Rate limiting is used to smooth traffic and prevent a small number of heavy users from monopolizing shared resources. Common algorithms include fixed window, sliding window, and token bucket. The token bucket allows for short bursts while constraining the long-term average rate, making it well-suited for LLM service scenarios.
3. Design Approaches
3.1 Tiered Management of Session Lifecycle
A more robust approach is to store session states in tiers rather than deleting them upon expiration:
- Hot data: Recently active sessions, retaining full context in high-speed storage.
- Warm data: Sessions exceeding the idle threshold, compressed into summaries and migrated to low-cost storage.
- Cold data: Sessions inactive for a long time, retaining metadata and providing export options.
The purpose of tiering is to reduce storage costs while leaving room for users to recover and export data. The following example shows the logic for determining session status based on the last active time:
from datetime import datetime, timedeltaIDLE_LIMIT = timedelta(days=7) # Idle archive thresholdWARN_BEFORE = timedelta(days=1) # Advance notification windowdef classify_session(last_active: datetime, now: datetime) -> str:idle = now - last_activeif idle >= IDLE_LIMIT:return "archive" # Migrate to cold storage, retain export entryif idle >= IDLE_LIMIT - WARN_BEFORE:return "notify" # In-app prompt to user about upcoming archivereturn "active"
The value of a notification logic is often underestimated. If users receive a prompt a day before archiving, most will proactively return to the session or export the content, which subsequently reduces the service provider’s storage pressure.
3.2 Token-based Input Length Governance
Input validation should be completed before the request enters the inference queue. The following example assumes that count_tokens is provided by the tokenizer used on the server side:
MAX_INPUT_TOKENS = 32_000def validate_input(text: str, count_tokens) -> None:n = count_tokens(text)if n > MAX_INPUT_TOKENS:raise ValueError(f"Input contains {n} tokens, exceeding the limit of {MAX_INPUT_TOKENS}. ""Please submit in segments or generate a summary before sending.")
Error messages should include actual values and actionable suggestions. Returning only “request failed” forces users to guess the reason and triggers a large number of repeated requests.
3.3 Tiered Token Bucket Rate Limiting
Using the same set of parameters for all users forces light users and heavy users to pay the same price. A more reasonable approach is to set different bucket capacities and refill rates based on user tiers, while retaining burst allowances.
import timeclass TokenBucket:def __init__(self, rate: float, capacity: float):self.rate = rate # Tokens added per secondself.capacity = capacity # Bucket capacity, determines allowed burstself.tokens = capacityself.updated_at = time.monotonic()def allow(self, cost: float = 1.0) -> bool:now = time.monotonic()self.tokens = min(self.capacity,self.tokens + (now - self.updated_at) * self.rate,)self.updated_at = nowif self.tokens >= cost:self.tokens -= costreturn Truereturn False
The cost can be calculated based on the number of tokens in the request rather than being fixed at 1. This ensures that longer requests consume more quota, keeping traffic control consistent with actual resource consumption.
3.4 Basic Formula for Capacity Planning
Rate limiting only temporarily mitigates pressure and cannot replace capacity planning. Service providers should regularly estimate the required compute power using the following formula:
Required throughput (tokens/sec) ≈ DAU × average requests per user per day × average tokens per request ÷ 86400 × peak coefficient
Using a set of hypothetical numbers: DAU of 1 million, 20 requests per person per day, an average of 2,000 tokens per request, and a peak coefficient of 3. The average daily throughput is about 460,000 tokens/sec, and the peak demand is about 1.39 million tokens/sec. If existing resources can only support the average level, queuing, timeouts, or service denials will occur during peak hours.
The value of this formula lies in exposing the variables. DAU growth, longer requests per call, and sharper peaks will all increase the required throughput. Teams should continuously monitor these metrics rather than just looking at total user counts.
3.5 Communicating Changes
Adjusting constraints is a technical decision, but what users feel is a product change. Poor communication can turn a technically reasonable adjustment into a trust issue.
In practice, a few principles can be followed:
- Announce in advance, specifying the effective time, scope of impact, and alternatives.
- Set up a transition period to give users time to export or migrate content.
- Provide recovery paths, such as paid tiers, export features, or data archive downloads.
- Make error messages specific, explaining which rule was triggered, the current value, and the next step.
4. Common Pitfalls
Pitfall 1: Using rate limiting to mask capacity issues. Rate limiting can reduce peak pressure, but it cannot increase compute power. If average daily demand consistently exceeds supply, the team needs to scale up, optimize model inference efficiency, or adjust product strategy, rather than continuously tightening user quotas.
Pitfall 2: Treating deletion as the only means of storage governance. Direct deletion is the simplest but amplifies user loss. Tiered archiving and export entries can reduce negative impacts at a similar cost.
Pitfall 3: Only looking at averages. When the average load is normal, the system can still crash during peak hours. Capacity planning and rate limiting parameters should be designed based on peaks.
Pitfall 4: Changing rules without notification. The rationale of technical adjustments cannot be automatically understood by users. Unannounced rule changes, even if technically correct, will trigger numerous complaints and churn.
5. Implementation Checklist
- Does the session calculate idle duration based on the last active time, and remind users before archiving?
- Is the input limit counted by tokens, and does the error message include the actual value and suggestions?
- Does the rate limiting differentiate user tiers and retain a reasonable burst allowance?
- Does the capacity model include the four variables: DAU, average requests per user, average tokens, and peak coefficient, and is it reviewed regularly?
- Do rule changes include announcements, a transition period, and recovery paths?
