Rate Limiting and Quotas for LLM Chat Services: Engineering Practice
LLM chat platforms tighten session TTL, input length, and daily quotas because GPU memory and inference capacity cannot scale as fast as demand. This article abstracts three orthogonal constraints, shows idle-session reclaim, token-bucket and leaky-bucket patterns, consumer vs API quota models, capacity planning, and a developer checklist.
1. The shared constraint: compute is scarce
Several conversational AI products have recently tightened usage policies: idle long chats cannot be resumed, per-request input length is reduced, daily allowances surface as hard caps, and status pages record partial outages. These product moves share one engineering cause: inference capacity is far less elastic than request growth.
Unlike stateless web APIs, LLM inference has three cost peculiarities:
- GPU memory is a hard limit. KV cache grows linearly with sequence length. An idle session still occupies memory if the context is kept.
- Compute grows super-linearly with length. Attention is quadratic in sequence length, so a long prompt costs far more than a short one.
- Throughput is bursty. Arrivals have peaks and troughs, while memory and GPU count cannot autoscale in seconds.
Quotas and rate limits are therefore a predictable allocation of scarce resources across time and users, not hostility. Application design depends on understanding the layers.
2. Three orthogonal constraints
| Dimension | Target | Typical policy | Primary goal |
|---|---|---|---|
| Session lifetime | Session | Idle timeout; no resume after expiry | Free memory held by long context |
| Per-request size | Single input | Max input length; truncate or reject | Bound peak cost of one request |
| Time-window quota | User / tenant | Daily allowance, RPM, concurrency | Smooth peaks and keep fairness |
All three are required. Length limits without session reclaim still leave idle long sessions occupying memory. Session reclaim without windows still lets bursts exceed capacity. Windows without length limits let one oversized request stall a batch.
2.1 Why idle sessions are hard-reclaimed
Resume needs the full history in memory. Past the idle threshold, servers typically drop context instead of cold-storing it: serialize, transfer, and re-warm often cost more than asking the user to restate background. The UX is “cannot continue”; the engineering trade is visible inconvenience for reclaimable GPU memory.
Implication: do not treat session IDs as durable storage. Long-term memory belongs in the application’s own store, with summarization—not in unbounded platform retention.
2.2 Trade-offs on input length caps
Lowering the per-request cap usually pulls a long-tail cost curve back into a controllable range, not a capability regression. Three common tactics:
- Hard reject: over-limit errors; clearest semantics, worst UX.
- Tail truncate: keep the newest tokens; simple; may drop early instructions.
- Hierarchical summary: recursively summarize history; keep system instructions and latest raw text; cost for quality.
Illustrative sketch (replace token counting with the real tokenizer):
SESSION_TTL = 7 * 24 * 3600 # idle reclaim threshold (seconds)MAX_INPUT_TOKENS = 16000 # per-request input cap (illustrative)def load_session(store, sid, now):sess = store.get(sid)if sess is None:return Noneif now - sess.last_active > SESSION_TTL:store.delete(sid) # hard reclaim: context is not recoverablereturn Nonereturn sessdef trim(messages, budget=MAX_INPUT_TOKENS, counter=count_tokens):kept, used = [], 0for m in reversed(messages): # keep from newest backwardn = counter(m["content"])if used + n > budget:breakkept.append(m)used += nreturn list(reversed(kept))
3. Implementing quotas and rate limits
3.1 Algorithm choice
- Token bucket: allows bursts; fits token- or request-based billing; parameters are capacity and refill rate.
- Sliding window counter: simple, intuitive (“N per day”); can double-burst at window edges.
- Leaky bucket: constant outflow; protects the inference cluster from overload.
- Concurrency semaphore: caps in-flight requests; closest to the real GPU-memory bottleneck.
Production stacks usually combine them: tenant token buckets at the edge, concurrency semaphores at the gateway, leaky-bucket shaping at inference.
import timeclass TokenBucket:def __init__(self, capacity: int, refill_rate: float):self.capacity = capacityself.refill_rate = refill_rate # tokens per secondself.tokens = capacityself.last = time.monotonic()def acquire(self, need: int = 1) -> bool:now = time.monotonic()self.tokens = min(self.capacity,self.tokens + (now - self.last) * self.refill_rate)self.last = nowif self.tokens >= need:self.tokens -= needreturn Truereturn False
3.2 Quotas must be tiered and observable
A single global quota lets heavy and light users starve each other. A practical model is a 2D matrix: user tier (trial / standard / high priority) × resource (RPM, daily tokens, max concurrency). Expose remaining quota in response headers or a status API so limits are predictable, not only post-error.
3.3 Prefer honest reject over opaque queues
When quota is exhausted, return distinct error classes (quota, overload, parameter) rather than a generic “busy.” Clients can back off or degrade instead of retrying and amplifying load:
def call_with_backoff(fn, max_retry=5, base=0.5, cap=8.0):for i in range(max_retry):try:return fn()except RateLimited as e:if not e.retryable:raisedelay = min(cap, base * (2 ** i))time.sleep(delay * (0.5 + random.random() / 2)) # jitter, avoid synchronized retriesraise RuntimeError("quota exhausted")
4. Consumer product quotas vs API limits are different systems
This is easy to misread. Consumer chat and developer APIs differ in billing, isolation, and scheduling:
- Quota meaning: consumer products often use a per-user daily experience allowance (marketing plus cost control). APIs use per-tenant rate limits plus usage billing (capacity plus commercial contract).
- Isolation: APIs typically have separate tenant ledgers, limit channels, and priority queues so consumer spikes do not steal developer capacity.
- Reliability goals: consumers can tolerate degrade and queues; APIs emphasize SLA, predictable latency, and idempotency.
Tightening the consumer product does not imply the same for the API. Architecturally, keep multi-tenant isolation: a shared inference pool with independent quota books and priority scheduling so paid paths stay deterministic.
5. Stability and capacity planning
Partial outages are hard to eliminate on fast-growing inference platforms; what you can manage is blast radius and recovery time. Cover:
- Observability: unified request tracing; alerts on time-to-first-token, queue wait, GPU memory watermark, reject rate; keep the status page current so unknown failures become known degrades.
- Elasticity and peak shaving: stateless gateways and containerized runtimes for horizontal scale; buffer bursts in a queue and shape to a stable rate.
- Circuit breaking and degrade: trip thresholds on upstreams; fallbacks include a smaller model, a shorter context budget, and turning off non-core features.
- Capacity tests: model average input length × concurrency × output length, not QPS alone; long-input memory pressure often hits before FLOPs.
- Client resilience: streaming for perceived latency, local cache and reuse to cut duplicate calls, idempotency keys so retries do not double-bill.
6. Developer checklist
- Treat sessions as ephemeral; persist and summarize long-term memory yourself.
- Estimate tokens locally and trim before send to avoid hard rejects.
- Handle quota vs overload errors differently, with exponential backoff and jitter.
- Surface remaining quota in the product UI instead of waiting for a wall.
- Keep a smaller fallback model and caches on critical paths; size capacity for long-input cases.
Rate limits and quotas are how rigid compute is priced and ordered across priority classes. Understanding the layers lets applications stay stable and predictable inside those constraints.
