The Cost of Long Conversations: Context Management Under Tight Quotas
Long conversations with large language models can quietly become expensive: prefill computation grows roughly quadratically with context length, KV cache memory scales linearly, and decode-time memory bandwidth increases as history accumulates. When platforms tighten free-tier limits on session retention, input length, and daily quotas, users who rely on a single long-lived session lose the most. This article breaks down the cost model of long contexts, provides working rate-limiting implementations for both single-process and multi-instance deployments (including a Redis + Lua atomic script), and introduces practical context management techniques—rolling summaries and externalized state—that keep essential information alive without depending on session survival.
1. Why This Matters
Based on public discussions, several LLM platforms have recently tightened restrictions for free-tier users, mainly around cleaning up long-inactive sessions, capping single-input length, and enforcing daily quotas. These changes have not been officially confirmed, and specific numbers should be taken from platform announcements. This article does not discuss any platform’s specific rules, nor does it offer ways to bypass platform limits. The rate-limiting code shown here targets developers’ own services, to control the usage of their own resources.
When limits tighten, users who depend on long-lived sessions lose the most. Scenarios like role-playing and AI companionship store persona, prior events, and relationship progress within a single session. Once the session is cleaned up, everything accumulated in it disappears. The fundamental fix is to extract key information out of the session, rather than relying on the session itself to survive long-term.
2. The Cost Model of Long Conversations
Inference cost consists of three parts, each with different growth patterns.
First, the prefill stage. Self-attention computation grows approximately quadratically with sequence length. When a user sends a request carrying tens of thousands of tokens of history, the server must run this computation over the entire history.
Second, KV cache memory. During generation, to avoid redundant computation, the server caches the Key and Value tensors of every attention layer in GPU memory. Cache size grows linearly with context length:
KV cache bytes per token = 2 × layers × KV heads × head_dim × bytes per element
The factor of 2 accounts for storing both Key and Value. For a model with 32 layers, 8 KV heads, head dimension 128, and FP16 elements (2 bytes): 2 × 32 × 8 × 128 × 2 = 131,072 bytes, or about 128 KiB per token. A 32K-token session therefore occupies roughly 4 GiB of GPU memory.
This figure covers only the KV cache itself. Attention intermediate activations, memory fragmentation, and batching overhead all consume additional memory, so the real total is always higher. Results also change noticeably with different models, quantization schemes, or context lengths.
Third, the decode stage. Every newly generated token requires reading the entire KV cache of the history, so the longer the session, the higher the memory-bandwidth cost per turn.
3. Rate Limiting Implementation
Rate limiting typically lives at the gateway layer. Below are two implementations matching different deployment shapes: single-process and multi-instance.
3.1 Single-Process Example
The single-process version maintains a sliding window per user and tracks token usage within the window. It uses only the standard library and runs on Python 3.8+.
import threadingimport timefrom collections import dequefrom typing import Optionalclass SlidingWindowTokenLimiter:def __init__(self, quota: int, window_seconds: int = 86400):if quota <= 0 or window_seconds <= 0:raise ValueError("quota and window_seconds must be positive integers")self.quota = quotaself.window = window_secondsself.records = {} # user_id -> deque[(timestamp, tokens)]self.used = {} # user_id -> total tokens used within the windowself._lock = threading.Lock()def _evict(self, user_id: str, now: float) -> None:q = self.records.get(user_id)if not q:returnwhile q and now - q[0][0] >= self.window:_, tokens = q.popleft()self.used[user_id] -= tokensdef allow(self, user_id: str, tokens: int, now: Optional[float] = None) -> bool:if tokens <= 0:raise ValueError("tokens must be a positive integer")now = time.time() if now is None else nowwith self._lock:self.records.setdefault(user_id, deque())self.used.setdefault(user_id, 0)self._evict(user_id, now)if self.used[user_id] + tokens > self.quota:return Falseself.records[user_id].append((now, tokens))self.used[user_id] += tokensreturn Truelimiter = SlidingWindowTokenLimiter(quota=200_000)print(limiter.allow("user_a", 5_000)) # Trueprint(limiter.allow("user_a", 250_000)) # False, exceeds window quota
Key limitations of this code:
- Counters live only in process memory. They reset to zero when the process restarts.
- Multiple worker processes or machines count independently, so the same user can bypass the quota. Once you move to multi-instance deployment, switch to the approach in 3.2.
_evictonly cleans up the user being requested. Records for long-idle users stay in memory indefinitely, so you need a scheduled job to sweep them periodically, for example once an hour.
3.2 Multi-Instance: Redis with an Atomic Lua Script
In multi-instance deployments, counters must live in Redis. The key requirement is that “read, check, write” must happen in a single atomic operation. Otherwise, two concurrent requests can both pass the check and together exceed the quota. Redis executes Lua scripts without interleaving other commands, so putting both the check and the write inside the script satisfies this requirement.
The following script uses fixed-window counting, with keys composed of the user ID and the UTC date:
-- KEYS[1]: counter key, e.g. quota:tok:user_a:20261124-- ARGV[1]: tokens requested this time (positive integer)-- ARGV[2]: daily quota-- ARGV[3]: key expiration in seconds-- Returns: {allowed (1 or 0), usage after the call}local cost = tonumber(ARGV[1])local quota = tonumber(ARGV[2])local ttl = tonumber(ARGV[3])local current = tonumber(redis.call('GET', KEYS[1]) or '0')if current + cost > quota thenreturn {0, current}endlocal new_val = redis.call('INCRBY', KEYS[1], cost)if new_val == cost then-- Set expiration only when the key is first created;-- later requests do not reset itredis.call('EXPIRE', KEYS[1], ttl)endreturn {1, new_val}
The Python side calls the script via register_script:
import datetimeimport redisLUA_SCRIPT = open("quota.lua", encoding="utf-8").read() # the script abover = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)consume = r.register_script(LUA_SCRIPT)DAILY_QUOTA = 200_000KEY_TTL = 172800 # 2 days, to cover timezone differences and let stale data expiredef try_consume(user_id: str, tokens: int) -> bool:if tokens <= 0:raise ValueError("tokens must be a positive integer")today = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d")key = f"quota:tok:{user_id}:{today}"allowed, _used = consume(keys=[key], args=[tokens, DAILY_QUOTA, KEY_TTL])return allowed == 1print(try_consume("user_a", 5_000)) # Trueprint(try_consume("user_a", 250_000)) # False
Additional implementation notes:
user_idmust come from authenticated identity information, never from a client-submitted field. Otherwise users can forge other people’s counter keys.- Keys use the UTC date so that servers in different timezones do not place the same user into different buckets.
- Set expiration to 2 days rather than 1, so that requests crossing a date boundary from other timezones do not hit an already-expired key.
- The script touches only one key, so it never crosses slots in Redis Cluster. If you later modify it to operate on multiple keys, use hash tags to keep them in the same slot.
3.3 The Cross-Window Problem with Fixed Windows
Fixed windows are simple and memory-efficient, at the cost of possible bursts at window boundaries. With a daily quota of 200,000 tokens, a user could burn the entire quota at 23:59 and burn it again at 00:01—consuming nearly twice the quota within two minutes.
Three common mitigations:
- Dual-layer windows: Keep the daily quota and add a shorter-window cap, for example no more than a fixed fraction of the daily quota per hour. This is a small change that effectively suppresses boundary bursts.
- Token bucket: Refill tokens at a fixed rate, with bucket capacity limiting burst size. It smooths request rates well but does not directly express “at most X per day,” so it should be combined with a daily quota.
- ZSET + Lua sliding window: Each request writes its timestamp and token count into a sorted set; the script first removes records outside the window, then sums usage and decides whether to write. This has the strictest semantics, but each user’s set grows with request count, raising operational cost.
Compared with the single-process implementation in 3.1, the Redis approach differs in three ways: counter state is shared across all instances, the check-and-write is atomic, and expiration is handled automatically by Redis TTL—no scheduled cleanup job needed.
4. Context Management in Practice
When quotas tighten, the most effective approach is to reduce the amount of history carried in each request while preserving key information. The following two techniques can be used independently or combined.
4.1 Rolling Summaries
The rolling summary approach: keep the verbatim text of the most recent turns, and have the model compress older content into a rolling summary. Each request carries only “summary plus recent turns.”
RECENT_TURNS = 10 # number of recent turns kept verbatimdef build_context(session):return [{"role": "system", "content": session.system_prompt},{"role": "system", "content": f"Summary of earlier conversation: {session.summary}"},*session.messages[-RECENT_TURNS:],]def after_turn(session, llm):if len(session.messages) > RECENT_TURNS * 2:old = session.messages[:-RECENT_TURNS]session.summary = llm.summarize(session.summary, old)session.messages = session.messages[-RECENT_TURNS:]
Three things to watch when implementing this. The summary gets re-compressed every turn, so errors accumulate over time—check periodically whether the summary has drifted. The summary should contain verifiable facts such as names, agreements, and unfinished items, not just rhetorical descriptions. Before compressing, you can first have the model list the facts that must be retained, then generate the summary.
4.2 Externalized State
The externalized state approach: store key state—persona, relationship progress, user preferences—in a database as structured data. Each request loads only the fields currently needed, and the session itself can be cleaned up at any time.
def build_prompt(user_id, recent_messages):profile = db.load_profile(user_id) # structured fields, e.g. persona, key facts, versionstate_block = render_profile(profile)return [{"role": "system", "content": state_block},*recent_messages,]def after_session(user_id, transcript, llm):updates = llm.extract_facts(transcript, schema=PROFILE_SCHEMA)db.update_profile(user_id, updates)
Externalized state breaks the dependency on session survival. Even if the session is cleaned up, persona and relationship data can be rebuilt from the database, and structured fields are easier to audit and correct than free-form summaries.
