LLM Quota and Rate Limits: How Developers Can Keep Applications Stable

    This article explains how to design LLM-backed applications when provider quotas, context windows, and request rates are constrained. It covers storing session state in your own backend, chunking and retrieving long documents, using Map-Reduce summarization, and handling rate limits with backoff, queuing, and graceful degradation. It also outlines monitoring metrics and when self-hosted inference may be worth considering.

    First, a note: this article discusses publicly stated quota, token, and frequency rules from service providers. These rules are subject to the provider’s terms. Read them carefully before designing an application, and then choose from the methods below.

    1. What the Three Types of Limits Are

    1. Session lifecycle limits. Some platforms clear context after a conversation has been inactive for a long time and prompt users to export their history. This is mainly a provider strategy for managing session-history storage costs and reclaiming resources. The KV Cache used during inference is a per-request compute cache and is usually not retained after the request ends; it is separate from conversation history. Therefore, you cannot rely on the platform to store conversation state over the long term.

    2. Single-input length limits. Every model has a maximum context window. Input that exceeds this length is truncated or rejected outright; this is a hard boundary determined by the model architecture. Within the window, the attention computation of a standard Transformer grows approximately quadratically with context length. The longer the input, the faster latency and memory usage increase. Therefore, even if a model can accept long input, you should not put all content into it at once.

    3. Request frequency and concurrency limits. Providers usually limit the number of requests and concurrency per day or per minute. The purpose is to control compute costs and prevent abuse. When you hit a limit, the legitimate approach is to request a higher quota, reduce unnecessary calls, queue requests, or degrade service—not to find ways around the limit.

    2. Long Conversations: Keep Session State in Your Own System

    When the platform no longer stores conversations, state management must be handled by your own backend.

    1. Design a session table. At a minimum, include the following fields: user ID (user_id), session ID (session_id), turn index (turn_index), user input, model output, summary text (summary_text), summary version (summary_version), last active time (last_active_at), and expiration policy (expire_policy). Raw conversations can be stored in a relational database. Very long logs can be stored in object storage, with only the file address kept in the table.

    2. Use a sliding window plus dynamic summaries. Keep the raw text of the most recent N turns; start with N between 5 and 10 and adjust from there. Older conversations are compressed into summaries by a scheduled task that calls the model. Increment the summary version after each compression. The following function shows how to assemble the prompt:

    1. def build_prompt(user_input, recent_history, past_summary):
    2. """Build a prompt with the historical summary and recent turns"""
    3. parts = []
    4. if past_summary:
    5. parts.append(f"Historical conversation summary:\n{past_summary}\n")
    6. for turn in recent_history:
    7. parts.append(f"User: {turn['user']}\nAI: {turn['ai']}")
    8. parts.append(f"User: {user_input}\nAI:")
    9. return "\n".join(parts)

    Summaries lose detail. Key information such as user preferences, constraints, and confirmed facts should be stored separately in structured fields. Do not rely on summary text alone.

    3. Long Text: Chunking, Retrieval, and Map-Reduce

    When processing documents that are tens of thousands of words long, split them first and then process the chunks separately.

    1. Chunking parameters. Split by semantic paragraphs. A single chunk should be around 500 to 1,000 tokens, with 50 to 100 tokens of overlap between adjacent chunks to avoid cutting key sentences. Keep code blocks and tables intact where possible; do not split them in the middle. These values are starting points and need to be adjusted based on actual retrieval performance.

    2. RAG retrieval. Use an embedding model to convert each text chunk into a vector and store it in a vector database. When a user asks a question, retrieve the Top-K most relevant chunks and pass only those chunks and the question to the model. K is usually 3 to 5. You can start with a smaller K to test retrieval quality and then increase it gradually. This approach is suitable for knowledge Q&A, not for tasks that require reading the entire document.

    3. Map-Reduce summarization. In the Map stage, split the document into sub-documents that fit within the window limit and generate local summaries in parallel. In the Reduce stage, merge all local summaries to produce a global summary. If the merged result still exceeds the window length, run another round of Map-Reduce on the merged result.

    4. Summary trigger threshold. When document length exceeds about 70% of the model window, start the chunking process to leave room for instructions and model output. This ratio can serve as a starting point; the actual value should be adjusted based on output length.

    4. Request Frequency: Backoff Retries, Queuing, and Degradation

    When you encounter rate limiting, your program needs to retry in a controlled way and have fallback options ready.

    1. import random
    2. import time
    3. class RateLimitError(Exception):
    4. """Raised when the provider returns a rate-limit error (e.g., HTTP 429)"""
    5. def call_llm_with_retry(prompt, max_retries=5, max_wait=30.0):
    6. for attempt in range(max_retries):
    7. try:
    8. # invoke_llm_api is a placeholder; replace it with the actual SDK call
    9. return invoke_llm_api(prompt, timeout=60)
    10. except RateLimitError:
    11. if attempt == max_retries - 1:
    12. break
    13. wait = min(max_wait, (2 ** attempt) + random.uniform(0, 1))
    14. time.sleep(wait)
    15. raise RuntimeError("Maximum retries exceeded; queue the request or degrade gracefully")

    This code has three key points. First, the wait time has an upper bound to avoid long blocking. Second, every request has a timeout. Third, before retrying, confirm whether the previous request was already processed by the server. For operations that write data or incur charges, use idempotency keys to prevent the same task from being executed more than once.

    At the gateway or application layer, you can configure multiple legitimate providers and route requests based on cost, latency, and availability. Each provider should use the quota requested under its own account. Do not rotate multiple accounts to bypass a single account’s quota; such practices usually violate the terms of service and can also lead to account suspension.

    When all channels are under pressure, you can take two degradation approaches. First, put non-real-time tasks into a queue for asynchronous processing and notify the user when they are complete. Second, return cached results for common questions or tell users to try again later. Core functionality should be protected first; non-core functionality can be degraded first.

    During operation, log the proportion of 429 errors, average wait time, queue length, and success rate for each provider. These metrics can help determine whether quotas need to be adjusted.

    5. Self-Hosted Inference: When It Is Worth Considering

    Self-hosting models can reduce reliance on third-party quotas, but it does not eliminate resource constraints. The number of GPUs you own, memory size, and concurrency limits will also constrain throughput.

    Before deciding whether to self-host, compare the following items:

    • GPU purchase or rental costs, calculated per hour or per month
    • Deployment and maintenance labor for the inference framework
    • Number of instances required at peak concurrency
    • Data security and compliance requirements

    Mainstream cloud providers offer container services and GPU instances, which can be elastically scaled to handle traffic fluctuations. Before launch, prepare monitoring metrics including GPU utilization, memory usage, first-token latency, requests per second, and error rate, and have logging and alerting cover these metrics. Private deployment can protect data, but it also requires someone to own model version management and security updates.

    6. Summary

    The limits on LLM services come from compute costs and resource scheduling. On the application side, there are four things you can do: store session state in your own system, split long text before processing it, use backoff, queuing, and degradation strategies for rate limits, and plan quotas within the scope allowed by the terms of service. Following the terms is what allows an application to run stably over the long term.