Handling LLM API Rate Limits: A Guide to Stable Calls Within Quota

    This article explains where web UI and API limits come from, how RPM, TPM, daily quotas, concurrency, and account status affect LLM calls, and how to design more stable integrations. It covers API key management, timeout and retry logic, context trimming, long-term memory storage, and gateway-level quota protection so applications can operate reliably within platform limits.

    Where Web UI Limits Come From

    Many people use web-based LLM tools for continuous writing, code debugging, and research. Once a conversation becomes very long, they may encounter messages such as “usage limit reached” or “server busy,” which interrupts the project. These limits usually come from three areas.

    The first is session lifecycle. Sessions that remain inactive for a long time may be cleaned up or may no longer accept new messages. A long conversation’s context occupies KV Cache in GPU memory, and retaining these caches for a long time is expensive for the service provider, so retention periods are set.

    The second is single-input length. Longer inputs increase the cost of attention computation and GPU memory usage. In the standard Transformer architecture, attention computation scales with the square of the sequence length, and long context also noticeably increases response latency. Platforms therefore often limit the number of characters per input.

    The third is call frequency. Platforms track a single user’s daily request count or token usage. After the quota is exceeded, the platform returns a rate-limit or quota-exhausted message.

    API Calls Have Quotas Too

    Many people assume that API calls have no request limits after switching to pay-as-you-go billing. That is not accurate. API calls are also governed by explicit rules, commonly including the following:

    • RPM (requests per minute): the number of requests that can be sent in a given period.
    • TPM (tokens per minute): the upper limit for combined input and output tokens.
    • Daily or monthly quota: some plans set a cap on total usage.
    • Concurrency: the number of simultaneous requests.
    • Account balance and account verification: requests may be rejected when the balance is insufficient, and some models or higher quotas may require verification or review.

    When these limits are exceeded, the API usually returns HTTP 429. Users who need higher quotas should submit a quota-increase request through the platform’s process. Specific values should be taken from the official documentation and console; do not rely on numbers shared by others.

    For example, when using Baidu AI Cloud’s LLM services, review the quota, billing, and rate-limit information in the console before starting, and record the meaning of official error codes so you can accurately identify where a problem comes from.

    Manage API Keys with Environment Variables

    An API key is an access credential for an account. If it is written directly into code or committed to a code repository, it can easily leak and be used by others, resulting in charges. The recommended approach is to store the key in environment variables or a secret management service, and have the code read only the variable name.

    1. export LLM_API_KEY="your-key"

    On Windows, you can use setx LLM_API_KEY "your-key". After setting it, reopen the terminal. In a project, add the .env file to .gitignore to avoid committing it.

    Example: Timeouts, Rate-Limit Retries, and Context Truncation

    The example below makes several improvements: it reads the key from an environment variable, sets a request timeout, applies exponential backoff retries on 429 or 5xx errors, and truncates long history before sending.

    1. import os
    2. import time
    3. import requests
    4. API_URL = os.environ.get("LLM_API_URL", "https://api.example.com/v1/chat/completions")
    5. API_KEY = os.environ.get("LLM_API_KEY")
    6. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    7. MAX_RETRIES = 4
    8. MAX_HISTORY_CHARS = 20000 # Rough character estimate; use the official tokenizer for actual counting
    9. def trim_history(messages, max_chars=MAX_HISTORY_CHARS):
    10. # Keep system messages and retain messages from newest to oldest; drop older history if over the limit
    11. system_msgs = [m for m in messages if m["role"] == "system"]
    12. others = [m for m in messages if m["role"] != "system"]
    13. total = sum(len(m["content"]) for m in system_msgs)
    14. kept = []
    15. for m in reversed(others):
    16. total += len(m["content"])
    17. if total > max_chars:
    18. break
    19. kept.append(m)
    20. return system_msgs + list(reversed(kept))
    21. def call_llm_api(messages):
    22. if not API_KEY:
    23. raise RuntimeError("LLM_API_KEY environment variable is not set")
    24. headers = {
    25. "Content-Type": "application/json",
    26. "Authorization": f"Bearer {API_KEY}",
    27. }
    28. payload = {
    29. "model": "large-language-model-v1", # Replace with the model name provided by the platform
    30. "messages": trim_history(messages),
    31. "max_tokens": 2048,
    32. "temperature": 0.7,
    33. }
    34. for attempt in range(MAX_RETRIES):
    35. try:
    36. resp = requests.post(API_URL, headers=headers, json=payload, timeout=60)
    37. except requests.RequestException as e:
    38. print(f"Network error: {e}")
    39. resp = None
    40. if resp is not None:
    41. if resp.status_code == 200:
    42. return resp.json()["choices"][0]["message"]["content"]
    43. if resp.status_code not in RETRYABLE_STATUS:
    44. # Errors such as 400 and 401 usually require fixing parameters or keys; retrying is not useful
    45. raise RuntimeError(f"Request failed with status code {resp.status_code}: {resp.text}")
    46. wait = 2 ** attempt
    47. print(f"Attempt {attempt + 1} failed, retrying in {wait} seconds")
    48. time.sleep(wait)
    49. return None
    50. history = [
    51. {"role": "system", "content": "You are a professional code assistant."},
    52. {"role": "user", "content": "Please explain what a closure is."},
    53. ]
    54. answer = call_llm_api(history)

    There are two things to note in this code. First, a 429 error may come from temporary congestion or from a daily quota that has already been exhausted. Retrying usually helps with the former, while retrying the latter only wastes time; log the error and notify the user. Second, estimating history truncation by characters is only an approximation. In production, use the platform’s tokenizer to count tokens.

    Long-Term Memory: Don’t Send All History with Every Request

    The API itself is stateless, so each request must include the history it needs. Sending all history quickly consumes the TPM quota and also increases latency and cost.

    A better approach is layered storage. Recent context can be placed in an in-memory database such as Redis for fast reads. Older full conversations can be stored in object storage and converted into vectors through an embedding model, then written to a vector database. When content from months ago needs to be recalled, first perform vector search, retrieve the most relevant snippets, and add them to the prompt. This keeps the token count per request smaller and reduces the chance of hitting TPM limits.

    Privacy must be considered when storing conversation history. Conversations may contain names, phone numbers, keys in code, or trade secrets. Apply data masking before writing, strictly limit access permissions, set data retention periods, and provide a way for users to delete their data.

    Quota Protection at the Architecture Layer

    Deploying an API gateway between the application and the model API can centralize authentication, routing, and rate limiting. The gateway can set QPS limits per user or per application and block oversized requests based on estimated token counts. When the backend repeatedly returns 429 or times out, the gateway can enter a circuit-breaker state and directly return a degraded result for a period, such as asking the user to try again later or switching to a smaller model, avoiding a backlog of requests in the queue.

    Thresholds should leave headroom. If the platform provides a fixed RPM value, the gateway threshold should be lower and reserve some quota for other services. The circuit-breaker window and degradation strategy need to be validated through load testing rather than set by intuition.

    Load balancing and container platforms such as Kubernetes can automatically scale application instances based on CPU, memory, or custom metrics to handle traffic fluctuations. However, scaling application instances does not increase the model-side quota. After the application scales out, request volume increases faster and is more likely to trigger rate limits, so application-level rate limiting must be designed together with model quotas.

    Conclusion

    Web UI limits mainly come from compute costs and resource scheduling. API constraints are a set of values that can be checked and adjusted, including RPM, TPM, daily quota, and concurrency limits. Developers should first understand these metrics, then handle key management, retry backoff, and context control. Designing call patterns within platform rules is what allows LLM applications to run stably over the long term. When quota is insufficient, check the balance or request a quota increase through official channels rather than hoping for unlimited calls.