LLM API Rate Limits: Compute Constraints and Stability Strategies

    This article explains why LLM serving hits compute limits, compares three rate-limiting algorithms, and presents application-level practices for context compression, multi-model fallback, and 429 backoff retry. It also covers monitoring, troubleshooting, and compliance considerations for applications that depend on third-party LLM APIs.

    Recently, a popular LLM application increased restrictions for free users because of rapid growth in call volume. According to public reports and user discussions, the restrictions include the number of long conversations, daily usage quotas, and the maximum length of a single text input; the specific rules are subject to the platform’s announcements.

    Applications that depend on third-party LLM APIs need request-side budgeting, degradation, backoff, and monitoring to remain available when quotas fluctuate. The following sections first explain why compute is tight, then compare rate-limiting algorithms, and finally give concrete application-layer practices.

    1. The Compute Boundary Behind Rate Limits

    When a large language model generates each token, it must read model parameters and perform attention computation over the existing context. To avoid recomputing historical tokens, the system caches each layer’s keys and values in GPU memory. This cache is called the KV cache.

    KV cache size grows approximately linearly with context length. The estimation formula is:

    KV cache bytes ≈ 2 × layers × KV heads × head dimension × sequence length × bytes per element

    Consider a model with 32 layers, 32 KV heads, head dimension 128, and FP16. Under this configuration, each token takes about 0.5 MiB. When the context reaches 8,192 tokens, a single sequence needs about 4 GiB of GPU memory. If the model uses grouped-query attention (GQA) and the number of KV heads drops to 8, the same length needs about 1 GiB.

    This formula only estimates the KV cache. It does not include model weights, activations, or memory fragmentation. In actual deployment, calculate based on the model’s real configuration; do not directly apply the numbers above.

    Beyond GPU memory, long sequences also increase the amount of memory read during each decoding step, making memory bandwidth a bottleneck. Inference services commonly use continuous batching to improve GPU utilization. This scheduling method can iteratively add new requests and remove completed requests at each decoding step. Long requests occupy the token budget and GPU memory within a batch for a long time, squeezing the resources available to short requests. This can reduce short-request throughput and raise tail latency. When long and short requests are mixed in the same batch, memory fragmentation and OOM risk also increase.

    This is also the main reason platforms limit single-input length and long inactive sessions. The platform needs to release these resources so that a small number of long sessions do not slow down the entire inference cluster.

    2. Choosing Among Three Rate-Limiting Algorithms

    Rate-limiting algorithms control different objects. When they are mixed, the rules become hard to explain and troubleshooting becomes harder.

    Algorithm Controlled object Key parameters Typical scenario Misuse risk
    Fixed window Requests or tokens per unit time; the counter resets at the end of the window Window length, limit Daily quotas, simple quota counting At the window boundary, nearly twice the requests may be allowed in a short period
    Sliding window Requests in the most recent N seconds; the window moves continuously over time Window length, limit, sub-window granularity API calls that need smooth limiting Requires timestamp records; finer granularity increases memory and compute overhead
    Token bucket Tokens are added to the bucket at a fixed rate, and each request consumes one token Refill rate, bucket capacity Allows short bursts while limiting the long-term average rate If bucket capacity is too large, burst requests hit upstream in a concentrated way and trigger rate limits

    Use the following order to choose:

    1. Confirm whether the platform limits requests per minute (RPM), tokens per minute (TPM), or daily total (RPD). When multiple dimensions exist, count them separately. If any dimension exceeds its limit, wait or degrade.
    2. If the workload allows short bursts, choose a token bucket. If strict smoothing is required, choose a sliding window. If only quota counting is needed, a fixed window is sufficient.
    3. Client-side rate limiting can only reduce the probability of rejection. The actual quota is determined by the server, so the client must also handle 429 responses.

    Pseudocode for a client-side token bucket:

    1. class TokenBucket:
    2. capacity = 10 # Bucket capacity: maximum allowed burst requests
    3. rate = 2 # Tokens added per second: long-term average rate
    4. tokens = capacity
    5. last = now()
    6. def acquire():
    7. tokens = min(capacity, tokens + (now() - last) * rate)
    8. last = now()
    9. if tokens >= 1:
    10. tokens -= 1
    11. return True
    12. return False # Alternatively, wait (1 - tokens) / rate seconds and retry

    3. Three Application-Layer Responses

    3.1 Context Compression

    The goal of context compression is to reduce the number of tokens per request while retaining the information the model needs to continue the conversation. Common parameters and rules are:

    • Keep the original text of the most recent N turns. Start with N = 6 and adjust it based on the workload.
    • Replace older history with a summary. Keep the summary to around 800 tokens or less.
    • Always retain the system prompt, explicit user constraints, and unfinished tasks; do not include them in compression.
    • Trigger compression when the context reaches about 70% of the model limit, leaving enough room for output.
    • When there is a large amount of history, store old messages in a vector store and retrieve relevant snippets for the current question.

    After compression, check whether the summary omits user constraints, numbers, or to-do items. Use a fixed set of test conversations for periodic validation.

    3.2 Multi-Model Fallback

    Multi-model fallback means switching to backup models by priority when the primary model is unavailable. The key is to decide whether to switch based on the error type and to use a circuit breaker to avoid repeatedly requesting a model that has already failed.

    1. providers = [primary, fallback A, fallback B] # Ordered by priority
    2. for p in providers:
    3. if circuit[p].is_open():
    4. continue # Circuit is open; skip directly
    5. try:
    6. return call(p, timeout=20) # Set timeout according to the workload
    7. except (RateLimited, Timeout, ServerError):
    8. circuit[p].record_failure()
    9. continue
    10. return degraded_response() # Return a degraded message or queue when all are unavailable

    Recommended parameters:

    • Timeout: for non-streaming requests, start with 15 to 30 seconds and adjust according to actual P95 latency.
    • Circuit opening condition: open the circuit after 5 consecutive failures or when the failure rate within 1 minute exceeds 50%, whichever occurs first.
    • Half-open probe: after the circuit stays open for 30 to 60 seconds, allow one probe request. Close the circuit on success; keep it open on failure.
    • Capability validation: compare the fallback model’s context length, output format, and language capability with the primary model. Do not switch if requirements are not met.

    Fallback changes output style and quality, so validate fallback model results with an evaluation set. Log switches to avoid silent changes that cannot be traced.

    3.3 429 Backoff and Retry

    When a 429 response is received, handle it as follows:

    1. Retry only temporary errors such as 429, 503, and timeouts. Errors such as 400, 401, and 403 indicate a problem with the request itself or with permissions; retrying is meaningless.
    2. If the response header contains Retry-After, wait according to that value first.
    3. When there is no Retry-After, use exponential backoff with random jitter: start with a base delay of 1 second, double it each time, and cap it at 60 seconds.
    4. Retry at most 5 times. After exceeding the retry count or the total workload timeout, stop retrying and return a failure.
    5. Automatically retry only idempotent requests. For generation requests, use a client-generated request ID for deduplication to avoid duplicate billing or duplicate writes.
    1. def call_with_retry(req, max_retries=5):
    2. for n in range(max_retries + 1):
    3. resp = send(req)
    4. if resp.ok:
    5. return resp
    6. if resp.status not in (429, 503) and not is_timeout(resp):
    7. raise_error(resp)
    8. if n == max_retries:
    9. raise_error(resp)
    10. wait = parse_retry_after(resp) or min(60, 1 * 2 ** n)
    11. sleep(random_between(0, wait)) # Full jitter to avoid synchronized retries

    Without jitter, many clients retry at the same moment, causing a retry storm that worsens 429 responses.

    4. Monitoring, Troubleshooting, and Compliance

    At a minimum, monitor the following metrics:

    • 429 ratio, counted separately by model and API.
    • P95 and P99 latency.
    • Quota remaining, shown as a percentage for daily and monthly quotas.
    • Fallback count and circuit state.
    • Retry success rate.
    • Average context length.

    Alert thresholds can serve as a starting point: alert when the 429 ratio exceeds 5% for 5 consecutive minutes; warn in advance when quota remaining falls below 20%; notify on-call staff when fallback count rises sharply in a short period. Adjust thresholds based on historical data.

    Common troubleshooting directions:

    • Frequent 429 responses: check whether concurrency is too high, whether retries lack jitter, and whether a single input exceeds the platform limit.
    • Long sessions suddenly fail: check whether the session exceeds the platform’s inactivity timeout. Critical state should be saved locally so the session can be rebuilt.
    • Output quality drops: check whether compression lost constraints, and whether the fallback model’s language or format matches the primary model.
    • Abnormal cost: check whether retries cause duplicate billing, and confirm that request ID deduplication is working.

    For compliance, follow the third-party platform’s terms of service and usage policies. Rate limiting, fallback, and retry are intended to keep services stable. They must not be used to bypass platform limits, nor should multiple accounts be rotated to evade billing or abuse free quotas. Desensitize user data before sending it to third-party APIs; summaries and logs generated by compression should also not retain sensitive information.