Managing Long Conversations and Inputs Under LLM Service Usage Limits
This article explains how to build predictable LLM applications when service providers impose session retention limits, per-request input caps, and daily usage quotas. It covers impact assessment, externalized conversation state, chunking and hierarchical summarization for long inputs, and quota-aware request scheduling with distinct handling for exhausted quotas and temporary capacity pressure.
1. The Nature of the Problem: Quota Management Under Limited Compute
LLM inference consumes substantial compute resources and GPU memory. Service providers typically need to support many concurrent users with limited capacity, so they place constraints on how users interact with the service. These constraints generally fall into three layers: session-level lifecycle management, request-level input length limits, and account-level usage quotas. Each corresponds to a different resource dimension, and developers need to understand and handle them separately.
From an engineering perspective, these limits are not surprising. Long-context sessions require the service to retain intermediate state associated with historical tokens, and longer contexts consume more memory. Longer single inputs increase the computational cost of each inference call. Daily quotas are a way to smooth overall load. When load exceeds capacity, providers typically return a message indicating capacity pressure rather than allowing requests to queue until they time out.
For developers, the key is to treat these limits as input conditions for system design, not as occasional failures. A well-designed application should still produce predictable behavior when limits take effect.
2. Technical Meaning of the Three Types of Limits
2.1 Session Retention Period
Session retention period refers to the service provider’s policy for reclaiming long-inactive sessions. When a session has no new requests for a period of time, the service may release its context cache, after which the session cannot be resumed directly.
This policy has a significant impact on tasks that need to progress across multiple cycles. For example, a technical design discussion may last several weeks, and users expect the assistant to remember previous decision rationale. If the service relies only on a session ID to preserve history, then after reclamation the user can only restate the background.
The core approach is not to keep critical state only on the server. Developers should retain summaries, key conclusions, and pending items in local or owned storage, and inject that information back into the context when resuming a session.
2.2 Per-Request Input Length Limit
The per-request input limit is usually measured in tokens, while users are more accustomed to estimating by characters or word count. Chinese and English have different character-to-token ratios, and the same number of characters can correspond to very different token counts depending on language and text type. Therefore, when using character count as a safety threshold, leave headroom rather than inputting close to the upper limit.
Long-text scenarios, such as an entire report, a large code repository, or bulk reference material, will directly hit this limit. Ordinary Q&A is barely affected, but when processing long documents, the narrowed input space makes one-shot submission infeasible.
The response is chunking and hierarchical summarization. Section 5 provides a concrete implementation.
2.3 Daily Quota and Capacity Messages
The daily quota is an account-level usage control. When the day’s usage reaches the cap, requests are rejected and a message is returned indicating that the quota is exhausted or the service is busy. These two cases require different engineering handling: quota exhaustion means further retries are pointless and the quota reset must be awaited, while temporary capacity pressure can usually be recovered through backoff retries.
Developers should distinguish these two types of errors on the client side and apply different strategies. Treating them as the same leads to two outcomes: either continuing to send requests after quota exhaustion and wasting connection resources, or giving up immediately during temporary congestion and losing tasks that could have been recovered.
3. Impact Assessment: Quantify First, Then Design
Before modifying the system, first determine which business flows are most affected. A matrix by user type and task type can help.
| User Type | Typical Scenario | Mainly Affected Limit | Risk Level |
|---|---|---|---|
| Everyday Q&A users | Looking up information, simple rewriting | Daily quota | Low |
| Long-document users | Report review, contract comparison | Per-request input limit | High |
| Cross-cycle project users | Design iteration, long-term research | Session retention period | High |
| Batch processing tasks | Data labeling, bulk summarization | Daily quota, per-request input limit | High |
The assessment should also track several quantifiable metrics: daily request count, average input character count, failure rate per task, session resume failure rate, and the curve of quota usage over time. These metrics determine optimization priorities. If the session resume failure rate is very low, there is no need to prioritize building externalized session capability.
4. Externalizing Session State: Reduce Dependence on Server-Side History
The basic approach to externalizing sessions is for the client or business service to write key information to owned storage after each conversation turn. When resuming a session, reassemble the prompt content, including system instructions, historical summaries, key facts, and the most recent raw messages.
This design provides three benefits. First, the business no longer depends on whether the server retains history. Second, summaries and facts can be reviewed and corrected manually, reducing the accumulation of incorrect information. Third, the storage layer can scale independently and be included in existing backup and audit systems.
The following example uses the standard library to implement a simple conversation store. Writes use a temporary file plus atomic replacement to avoid file corruption caused by interrupted writes. Session IDs are validated to prevent path traversal.
import jsonimport refrom dataclasses import dataclass, field, asdictfrom pathlib import PathSESSION_ID_PATTERN = re.compile(r"[A-Za-z0-9_-]{1,64}")@dataclassclass ConversationRecord:session_id: strsummary: strkey_facts: list[str] = field(default_factory=list)last_message_index: int = 0class ConversationStore:def __init__(self, root: Path) -> None:self.root = rootself.root.mkdir(parents=True, exist_ok=True)def _path_for(self, session_id: str) -> Path:if not SESSION_ID_PATTERN.fullmatch(session_id):raise ValueError("Invalid session ID")return self.root / f"{session_id}.json"def save(self, record: ConversationRecord) -> None:path = self._path_for(record.session_id)tmp = path.with_suffix(".tmp")tmp.write_text(json.dumps(asdict(record), ensure_ascii=False, indent=2),encoding="utf-8",)tmp.replace(path) # Atomic replacement within the same filesystemdef load(self, session_id: str) -> ConversationRecord | None:path = self._path_for(session_id)if not path.exists():return Nonedata = json.loads(path.read_text(encoding="utf-8"))return ConversationRecord(**data)def build_resume_prompt(record: ConversationRecord, recent_messages: list[str]) -> str:facts = "\n".join(f"- {fact}" for fact in record.key_facts)recent = "\n".join(recent_messages)return (f"Below is a summary of the previous discussion:\n{record.summary}\n\n"f"Confirmed key facts:\n{facts}\n\n"f"Most recent conversation:\n{recent}\n\n""Please continue the discussion based on the information above.")
In use, call save after each conversation turn to update the summary. The summary can be generated by the model, but key facts should ideally be confirmed by the user before being written, to avoid solidifying incorrect information.
5. Chunking and Hierarchical Summarization for Long Inputs
For text that exceeds the per-request input limit, a common approach is to split first, process each chunk, and then merge the results. Splitting should prioritize paragraph or section boundaries, and only fall back to hard character cuts when there is no obvious boundary. Keep some overlap between adjacent chunks so that critical information is not truncated exactly at the cut point.
The following function splits text by character count and keeps an overlap region between adjacent chunks. In real projects, you can first split by blank lines, then combine paragraphs into chunks that do not exceed the limit.
def split_text(text: str, max_chars: int, overlap: int = 200) -> list[str]:if max_chars <= overlap:raise ValueError("max_chars must be greater than overlap")chunks: list[str] = []start = 0while start < len(text):end = min(start + max_chars, len(text))chunks.append(text[start:end])if end == len(text):breakstart = end - overlapreturn chunks
After splitting, use a “split first, merge later” strategy. The first layer generates a local summary for each chunk, and the second layer merges all local summaries into a global summary. This method applies to report review, question answering over large documents, and codebase summarization.
from collections.abc import Callabledef hierarchical_summarize(text: str,call_model: Callable[[str], str],max_chars: int = 20000,) -> str:"""call_model is injected by the caller and receives prompt text, returning model output."""chunks = split_text(text, max_chars=max_chars)partial = [call_model(f"Please summarize the key points of the following content concisely:\n{chunk}")for chunk in chunks]if len(partial) == 1:return partial[0]merged = "\n".join(partial)return call_model(f"Please consolidate the following partial summaries into a complete summary:\n{merged}")
This function assumes that each chunk and the merged summary can fit within the input limit. If the total size of the local summaries is still too large, apply the same process recursively until the result can be supplied in one request.
Note that hierarchical summarization loses detail. For precise information such as contract clauses and numerical metrics, retain source locations, such as section numbers or paragraph indexes, so they can be reviewed.
6. Quota-Aware Request Scheduling
The client needs to distinguish two types of failure: quota exhaustion and temporary capacity pressure. The former should stop retries and suspend the task until the quota resets; the latter is suitable for a retry strategy using exponential backoff plus random jitter. Random jitter prevents many clients from reissuing requests at the same moment and causing secondary congestion.
import randomimport timeclass QuotaExhausted(Exception):"""Daily quota exhausted; retrying is pointless and the reset should be awaited."""class TransientBusy(Exception):"""Service temporarily busy; suitable for retry after backoff."""
The retry helper should accept parameters such as max_attempts, base_delay, and max_delay, and should apply exponential backoff with random jitter between attempts. When the error is QuotaExhausted, the task should be suspended rather than retried. When the error is TransientBusy, the request can be retried until the maximum number of attempts is reached.
