Conversation State Engineering for Rate-Limited LLM Services
This article explains why LLM service limits on conversation length, single-request size, and daily quotas are a reflection of inference resource constraints rather than a loss of functionality. It presents an application-side architecture that treats the model as a stateless inference function: tiered session storage (hot, warm, cold), rolling summarization with layered memory, chunking plus retrieval augmentation, quota-aware scheduling with token buckets and graceful degradation, error semantics that separate rate limiting from transient failures, observability metrics, and product safeguards for long-running conversations.
1. The Symptom and the Root Cause: Rate Limits Are Resource Constraints Made Visible
Over the past couple of days, many users who have long relied on a free LLM chat service have found their sessions abruptly interrupted: inactive conversations can no longer be resumed after a certain period, the amount of text accepted in a single request has been reduced, and the total number of conversations per day is now capped, with only a “service busy, try again tomorrow” message once the cap is reached. App store reviews have filled with complaints, and the core demand is consistent: long-running conversations that accumulated hundreds of thousands of characters of context are being forcibly cut off.
From an engineering standpoint, these limits are not a regression in product capability but an inevitable externalization of inference resource constraints. The cost structure of LLM inference differs fundamentally from that of an ordinary web API:
- GPU memory usage scales roughly linearly with context length, so long contexts significantly raise the memory and compute cost of a single request;
- autoregressive decoding makes per-request latency grow with output length, and long conversations tend to produce long outputs;
- traffic is highly bursty, and peak concurrency determines the spare capacity the provider must reserve;
- free traffic carries no price signal, so demand-side peak shaving does not happen organically.
Providers therefore typically impose constraints along three dimensions: session lifetime (reclaiming inactive sessions), per-request size (input length limits), and account-level quotas (daily totals). For application developers, the right response is not to complain about the constraints but to turn “rate limiting that is externally uncontrollable” into “engineering capability that is internally controllable.”
2. Technical Causes and Impact of the Three Limit Types
2.1 Conversations That Cannot Be Resumed: A State Lifecycle Problem
The root cause of non-resumable conversations is that the server no longer retains internal state for long-inactive sessions (such as cached key-value context or session metadata). The lesson is that any architecture relying on the server to implicitly hold state is fragile. Session state must be explicitly modeled, explicitly persisted, and explicitly reclaimed.
2.2 Single-Request Input Limits: Context Window and Cost
Input length caps usually correspond to the model’s context window and memory budget. When the business needs to process long documents, large codebases, or lengthy interview transcripts, you must introduce chunking, retrieval, and compression rather than expecting to “stuff it all in at once.”
2.3 Daily Quota Caps: Allocation and Scheduling
Account-level quotas are a classic multi-tenant resource allocation mechanism. Returning “busy” instead of a clear error code once the cap is hit makes it hard for clients to distinguish “retryable” from “non-retryable,” which triggers retry storms and worsens congestion. The application side must build quota awareness.
3. Architectural Response: Move Session State from the Server to the Application
The core principle in one sentence: treat the server as a stateless inference function and let the application own the state.
3.1 Externalized, Tiered Session Storage
Split the session into three tiers:
- Hot tier: the rolling window of the current session (the most recent turns), kept in memory or a low-latency cache;
- Warm tier: the full verbatim message stream, written to object storage or a document store, archived by session ID;
- Cold tier: structured summaries of long-term memory and key entities, written to a relational store or a vector retrieval index.
An illustrative data structure:
{"session_id": "s-20261117-0001","updated_at": "2026-11-17T10:00:00Z","hot_window": [{"role":"user","content":"..."},{"role":"assistant","content":"..."}],"summary": "A long story the user and the AI are writing together, now at chapter 14...","entities": {"protagonist":"Lin","key_item":"old pocket watch"},"token_budget": 6000}
This way, even if the upstream session expires, the application can rebuild context from the warm tier’s verbatim messages, and the user’s “continue the conversation” experience is unaffected.
3.2 Context Compression: Rolling Summaries and Layered Memory
Long conversations cannot grow indefinitely and must be compressed. The common industry practice is “rolling summary plus verbatim retention”:
def build_prompt(hot, summary, entities, budget=6000):# 1) Budget allocation: summary and entities take a small share, hot window the bulkreserve = 800hot_budget = budget - reservehot = trim_by_tokens(hot, hot_budget)# 2) Inject structured memorymemory = f"Long-term memory summary: {summary}\nKey entities: {entities}"return memory + "\n" + render(hot)def maybe_update_summary(session, max_turns=20):if session.turns_since_last_summary >= max_turns:old = session.summarychunk = session.hot_windowsession.summary = llm_summarize(old, chunk) # summary of the summarysession.hot_window = keep_recent(chunk, 4)
Key points: the summary itself must be re-summarizable to avoid secondary growth, and entity extraction must be stable so it can serve as “hard memory” across sessions.
3.3 Input Chunking and Retrieval Augmentation
Against a single-request length cap, adopt a “retrieve first, then generate” pattern: split long documents into chunks, vectorize and index them, recall the Top-K chunks relevant to the question, and feed only those chunks to the model.
def answer(question, session):hits = vector_search(question, top_k=6, filters={"session": session.id})context = "\n\n".join(h.text for h in hits)prompt = build_prompt(session.hot_window, session.summary, session.entities)return llm(prompt + "\nReference material:\n" + context)
Chunking must preserve semantic completeness (split on paragraph, section, or function boundaries with moderate overlap), and each chunk should retain source metadata for citation and traceability.
4. Quota-Aware Scheduling, Degradation, and Experience Design
4.1 Client-Side Quota Budget and Token Bucket
Maintain a mirror of the account-level quota in the application and smooth it with a token bucket:
class QuotaBucket:def __init__(self, daily=1000, rate_per_min=5):self.tokens = daily; self.rate = rate_per_mindef allow(self, cost=1):if self.tokens >= cost:self.tokens -= cost; return Truereturn False
4.2 Tiered Degradation Chain
When quota is tight, degrade in order from smallest to largest experience loss:
- Shorten the hot window and raise the summary ratio;
- Turn off non-essential deep reasoning and switch to a lighter model or templated replies;
- Keep only the single most relevant retrieval result;
- Move non-real-time tasks (such as batch summarization) into a queue for off-peak execution;
- Clearly tell the user the remaining quota and reset time, and offer export and read-only browsing.
4.3 Distinguishing Error Semantics and Backoff
“Rate limited / quota exhausted” must be separated from “temporary server failure”: the former cannot be retried immediately and should use exponential backoff with a next-day recovery hint; the latter can be retried briefly. A unified error wrapper:
class UpstreamError(Exception):def __init__(self, kind, retryable, reset_hint=None):self.kind = kind; self.retryable = retryable; self.reset_hint = reset_hintdef call_with_backoff(fn, max_retry=3):for i in range(max_retry):try: return fn()except UpstreamError as e:if not e.retryable: raisesleep(2 ** i + jitter())raise RuntimeError("upstream unavailable")
5. Observability and Capacity Governance
No measurement means no governance. At minimum, collect: token consumption per session, number of summary triggers, retrieval hit rate, quota cap-hit rate, distribution of degradation triggers, time to first token, and end-to-end latency. Set alert thresholds on top of monitoring — for example, if the quota cap-hit rate exceeds 5% for 10 consecutive minutes, scale out or adjust the degradation policy. Keep a request trace ID in the logging service so user complaints can be traced to a specific session and a specific degradation action.
6. Product Safeguards for Long-Running Conversations
What users care about most is that “accumulated content is not lost.” Engineering should deliver:
- Automatic archiving: periodically write verbatim session content to object storage and support export to a common format;
- Resumable conversations: rebuild context from the warm tier so users can “keep chatting even after switching devices”;
- Visible memory: let users view and edit long-term summaries and key entities to increase their sense of control;
- Quota transparency: show remaining quota and reset time in the UI to reduce misunderstandings caused by “service busy” messages;
- Graceful degradation: prioritize “can continue,” then “can review,” and only last “can start new.”
7. Conclusion
The quotas and long-conversation limits of external LLM services are, in essence, a market-based expression of resource constraints. The correct answer on the application side is not to wait for the limits to be lifted but to build a complete pipeline of “no stateful dependency + externalized state + context compression + retrieval augmentation + quota-aware scheduling.” If an organization wants a more controllable combination of inference and storage in its own environment, it can evaluate general-purpose capabilities such as the container platform, object storage, message queue, logging service, and monitoring and alerting offered by Baidu AI Cloud, and assemble an elastic, observable, governable session engineering foundation on demand — leaving uncertainty upstream and keeping certainty in your own hands.
