Rate Limiting LLM Inference in Practice: Token Quotas, Graceful Degradation, and Dynamic Batching

    This guide shows how to build a practical rate limiting scheme for LLM inference services. It combines token-based quotas, session reclamation, tiered degradation, queuing rules, and dynamic batching parameters, and uses Redis Lua scripts for atomic quota checks. The example values are illustrative and should be tuned based on the GPU model, model size, and load test results.

    When a free user sends dozens of rounds of long conversation, or pastes a large document in one request, GPU memory and compute are noticeably consumed, while these requests generate almost no revenue. For LLM services, rate limiting should target computational cost. Request count is only one reference metric. This article describes how to combine token quotas, session reclamation, tiered degradation, and dynamic batching into a practical rate limiting scheme. All numbers in this article are examples. Adjust them based on the GPU model, model size, and load test results.

    1. Defining What Rate Limiting Should Control

    Traditional web services have relatively stable per-request costs, so QPS-based rate limiting is usually sufficient. LLM inference is different. Its cost comes mainly from three sources.

    First, inference cost is strongly tied to input length. A request with 20K input tokens may consume many times more compute than a short question of a few dozen tokens. If only request counts are measured, a small number of long requests can slow down the entire cluster.

    Second, the KV cache consumes GPU memory. When a model generates text, it must cache the Key and Value vectors of previous tokens. With a fixed model architecture and precision, KV cache memory usage grows roughly in proportion to context length. The longer the context, the fewer requests a single GPU can serve at the same time. Attention computation grows quadratically with sequence length. However, this affects computation time, and its growth pattern differs from that of memory usage, so the two should be considered separately during design.

    Third, compute has an opportunity cost. Inference and training usually share the same GPUs or the same scheduling system. If free traffic takes too much capacity, it crowds out the resources needed for pretraining, fine-tuning, and evaluation.

    Therefore, the metering unit for rate limiting should be tokens. The number of concurrent sessions and the session length should also be considered.

    2. Designing Token Quotas and Time Windows

    1. Quota Dimensions

    Quotas should cover at least the following dimensions.

    Dimension Purpose Example value Action when exceeded
    Max input tokens per request Prevents a single request from occupying all GPU memory 32K Return 400 and ask the user to shorten the input
    Max output tokens per request (max_tokens) Controls the length of a single generation 4K Truncate the output or return a parameter error
    Total tokens within a window Limits the total compute within a time window 50K per hour, 200K per day Return 429 with Retry-After
    Concurrent sessions Limits the number of sessions occupying the KV cache at the same time 2 Queue or reject
    Turns per session Prevents long conversations from occupying GPU memory for extended periods 30 turns Prompt the user to start a new session, or trigger history summary compression

    To determine the example values, run load tests on the target GPU using the input and output token distribution from real traffic. Find the token throughput a single GPU can sustain while meeting the P99 latency target. Then allocate quotas based on the proportion of free users.

    2. Quota Accounting

    Keep two points in mind when metering.

    The first is pre-deduction and settlement. When a request arrives, deduct an estimated cost from the quota before processing. The estimate is the input token count plus max_tokens. This prevents many requests from passing the check at the same time and overselling the quota. After the request finishes, compare the actual usage (input tokens plus actual output tokens) with the estimate. Refund the difference if the estimate was too high, or charge the difference if it was too low.

    The second is that input must be tokenized before counting. Estimating by character count can produce large errors, especially for Chinese text and code.

    3. Redis Key Design

    Quota data is stored in Redis. The recommended key format is:

    1. quota:{tier}:{user_id}:{window_start}

    window_start is the Unix timestamp of the window start. It is obtained by rounding the current time down to the window length. For example, for a one-hour window, window_start = floor(now / 3600) * 3600. When the window rolls over, new requests naturally land on a new key. Old keys expire automatically through their TTL, so no separate cleanup job is needed.

    A fixed window is simple to implement and uses little memory, but bursts can occur at window boundaries. In the worst case, a client can pass nearly twice the quota across two adjacent windows. If bursts are a concern, use a sliding window instead. It records the timestamp and token count of each request in a sorted set (ZSET). The trade-off is higher memory and computation overhead. For free users, a fixed window with a short length, such as one hour, is usually sufficient.

    4. Configuration Example

    1. quota:
    2. free:
    3. max_input_tokens: 32768
    4. max_output_tokens: 4096
    5. window:
    6. type: fixed
    7. size_seconds: 3600
    8. token_limit: 50000
    9. concurrent_sessions: 2
    10. max_turns_per_session: 30
    11. on_exceed: reject_429
    12. paid:
    13. max_input_tokens: 131072
    14. max_output_tokens: 8192
    15. window:
    16. type: fixed
    17. size_seconds: 3600
    18. token_limit: 500000
    19. concurrent_sessions: 16
    20. max_turns_per_session: 200
    21. on_exceed: queue

    When a request exceeds the limit, the API should return HTTP 429 with a Retry-After header that tells the client how many seconds to wait. When the input exceeds the single-request limit, return 400 and state the limit in the error message so the client can truncate the input.

    3. Atomic Rate Limiting with Lua Scripts

    When multiple gateway nodes read and write the same quota key at the same time, a sequence of GET