LLM Service Limits: Long-Text Processing and Capacity Strategies
This article explains how to design LLM-backed systems when providers enforce input-size, session-retention, rate, and quota limits. It covers token budgeting, paragraph-based chunking, rolling conversation summaries, differentiated retry and backoff, local daily budgets, queueing and caching, plus a deployment checklist for capacity planning and graceful degradation.
1. Background: Quotas and Capacity Limits Are Now Routine
The available capacity of large language model services is constrained by compute supply. To maintain overall stability, providers often set limits on the input length per request, session retention time, and total calls or usage within a period. These limits are fundamentally different from service outages. An outage is a passive degradation after a system anomaly, while a capacity limit is an active adjustment made by the provider based on load and usually follows defined rules and reset periods.
Before handling these limits, developers need to answer three questions: Can the error be retried? Is there a clear recovery time? Does the limit apply to a single request or to cumulative usage? Different answers require different handling.
2. Three Typical Limits and Their Technical Implications
2.1 Single-Input Length Limit
Models process text in tokens, not characters. The conversion ratio between Chinese and English differs, and the same text can produce different token counts under different tokenization methods. Estimating input size by character count therefore gives only a rough result. Before launch, use the tokenizer for the corresponding model to count tokens precisely, and reserve margin for system prompts, historical messages, and output content.
Long documents, long code, and full-material processing are typical high-consumption scenarios. When the input exceeds the limit, direct truncation can lose critical information. A more reliable approach is to split the input into chunks, extract key points from each chunk, and then summarize them.
2.2 Session Retention and Context Recycling
Historical messages in long sessions continue to occupy the context window. Providers may reclaim storage for sessions that have been inactive for a long time or stop continuing their context. Business systems should therefore not rely entirely on the server to store all conversation state. Session records should be kept in owned storage, and context should be reassembled when needed.
2.3 Rate Limits and Periodic Quotas
Rate limiting usually falls into two categories. A rate limit constrains the number of requests or tokens within a unit of time; after it is triggered, waiting for a period and retrying usually works. A quota limit constrains total usage within a statistical period; once exhausted, retrying is meaningless, and the only options are to wait for the period to reset, request a higher quota, or switch to another approach. The error information returned by these two types of limits often differs, and specific error codes should follow the provider’s documentation. Programs need to handle them according to status codes and error types rather than applying unlimited retries to every error.
3. Design Principles
- Externalize state: Keep session records, document chunk results, and intermediate summaries in owned storage; the server is responsible only for inference.
- Budget upfront: Estimate token usage before sending a request and compare it with the local budget; block locally when it exceeds the limit.
- Tiered degradation: Prioritize core business paths; non-critical tasks can be queued, delayed, or moved to a lighter model.
- Observability: Log input volume, output volume, latency, and error type for each request to provide data for capacity planning.
4. Practical Approaches
4.1 Chunk by Paragraph Boundaries
When chunking, prefer paragraph boundaries and keep an overlap region of a certain length to avoid breaking semantics at the boundary.
def split_text(text, max_chars=20000, overlap=500):"""Split long text at paragraph boundaries, with overlap between adjacent chunks."""chunks = []start = 0while start < len(text):end = min(start + max_chars, len(text))if end == len(text):chunks.append(text[start:end])break# Prefer a paragraph separator in the second half; otherwise hard cutcut = text.rfind("\n\n", start + max_chars // 2, end)if cut == -1:cut = endchunks.append(text[start:cut])start = max(cut - overlap, start + 1)return chunks
Key points can be extracted from each chunk separately, and the points can then be merged into a single summarization request. This controls the size of each input while retaining the main information from the full text.
4.2 Compress Conversations with Rolling Summaries
When historical messages exceed the budget, earlier messages can be compressed into a summary while only the most recent turns are kept in full. The summary can be generated by a model or extracted with rules for key sentences, depending on the trade-off between accuracy and cost.
def compress_history(history, summarize, keep_recent=6, budget_chars=8000):"""When history exceeds budget, compress older messages into a single summary."""total = sum(len(m["content"]) for m in history)if total <= budget_chars:return historyold, recent = history[:-keep_recent], history[-keep_recent:]summary = summarize(old)return [{"role": "system", "content": f"Previous conversation summary: {summary}"}] + recent
The summary should preserve user goals, confirmed constraints, and unresolved issues. Irrelevant greetings and repeated content can be dropped directly.
4.3 Differentiated Retry with Backoff
Rate limits and transient server overload are suitable for retries with exponential backoff and random jitter, which prevents many clients from retrying at the same moment. Quota exhaustion should be terminated directly and reported to the upper layer.
import randomimport timeRETRYABLE_STATUS = {429, 500, 502, 503, 504}def call_with_backoff(send, payload, max_retries=5):"""send returns (status_code, body). Retry with backoff only for retryable errors."""for attempt in range(max_retries + 1):status, body = send(payload)if status == 200:return bodyif status not in RETRYABLE_STATUS or attempt == max_retries:raise RuntimeError(f"Request failed: status={status}, body={body}")# Exponential backoff, capped at 30 seconds, plus random jitterdelay = min(2 ** attempt, 30) + random.uniform(0, 1)time.sleep(delay)
In actual deployment, the send function also needs to inspect the error type in the response body. If the error is quota-related, it should bypass the retry logic and throw a custom exception, leaving the scheduling layer to decide whether to queue the task or switch to another approach.
4.4 Local Quota Control
Maintaining a daily budget counter on the client side can avoid repeated requests after the quota is exhausted and can help the business layer provide early warnings.
from datetime import dateclass DailyBudget:def __init__(self, daily_limit):self.daily_limit = daily_limitself._day = date.today()self._used = 0def try_consume(self, tokens):today = date.today()if today != self._day:self._day, self._used = today, 0if self._used + tokens > self.daily_limit:return Falseself._used += tokensreturn True
Local counting can only be an approximation. Actual usage should be based on the statistics returned by the provider, and the local count should be calibrated periodically.
5. Peak Shaving and Off-Peak Scheduling
Not every request needs a real-time response. Batch summarization, offline index construction, report generation, and similar tasks can be placed in queues and executed during periods of lower load. If the provider offers differentiated billing by time period, task scheduling can be adjusted accordingly. Queue length, concurrency, and timeout values should have upper limits to prevent backlogged tasks from crowding out online business resources.
Caching can also reduce call volume. For requests with the same input and stable results, model output can be cached with a reasonable expiration time. For requests involving personal information or sensitive content, desensitization and permission checks should be completed before caching.
6. Deployment Checklist
- Validate input length with the tokenizer for the corresponding model and reserve space for output.
- Store session records and chunk results in owned storage, with support for rebuilding context on demand.
- Retry logic distinguishes among rate limits, transient overload, and quota exhaustion.
- Maintain a daily budget counter on the client side and periodically reconcile it with usage returned by the provider.
- Put non-real-time tasks into queues and set concurrency and timeout limits.
- Log request volume, latency, error types, and cost, and configure alert thresholds.
- Define degradation plans for limit changes, such as switching to a lighter model or pausing non-core features.
Quota policies may change as capacity changes. System design should place limit parameters in configuration rather than hardcoding them in business logic. When rules change, this allows teams to update configuration and validate it without republishing code.
