Managing Context Limits and Quotas in Long LLM Conversations
Long LLM conversations can stop working for several reasons, including context window limits, message restrictions, and exhausted compute quotas. This article explains how to distinguish these constraints and manage them through history trimming, rolling summaries, server-enforced quotas, actionable error messages, and portable conversation exports. Python examples and testing guidance illustrate how to make resource limits more predictable and recoverable for users.
1. Why Long Conversations Stop Working
Users of LLM chat applications commonly encounter situations such as these:
- They return to a long conversation after several days and find that it has expired and cannot continue.
- A message cannot be sent because the input is too long or has been edited too many times.
- A conversation reaches its message limit, requiring a new conversation.
- A notice above the input field reports insufficient quota or compute capacity, and some features become temporarily unavailable.
To users, these situations may all look like the application has suddenly stopped working. From an engineering perspective, however, they arise from different constraints. Identifying the source determines where to handle the restriction and what information to show the user.
2. Understanding the Limits
2.1 Context Windows
A model can process only a limited number of tokens in a single inference request. As a conversation grows, each request may need to carry more history, increasing computation and GPU memory usage.
There is no fixed conversion between tokens and characters. Tokenizers handle English, Chinese, and code differently, so character counts alone are not a reliable way to determine whether a request exceeds the context window.
2.2 Input and Message Restrictions
Servers commonly impose limits on individual input length, the number of messages in a conversation, and the number of edits to a message. These restrictions help prevent abnormal traffic, control storage costs, and maintain response quality for other users.
2.3 Compute Capacity and Quotas
Services allocate quotas by user, model, and time window. Once a quota is exhausted, a service may reject requests, fall back to a smaller model, or ask the user to wait for the quota to reset.
Quota usage is typically tracked on the server. Clients can only synchronize and display that information periodically, so their displayed state may lag behind the server.
3. Design Principles
Limits are difficult to eliminate, but their impact on the user experience can be reduced. Three principles are especially useful:
- Make limits visible: Explain why a restriction occurred instead of displaying a generic error.
- Provide a recovery path: Tell users what they can do next, such as shorten the input, start a new conversation, wait for a quota reset, or export the history.
- Support portability: Allow conversation data to be exported in a standard format so that restrictions do not leave users without access to their work.
4. Strategy One: Trim Conversation History
The most direct approach is to trim history to a token budget before sending a request. A common strategy preserves system prompts, then works backward through recent messages until the budget is exhausted.
from dataclasses import dataclass@dataclassclass Message:role: str # "system" | "user" | "assistant"content: strdef estimate_tokens(text: str) -> int:"""Rough estimate. Use the target model's tokenizer in production."""return max(1, len(text) // 2)def trim_history(messages: list[Message], max_tokens: int,reserve_for_reply: int = 1024) -> list[Message]:budget = max_tokens - reserve_for_replysystem_msgs = [m for m in messages if m.role == "system"]dialog = [m for m in messages if m.role != "system"]used = sum(estimate_tokens(m.content) for m in system_msgs)kept: list[Message] = []for msg in reversed(dialog):cost = estimate_tokens(msg.content)if used + cost > budget:breakkept.append(msg)used += costreturn system_msgs + list(reversed(kept))
Trimming discards earlier information. For example, constraints supplied in the first exchange may no longer be present by the fiftieth. History trimming therefore usually needs to be combined with summarization or another mechanism for retaining key information.
5. Strategy Two: Use Rolling Summaries
A rolling summary compresses older exchanges once the history exceeds a threshold. The summary is then retained near the beginning of the context as a system message.
SUMMARY_THRESHOLD = 40 # Compress when non-system messages exceed this countKEEP_RECENT = 10 # Always preserve the most recent messages verbatimdef compress_history(messages, call_llm):system_msgs = [m for m in messages if m.role == "system"]dialog = [m for m in messages if m.role != "system"]if len(dialog) <= SUMMARY_THRESHOLD:return messagesold, recent = dialog[:-KEEP_RECENT], dialog[-KEEP_RECENT:]transcript = "\n".join(f"{m.role}: {m.content}" for m in old)summary_text = call_llm("In no more than 500 characters, summarize the user's goals, ""confirmed constraints, and unfinished tasks in this conversation:\n"+ transcript)summary_msg = Message(role="system",content=f"[Conversation summary]\n{summary_text}")return system_msgs + [summary_msg] + recent
Three considerations are important:
- Specify what the summary must retain. The prompt should explicitly identify elements such as user goals, constraints, and unfinished tasks.
- Preserve critical details separately. Summaries lose information. Important numbers, code snippets, and proper names are best extracted into structured fields.
- Evaluate summary quality regularly. Review samples against the original conversations or use automated factual-consistency checks.
6. Strategy Three: Retrieve and Display Quota Status
Quota information usually comes from the server. Clients must balance freshness against the cost of repeated requests. Common practices include:
- Poll only while the page is visible, and pause polling when it moves into the background.
- Use a reasonable synchronization interval, such as every few minutes, and have the server return current quota information when the user submits a request.
- Make the input field read-only when quota is exhausted, and show the time until reset or available alternatives.
import timefrom dataclasses import dataclass@dataclassclass QuotaState:remaining: intreset_at: float # Unix timestampclass QuotaCache:def __init__(self, fetch_fn, ttl_seconds: int = 300):self._fetch = fetch_fnself._ttl = ttl_secondsself._state: QuotaState | None = Noneself._fetched_at = 0.0def get(self) -> QuotaState:now = time.time()if self._state is None or now - self._fetched_at > self._ttl:self._state = self._fetch()self._fetched_at = nowreturn self._statedef can_send(self) -> bool:return self.get().remaining > 0
Client-side quota checks are only for user feedback. Enforcement must happen on the server. Otherwise, users could bypass limits by modifying local state, potentially causing uncontrolled service costs.
7. Classify Errors and Provide Actionable Messages
Mapping restrictions to explicit error categories helps frontend teams and operations staff identify problems quickly. The following table provides a reference classification.
| Error category | Typical trigger | User action | System response |
|---|---|---|---|
| Context limit exceeded | A single input or the combined history exceeds the context window | Shorten the input, or export the history and start a new conversation | Return a specific error code and offer a trimming option |
| Edit limit reached | A message has reached its edit threshold | Rephrase the question and create a new message | Record the event and avoid endless retries |
| Conversation message limit reached | A conversation reaches its maximum message count | Start a new conversation, optionally referencing a history summary | Provide a one-click option to start a conversation with a summary |
| Insufficient quota | The quota for the current period is exhausted | Wait for the reset or use other available resources | Return the time until reset and enforce the restriction server-side |
| Service degradation | Compute constraints reduce service availability | Retry later | Queue requests or provide degraded service, and communicate an estimated recovery time |
Avoid vague messages such as “Request failed.” Every message should explain at least the cause, the scope of the restriction, and the next available action.
8. Export Conversations for Data Portability
When a conversation cannot continue because of a limit, export is an important way to preserve user data. A line-oriented structured text format makes exported conversations easier for other systems to read and import.
import jsonfrom datetime import datetime, timezonedef export_conversation(conversation_id: str, messages, path: str) -> None:with open(path, "w", encoding="utf-8") as f:for i, m in enumerate(messages):record = {"conversation_id": conversation_id,"index": i,"role": m.role,"content": m.content,"exported_at": datetime.now(timezone.utc).isoformat(),}f.write(json.dumps(record, ensure_ascii=False) + "\n")
Export functionality should follow these guidelines:
- Exports should be initiated by the user and include only conversations that user is authorized to access.
- Export fields should remain consistent, with a documented schema to support downstream imports.
- Export activity should be recorded in audit logs, but those logs should not contain conversation content.
- If a conversation contains sensitive information, prompt the user for confirmation before exporting.
9. Testing and Monitoring
Limit-handling logic is prone to boundary errors and needs dedicated test coverage.
- Create conversations that are exactly at, slightly above, and far above the token budget, and verify that trimming behaves as expected.
- Verify that system messages are preserved under every trimming strategy.
- Verify that the most recent messages remain intact after summarization.
- Simulate quota exhaustion and reset timing, and check whether the client display updates promptly.
In production, monitor:
- The proportion of requests that trigger context trimming, to assess whether budgets are appropriate.
- The frequency and distribution of each limit-related error category.
- Summary request latency and failure rates.
- Export success rates and average file sizes.
- User actions after an error message, such as abandoning the task, starting a new conversation, or exporting the history.
When metrics change unexpectedly, first determine whether the cause is a budget configuration issue, a traffic spike, or a regression introduced by a release.
10. Conclusion
Long-conversation limits are a common challenge in LLM applications. They largely arise from context length, service costs, and quota management.
A layered approach reduces their impact: use trimming and rolling summaries to control context size, combine server-side quota enforcement with client-side caching, provide clear error categories and recovery actions, and support standardized exports for data portability.
Together, these measures help keep the application predictable, understandable, and recoverable even when resources are constrained.
