Rate Limiting for Large Model Services: Quota Design and Coping Strategies under Compute Constraints

    This article explores the background of rate limiting in large language model (LLM) services and details common quota dimensions such as request frequency, token usage, and concurrency. It provides practical strategies for both client and server sides to handle rate limits, including exponential backoff, token bucket algorithms, token optimization, and server-side degradation. Additionally, it covers monitoring, cost planning, and common misconceptions to help developers build stable and predictable applications.

    1. Background: Why Rate Limits Exist

    Large model inference heavily relies on graphics processing units (GPUs) and memory resources. Each request consumes computing power, and the longer the input and the greater the output, the higher the consumption. When the number of requests within a given period exceeds the cluster’s capacity, service providers typically have three options: scale up, queue, or rate limit. Scaling up requires time and cost, while queuing increases response times. Therefore, rate limiting is often the immediate method to ensure overall availability.

    For users, rate limits mean that the same code may perform differently depending on the time of day. Understanding the types and triggering logic of rate limits is a prerequisite for designing stable applications.

    2. Common Rate Limit Dimensions

    1. Request Frequency Limit: Constrains the number of calls per unit of time, such as the number of allowed requests per minute.
    2. Token Usage Limit: Constrains the total number of tokens processed per unit of time. Since the computational load of large models is directly related to the token count, long-text requests are more likely to trigger this limit.
    3. Concurrency Limit: Constrains the number of outstanding requests allowed at the same time.
    4. Periodic Quota: Sets a total usage cap by day or month. Once exhausted, you must wait for the cycle to reset or upgrade your plan.
    5. Tiered Strategy: Different accounts and service levels receive different quotas. High-priority tasks usually enjoy higher limits.

    Specific values are published by the service provider and may change with resource availability. During development, rely on official documentation and response headers rather than hardcoding a specific number.

    3. How to Identify Rate Limit Triggers

    When a rate limit is triggered, the service typically returns an HTTP 429 status code (Too Many Requests), which is standardly defined in RFC 6585. In some scenarios, 5xx errors may also occur, or response times may significantly increase. Follow these steps to identify the issue:

    • Log the status code, duration, and error message of each call to create a traceable record.
    • Distinguish between temporary rate limiting and exhausted quotas. The former recovers after a short wait, while the latter requires reducing usage or waiting for the cycle to reset.
    • If the response includes a suggested retry wait time, prioritize following that hint.

    4. Client-Side Coping Strategies

    4.1 Exponential Backoff and Jitter

    Directly retrying in a loop will exacerbate congestion, and multiple clients retrying simultaneously can create traffic spikes. The proper approach is to increase the wait time exponentially after each failure and introduce random jitter to spread out retry requests.

    1. import random
    2. import time
    3. def call_with_backoff(request_fn, max_retries=5, base_delay=1.0, max_delay=30.0):
    4. for attempt in range(max_retries):
    5. try:
    6. return request_fn()
    7. except RateLimitError: # Rate limit exception, defined by the caller based on the API used
    8. if attempt == max_retries - 1:
    9. raise
    10. delay = min(max_delay, base_delay * (2 ** attempt))
    11. delay = delay * (0.5 + random.random() / 2) # Add jitter
    12. time.sleep(delay)

    Usage Tips: Only retry on retryable errors (rate limits, temporary unavailability). Retrying on parameter errors or authentication failures is ineffective and should result in a direct error and log.

    4.2 Local Token Bucket Rate Limiting

    Compared to passively waiting, actively controlling the sending rate on the client side is smoother. A token bucket generates tokens at a fixed rate, and each request consumes one token. If tokens are insufficient, the request waits.

    1. import threading
    2. import time
    3. class TokenBucket:
    4. def __init__(self, rate_per_sec, capacity):
    5. self.rate = rate_per_sec
    6. self.capacity = capacity
    7. self.tokens = capacity
    8. self.updated = time.monotonic()
    9. self.lock = threading.Lock()
    10. def acquire(self):
    11. while True:
    12. with self.lock:
    13. now = time.monotonic()
    14. elapsed = now - self.updated
    15. self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
    16. self.updated = now
    17. if self.tokens >= 1:
    18. self.tokens -= 1
    19. return
    20. wait = (1 - self.tokens) / self.rate
    21. time.sleep(wait)

    The rate and capacity need to be configured based on the service provider’s actual limits. Capacity determines the allowed burst volume, while the rate determines the long-term average sending speed. Both should be configurable to allow adjustments as limits change.

    4.3 Compressing Token Consumption

    Reducing the number of tokens per request is often more effective than increasing retries. Common practices include:

    • Streamlining system prompts by removing redundant instructions and irrelevant examples.
    • Summarizing conversation history and using the summary instead of the full record.
    • Processing long documents in segments, carrying only the content needed for the current task in each segment.
    • Limiting the upper bound of generated content via output length parameters to avoid uselessly long replies.

    4.4 Caching and Request Merging

    When the same input is requested multiple times within a short period, prioritize reading from a local cache. For query-type tasks with deterministic results, set a reasonable cache expiration time. Multiple similar requests can be merged into a single batch call on the client side to reduce the number of requests.

    4.5 Asynchronization and Queuing

    Non-real-time tasks, such as batch text processing or offline report generation, are suitable for placing in a message queue consumed by background workers. Workers can take tasks at a steady rate based on the token bucket algorithm and increase processing volume during off-peak hours. The frontend only needs to display the task status without synchronously waiting for the result.

    5. Server-Side Architecture Design

    If you are responsible for building a service for end users, you also need to provide protection at the service level.

    • Degradation: During peak hours, switch to lighter processing methods, such as shortening output length or disabling non-core features, to ensure the main workflow remains available.
    • Circuit Breaking: When a downstream call fails continuously up to a threshold, pause calling for a period, then use a small number of probe requests to check if it has recovered.
    • Tiered Admission: Set up different priority queues for paying users, internal tasks, and general requests.
    • User Feedback: Clearly inform users of the queuing status and estimated wait time, and save their uncompleted input to prevent content loss caused by rate limiting.

    The core of these measures is to make the system predictable when resources are constrained. Users know what is happening, and the system does not crash entirely due to retry storms.

    6. Usage Monitoring and Cost Planning

    Without monitoring, rate limit issues are often only discovered after a failure occurs. It is recommended to continuously track the following metrics:

    • Total request volume and success rate.
    • The proportion of 429 responses to gauge the intensity of rate limiting.
    • P95 and P99 percentile values for request duration.
    • Daily and monthly token consumption.
    • Usage distribution across different functional modules to locate high-consumption areas.

    It is recommended to set up multi-level alerts for quotas, such as a reminder at 70% usage and an escalated alert at 90%. Additionally, use historical data to predict next month’s usage and proactively assess whether you need to adjust your plan or optimize business logic.

    When building related systems on Baidu AI Cloud, you can leverage the platform’s general capabilities, such as monitoring, alerting, and logging services, to aggregate the above metrics and generate dashboards. Refer to the official documentation for specific features and configurations.

    7. Common Misconceptions

    Misconception 1: The more retries, the more reliable the service. In reality, unrestrained retries amplify server pressure and worsen rate limiting. Retries should be used in conjunction with backoff and circuit breaking.

    Misconception 2: Hardcoding rate limit numbers in the code. Service provider limits change. Hardcoding will cause configurations to become invalid. These should be managed via configuration files or a configuration center.

    Misconception 3: Only focusing on request count while ignoring token volume. A single super-long request can consume far more resources than multiple short requests. Monitoring and rate limiting must consider both dimensions simultaneously.

    Misconception 4: Abandoning tasks directly after rate limiting. For important tasks, save the intermediate state to support resumption from breakpoints or delayed execution.

    8. Conclusion

    Rate limiting is a common mechanism under resource-constrained conditions and does not inherently mean a service failure. The key to coping involves three aspects: the client controls the sending pace through backoff and rate limiting, and reduces invalid consumption through token compression and caching; the server maintains overall stability through degradation, circuit breaking, and tiered admission; the team integrates rate limit risks into daily operations through continuous monitoring and cost planning. Following this approach, applications can maintain predictable performance even amid quota fluctuations.