Long Conversations and Quota-Based Rate Limiting in LLM Services

    Learn how to manage long-running conversations, input limits, and usage quotas in LLM services. This article covers session lifecycles, token bucket rate limiting, retry backoff, user-facing errors, and monitoring, with Python examples and an implementation checklist.

    1. Why Long Conversations and Usage Quotas Go Together

    Large language model inference costs are directly tied to compute consumption. The cost of a request increases with its input and output lengths. As a conversation grows, its history becomes longer, increasing the number of tokens that subsequent inference requests must process. Servers may also retain state for active sessions, such as attention caches and conversation history. These resources can become constrained during peak traffic.

    Service providers therefore commonly enforce three types of limits: how long conversations remain active, how much input a single request can contain, and how much a user can consume over a given period, such as a day. These are standard resource-management controls. Understanding how they work helps developers design similar policies that fit their own applications.

    2. Breaking Down the Problem

    2.1 Session Lifecycle

    Inactive conversations can continue to occupy context caches and storage. After a defined period of inactivity, the system can archive a conversation, allowing users to view its history or start a new one when they return.

    Expiration should be based on the last activity time, not the conversation’s creation time. This prevents conversations that are still in use from being incorrectly marked as expired.

    2.2 Per-Request Input Limits

    Input limits help control inference latency and GPU memory consumption. These limits are generally measured in tokens rather than characters.

    Different tokenizers can split the same text differently, so character counts provide only an approximation. Production systems should count tokens with the tokenizer that matches the model before deciding whether an input exceeds the limit.

    2.3 Daily Quotas and Overload Responses

    Daily quotas help balance resource consumption across users. When a quota is exhausted, the service should return a clear error code and an explanatory message.

    Temporary overload is different from quota exhaustion and requires different handling:

    • Temporary overload: Retry with exponential backoff.
    • Quota exhaustion: Wait for the quota to reset or adjust the pace of usage.

    3. Design Principles

    • Make rules predictable: Document limits and notify users before they reach a threshold.
    • Apply limits at multiple levels: Enforce global, tenant, user, and session limits to prevent a single traffic hotspot from disrupting the entire service.
    • Distinguish error types: Use distinct status codes and messages for invalid or oversized input, exhausted quotas, and system overload.
    • Support graceful degradation: During peak demand, prioritize short conversations and core functionality while deferring nonessential tasks.
    • Maintain observability: Track rejected requests, latency distributions, and retry success rates at each level.

    4. Key Implementation Components

    4.1 Session Lifecycle Management

    The following example determines whether a session is still active based on its last activity time. The threshold is illustrative; the appropriate value depends on the application.

    1. from datetime import datetime, timedelta, timezone
    2. IDLE_LIMIT = timedelta(days=7) # Example threshold
    3. def is_session_active(last_active_at: datetime, now: datetime | None = None) -> bool:
    4. now = now or datetime.now(timezone.utc)
    5. return now - last_active_at <= IDLE_LIMIT

    When a session expires, consider moving its data to lower-cost storage rather than deleting it immediately. This releases resources from the active storage tier while preserving the option for users to export their conversation history.

    4.2 Input Length Control

    Conversation histories that exceed the limit need to be trimmed. The following implementation retains messages starting with the most recent ones, stopping when the next message would exceed the length budget. This keeps the latest context available to the model.

    1. def trim_history(messages: list[str], max_chars: int) -> list[str]:
    2. """Keep the most recent messages within the total length limit."""
    3. kept: list[str] = []
    4. total = 0
    5. for msg in reversed(messages):
    6. if total + len(msg) > max_chars:
    7. break
    8. kept.append(msg)
    9. total += len(msg)
    10. return list(reversed(kept))

    This example measures length in characters and is suitable only for a prototype. Replace character counting with token counting in production.

    If a single user input exceeds the limit, reject it and ask the user to submit it in smaller parts. Do not silently truncate it: otherwise, users cannot tell which content was discarded.

    4.3 Token Bucket Rate Limiting

    A token bucket allows short bursts while limiting the long-term average consumption rate. The number of bucket tokens consumed by a request can be based on its input token count, enabling usage-based rate limiting.

    1. import threading
    2. import time
    3. class TokenBucket:
    4. def __init__(self, capacity: float, refill_rate: float):
    5. self.capacity = capacity # Maximum bucket capacity
    6. self.refill_rate = refill_rate # Tokens replenished per second
    7. self.tokens = capacity
    8. self.updated = time.monotonic()
    9. self.lock = threading.Lock()
    10. def acquire(self, cost: float = 1.0) -> bool:
    11. with self.lock:
    12. now = time.monotonic()
    13. elapsed = now - self.updated
    14. self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
    15. self.updated = now
    16. if self.tokens >= cost:
    17. self.tokens -= cost
    18. return True
    19. return False

    In a deployed service, maintain a separate bucket for each user or tenant and store bucket state in shared storage. Otherwise, separate service instances will not enforce a consistent limit.

    4.4 Exponential Backoff with Jitter

    Clients should back off before retrying requests that fail because of temporary overload. Random jitter helps prevent large numbers of clients from retrying simultaneously and creating another traffic spike.

    1. import random
    2. import time
    3. class TransientError(Exception):
    4. """A retryable temporary error, such as service overload."""
    5. def call_with_backoff(fn, max_retries: int = 5, base: float = 0.5, cap: float = 10.0):
    6. for attempt in range(max_retries):
    7. try:
    8. return fn()
    9. except TransientError:
    10. delay = min(cap, base * (2 ** attempt))
    11. time.sleep(delay + random.uniform(0, delay * 0.1))
    12. raise RuntimeError("Retry limit exhausted")

    Only retryable errors should enter the backoff path. Deterministic failures, such as exhausted quotas or invalid parameters, should be returned immediately to avoid pointless repeated requests.

    5. User Experience Design

    • Warn users early: Display a notification when the remaining quota falls below a threshold, giving users time to adjust their usage.
    • Explain the cause: Error messages should identify the reason, scope of impact, and expected recovery time rather than simply saying “Please try again later.”
    • Preserve user data: Support exports of archived conversations to reduce the frustration caused by lifecycle limits.
    • Offer alternatives: When an input is too long, suggest submitting it in sections or first generating a summary and continuing the conversation from that summary.

    6. Monitoring and Alerts

    Monitor at least the following metrics:

    1. Session archival rate: Shows the practical impact of the session lifecycle policy.
    2. Daily quota rejection rate: Helps assess whether usage quotas are appropriate.
    3. Input-limit rejection rate: Indicates whether input limits interfere with common use cases.
    4. Retry success rate and P95 latency: Measure service quality during overload.

    Alerts should distinguish brief traffic spikes from sustained overload. Backoff can usually absorb short spikes, while persistently high rejection rates call for additional capacity, quota adjustments, or changes to request structure.

    7. Implementation Checklist

    1. Map resource costs and define the accounting unit for each request type, such as token count or request count.
    2. Establish layered quotas and session lifecycle policies, and document them for users.
    3. Implement rate limiting, history trimming, and retry backoff, with unit tests and boundary-case coverage.
    4. Roll out to a small share of traffic and monitor rejection rates, latency, and user feedback.
    5. Adjust thresholds gradually based on monitoring data, and maintain a rollback plan.