Rate Limiting and Quota Scheduling for LLM Services During Peak Demand
This article examines how LLM inference services manage rate limiting and quota scheduling when demand outpaces capacity. It distinguishes admission control from long-term quotas, analyzes session resource retention, request cost variance, and burst queuing, and presents practical approaches such as token-bucket admission, compute-based quota accounting, idle-session reclamation, priority scheduling, and queue timeouts. It also covers user-facing error design, observability, capacity planning, common pitfalls, and implementation recommendations.
1. Background: What Breaks First When Demand Outpaces Supply
The cost structure of LLM inference services differs from that of ordinary web services. Each request consumes accelerator memory and compute time, and output length is not known in advance. As active users grow quickly, compute expansion requires procurement, deployment, and validation, often on a monthly or quarterly cycle. When a gap opens between demand and capacity, the service provider can only trade off among three options: reject some requests, extend waiting time, or reduce the resource consumption of each request.
It is important to distinguish two concepts. Rate limiting protects the system from short-term traffic spikes and focuses on how many requests can be accepted per second. Quotas allocate long-term resource allowances by user or plan and focus on how much total resource can be used over a period. They are often conflated, but their design goals and implementations differ.
2. Problem Breakdown
1. Long sessions hold resources. Inference services usually keep a context cache (such as KV Cache) for a session. A session that has been inactive for a long time still occupies accelerator memory and squeezes the resources available to active requests. If such resources are not reclaimed, utilization gradually declines.
2. Request costs vary widely. The compute required for a short Q&A request and a long document analysis request can differ by dozens of times. If only request count is used, lightweight requests are underestimated and heavy requests can crowd out other users’ resources.
3. Burst traffic compounds queuing. Concentrated access during peak periods forms queues within a short time. Without admission control, queue time keeps growing, eventually causing many requests to time out and reducing overall system throughput.
3. Technical Approaches
3.1 Admission Layer: Token-Bucket Rate Limiting
A token bucket replenishes tokens at a fixed rate. Each request consumes a corresponding number of tokens, and when the bucket is empty, requests are rejected or queued. It allows a certain degree of burst traffic while constraining the long-term average rate. It is smoother than fixed-window counters and makes it easier to set consumption based on different costs.
import threadingimport timeclass TokenBucket:def __init__(self, rate: float, capacity: float):self.rate = rate # Tokens replenished per secondself.capacity = capacity # Maximum bucket capacityself.tokens = float(capacity)self.updated_at = time.monotonic()self.lock = threading.Lock()def try_acquire(self, cost: float = 1.0) -> bool:with self.lock:now = time.monotonic()elapsed = now - self.updated_atself.tokens = min(self.capacity, self.tokens + elapsed * self.rate)self.updated_at = nowif self.tokens >= cost:self.tokens -= costreturn Truereturn False
In practice, a separate bucket is usually maintained for each user or API key, and cost is set to the request’s compute load rather than a fixed value of 1.
3.2 Quota Layer: Metering by Compute
The metering unit should relate to real cost. A common approach is to take a weighted sum of input tokens and output tokens. Output tokens usually need to be generated one by one, so their unit cost is higher than that of input tokens and their weight should be larger. There is no universal standard for the weight values; teams should calibrate them against their own load-test data.
def request_cost(input_tokens: int, output_tokens: int,w_in: float = 1.0, w_out: float = 4.0) -> float:"""Weights are illustrative and should be calibrated against actual load-test results."""return w_in * input_tokens + w_out * output_tokens
Quotas can be divided into three types and used in combination:
- Concurrency limit: the number of simultaneous requests from one user, preventing a single user from filling the queue.
- Time-window quota: for example, total compute available in a rolling 5-hour window, used to smooth usage pace.
- Long-term total quota: for example, allocated by calendar week or calendar month, used for plan or resource allocation management.
Quota rules should be written into configuration rather than hard-coded, so they can be adjusted when capacity changes and explained to users.
3.3 Session Resource Reclamation
An idle-session reclamation strategy needs to meet two goals at the same time: releasing resources and not losing user data. A recommended approach is to separate “releasing compute resources” from “deleting session data”.
IDLE_LIMIT_SECONDS = 7 * 24 * 3600def reclaim_idle_sessions(sessions, now: float) -> list[str]:released = []for s in sessions:idle = now - s.last_active_atif idle > IDLE_LIMIT_SECONDS and s.cache_loaded:s.release_cache() # Release only the cache held in GPU memorys.status = "cache_released"released.append(s.id)return released
After cache release, the session’s message history remains in storage. When the user returns, the system can reload historical messages or inform the user that the session has been compacted. Reclamation tasks should run as background batch jobs and record the number of sessions released for auditing.
3.4 Tiered Scheduling
Requests at the same moment differ in how sensitive they are to experience. Interactive dialogue requires low latency, while batch offline tasks can accept longer waits. Tiered scheduling assigns priority labels to requests and processes high-priority requests first when resources are tight.
import heapqimport itertools_counter = itertools.count()queue: list = []def enqueue(request, priority: int) -> None:# Lower priority value is processed first; counter preserves FIFO order within the same priorityheapq.heappush(queue, (priority, next(_counter), request))def dequeue():if not queue:return None_, _, request = heapq.heappop(queue)return request
Priority should be defined by business semantics, not user identity. For example, interactive requests can be 0, asynchronous tasks 1, and offline batch processing 2. Dividing strictly by paid tier can raise fairness concerns and leave low-priority users without responses for long periods.
3.5 Queue Timeouts and Degradation
Queuing cannot continue indefinitely. Every request should have a maximum wait time, and after timeout it should return a clear error rather than leaving the connection hanging. Degradation strategies can reduce service wear during peak periods. Common measures include:
- Limit the maximum output length per request to reduce the time each request occupies resources;
- Switch to a smaller model without affecting functionality, and indicate the model actually used in the response;
- Temporarily disable or defer non-critical features (such as long-document summarization or batch export).
Degradation must be observable. Silently changing the model or truncating output can make users mistake reduced result quality for a system failure and create trust issues.
4. Making Limit Status Understandable
Rate limits and quotas ultimately need to be communicated to users through APIs and interfaces. Vague messages such as “server busy” do not tell users what the problem is, when they can retry, or what they can do. A qualified error response should include the error type, retry time, and next-step guidance.
{"error": {"code": "rate_limited","message": "The current request volume is high. Please retry after 30 seconds.","retry_after_seconds": 30,"quota": {"window": "rolling_5h","remaining_ratio": 0.12}}}
At the HTTP layer, rate limiting should return a 429 status code and use the Retry-After header to tell the client how long to wait. Clients should implement exponential backoff based on that value so that all requests do not re-enter at the same moment.
In product interfaces, show the remaining allowance in the current window, the next refresh time, and the idle state of sessions. This information significantly reduces guesswork for users and lowers the extra load caused by repeated submissions.
5. Observability and Capacity Planning
Without monitoring, it is impossible to judge whether rate-limiting parameters are reasonable. At minimum, collect the following metrics:
- Request volume and rejection rate: break down by user tier, endpoint, and time period to identify abnormal traffic.
- Queue duration percentiles: focus on P95 and P99, not averages. Averages can hide many long-tail requests that time out.
- Cache occupancy and reclamation volume: observe the distribution of idle sessions to judge whether reclamation is too aggressive or too conservative.
- Average compute per request: used to calibrate quota weights and estimate capacity requirements.
Capacity planning should use queue duration as the expansion signal. When P95 queue duration consistently exceeds a threshold, or the rejection rate rises steadily outside abnormal periods, supply is close to its limit. Expansion should leave headroom, typically starting when utilization reaches 70% to 80%, to cover deployment cycles and burst traffic.
6. Common Pitfalls
Pitfall 1: Treating limits as a billing signal. Limits usually come from capacity constraints, cost control, or fairness considerations. Whether to charge is a business decision and a separate issue from the technical rate-limiting mechanism. Keeping the two separate in design helps make clearer judgments when conditions change.
Pitfall 2: Limiting only total volume. A daily total alone cannot prevent a single user from consuming all resources in a short period. Set rate limits, concurrency limits, and time-window quotas together.
Pitfall 3: Silently dropping requests. Dropping or truncating requests without notice leaves users unable to determine the cause or plan a retry. Reject requests with clear error information.
Pitfall 4: Deleting user data when reclaiming resources. Releasing compute resources and deleting user data are two different things. The former is a runtime optimization; the latter involves data retention policies and user rights and should be designed and approved separately.
7. Implementation Recommendations
- Collect the real distribution of request compute before setting quota weights; do not rely on intuition.
- Start with conservative rate-limiting parameters and relax them gradually, validating results with queue duration metrics.
- Put rate limiting, quota, and reclamation policies in a configuration center so they can be adjusted without redeploying.
- Write standard error codes for every rejection and degradation scenario and update clients and documentation at the same time.
- Record the reason for each policy change and the metrics before and after, creating a traceable decision basis.
Rate limiting and quotas are not merely “blocking” mechanisms; they are a rule system for resource allocation. When designed well, they allow limited compute to serve the requests that need it most and let users clearly understand their current state and next action.
