Session Management and Rate Limiting Design for LLM Chat Services Under Quota Changes
This article examines how quota and resource constraints in LLM conversation services translate into three user-visible limitations: session lifetime, per-request input size, and periodic usage caps. It discusses the engineering design behind each constraint, including session archiving and recovery, long-text chunking, quota and rate-limiting algorithms, client-side retry behavior, and observability for capacity planning. The goal is to help developers build conversation systems where quota changes remain predictable, recoverable, and minimally disruptive to users.
1. Problem Background
The main cost of large language model conversation services comes from inference compute. The resources consumed by a single request depend on input length, output length, and context length. The longer the context, the more computation and GPU memory a single inference step consumes. When compute resources are tight, service providers usually control resource usage in three ways:
- Limit how long a session is retained.
- Limit the size of a single input.
- Limit total usage within a time period.
What end users experience is the combined effect of these three constraints. Common complaints include:
- A long conversation can no longer be resumed after being idle for a while.
- A pasted text block is rejected because it exceeds the input limit.
- The daily quota is exhausted, and requests fail with a “service busy” message.
For developers, these symptoms can be decomposed into measurable, designable, and degradable engineering problems.
2. Technical Meaning of the Three Constraints
2.1 Session Lifecycle
Session state usually includes message history, summaries, and metadata. The server needs storage to hold this state. The longer the history, the more data must be loaded and re-encoded when the session is restored, which increases cost. Therefore, most services set an idle TTL for sessions.
An expiration policy needs to answer two questions:
- Is a recoverable summary retained before expiration?
- Can users export their content after expiration?
If neither question has a clear answer, users will only feel that the conversation “suddenly disappeared.”
2.2 Per-Request Input Limit
An input limit is essentially a hard constraint on token count or character count. When the limit is exceeded, the server typically rejects the request directly or asks the client to split the content. The limit is usually related to the model’s context window and GPU memory budget, not an arbitrary number.
For very long text, a common approach is to split it into chunks, process them separately, and then combine the results. This is more cost-friendly and makes it easier to locate errors.
2.3 Periodic Usage Quota
Usage quotas are usually defined by calendar day, rolling window, or billing cycle. When the quota is reached, the server returns a rate-limit error, and the client must wait until the quota resets. This type of limit is directly tied to cost control, and high-frequency users are most likely to hit it in the middle of a day.
3. Design Principles
A quota system for conversation applications can be designed around four principles:
- Predictable: Quota rules, reset times, and error meanings should be clear to users.
- Degradable: When limits are exceeded, users should still be able to view history, export content, or use a simplified mode, rather than losing service completely.
- Recoverable: Session state can be serialized and migrated, and users can retrieve important information before expiration.
- Observable: Usage curves are recorded per user and per tenant, providing the basis for capacity planning and rule adjustments.
These principles trade off against one another. For example, retaining sessions longer increases storage and recovery cost, so experience and resource usage must be balanced.
4. Session Archiving and Recovery
One practical design is to store sessions in two layers: keep the full message history for a period of time, and after expiration retain only a summary plus the most recent few turns. The pseudocode below illustrates the idea.
function saveSession(sessionId, messageList):write sessionStore(sessionId, messageList, expirationTime = now + idleTTL)if messageList.length > summaryThreshold:summary = generateSummary(earlierMessages)write summaryStore(sessionId, summary)function restoreSession(sessionId):if sessionStore contains sessionId and not expired:return fullMessageHistoryif summaryStore contains sessionId:return summary + recentMessagesreturn empty, and prompt user to create a new session with exportable content
Summaries lose detail, so the product should explain to users that the restored content is a summarized version, not a verbatim history. The system should also proactively remind users to export content before a session is about to expire.
5. Input Control and Chunking for Long Text
For text that exceeds the per-request input limit, preprocessing should happen on the client side or at the gateway layer, so the request does not fail only after reaching the server. Two points matter when chunking:
- Use token count as the primary measure; character count is only approximate.
- Split at paragraph or sentence boundaries, and keep a small overlap between chunks to preserve context continuity.
function chunkText(text, maxChunkSize, overlapLength):chunks = []start = 0while start < text.length:end = min(start + maxChunkSize, text.length)end = findSentenceOrParagraphBoundary(text, end)chunks.append(text[start:end])start = end - overlapLengthreturn chunks
After chunking, the common processing pattern is “process separately, then combine.” First generate a local result for each chunk, then merge the local results into a global output. This works well for long report summaries, batch document processing, and long code reviews. One caveat is that merging can lose dependencies between chunks, so the prompt should explicitly require cross-chunk references to be preserved in the output.
6. Quota and Rate Limiting Algorithms
Rate limiting and quota control usually need two layers:
- A short-period rate limit prevents sudden bursts.
- A long-period total quota controls cost.
These two layers can use different algorithms.
| Algorithm | Mechanism | Advantages | Disadvantages |
|---|---|---|---|
| Fixed window | Counts requests in fixed time intervals | Simple to implement, suitable for daily quotas | Bursts can occur at window boundaries |
| Sliding window | Counts requests over a rolling time window | Smoother, fewer boundary issues | Requires recording data at more time points |
| Token bucket | Tokens are replenished at a fixed rate; requests consume tokens | Allows reasonable bursts, rate is intuitive | Bucket capacity and refill rate need tuning |
The core token bucket logic is as follows:
Token bucket parameters: capacity = C, refill rate = R (per second)function allowRequest(usage):tokens = min(C, tokens + (now - lastTime) * R)lastTime = nowif tokens >= usage:tokens = tokens - usagereturn allowreturn reject, estimatedWaitSeconds = (usage - tokens) / R
A fixed window is suitable for daily quotas: count by calendar day and return the reset time to the client explicitly. For short-period rate limiting, a token bucket is more appropriate because it can absorb reasonable bursts.
7. Client-Side Handling of Limit Exceeded
Clients need to distinguish between two types of failures:
- Transient rate limiting: The request can succeed after a short wait. Exponential backoff with random jitter is appropriate.
- Quota exhausted: Retrying is meaningless. The client should show the user when the quota resets.
function callAPI(request):retries = 0while retries < maxRetries:response = send(request)if response.success:return responseif response.quotaExhausted:throw QuotaExhaustedError(resetTime)if response.transientRateLimited or response.serviceBusy:wait(baseInterval * 2^retries + randomJitter)retries = retries + 1throw ServiceUnavailableError
The key here is error semantics. If the server mixes “quota exhausted” and “service busy” into the same error message, the client cannot decide whether to retry or wait. Splitting them into separate error codes is a low-cost change that significantly improves the user experience.
8. Observability and Capacity Planning
To determine whether quota rules are reasonable, the following metrics should be continuously monitored:
- Number of active sessions and the percentage of expired sessions, to evaluate the impact of session retention policy.
- Distribution of per-request input length, especially the proportion of requests close to the limit.
- Rate-limit rejection rate and quota-exhausted ratio, broken down by user group.
- Request latency percentiles, to identify whether the service is approaching capacity limits.
- Daily usage peaks and valleys, to plan capacity expansion or quota adjustments.
Alerts should be set for these metrics. For example, if the rate-limit rejection rate keeps rising over a period, capacity or quota rules are no longer matching actual demand and should be reviewed.
If the system runs on Baidu AI Cloud, archived session data can be placed in object storage services, long-running tasks can be decoupled from the request lifecycle through message queue services, and the metrics and alert thresholds above can be handled by monitoring and alerting services. These are general cloud capabilities and are independent of any particular quota rule.
9. Implementation Recommendations
- Review long-session use cases in the business. Distinguish between sessions that need to continue across cycles and one-shot Q&A sessions, and design retention strategies for each.
- Add input length pre-checking on the client side. Chunk content that exceeds the limit before sending the request, to avoid invalid calls.
- Separate transient rate limiting from quota exhaustion in error handling, and show the concrete reset time to users in the UI.
- Provide clear entry points for session expiration, export, and recovery. Document the difference between summary restoration and full restoration.
- Build usage dashboards and alert rules. Adjust quotas based on real data rather than experience alone.
Quota rules themselves will change as resource availability changes. The goal of the system design is to make those changes predictable, observable, and controllable in their impact on users.
