Why Free AI Services Need Quotas: Cost, Quotas, and Rate Limiting Practices

    This article explores the underlying reasons for enforcing quotas and rate limits in free AI services, driven by the high computational costs of large language models. It breaks down the cost model per request, analyzes various quota dimensions, and provides practical implementations of token bucket rate limiting in Python and Redis. Additionally, it outlines tiered degradation strategies to maintain service stability under high pressure.

    1. The Core Issue: Why Free Users Pose a Challenge

    Traditional internet service growth models are largely built on the premise of low marginal costs. A single page view or message distribution costs very little, allowing platforms to scale free users to acquire traffic, later monetizing through ads or subscriptions. Large language model (LLM) services break this premise. Every inference consumes compute time on accelerators like GPUs, and the consumption grows with the length of the input and output.

    Therefore, an increase in free users does not automatically bring revenue. As request volumes continue to rise, service providers must answer three questions: What is the cost of a single request? Are resources sufficient during peak times? Which scenarios should receive free resources?

    Free tiers, token quotas, rate limiting, and cost control ultimately serve the same goal: allowing limited compute power to serve the maximum amount of reasonable demand under controllable costs. When designing free quotas, developers should focus on five areas—cost budgets, rate limiting, degradation, monitoring, and gradual rollouts—rather than just stopping at cost formulas.

    2. Cost Model: Breaking Down a Single Request

    Before designing quotas, costs must be broken down to the single-request level. For most text generation services, the cost of a single request can be approximated as:

    Cost ≈ Input token count × Input unit price + Output token count × Output unit price

    A token is the basic unit of text processed by the model. In Chinese, a single character usually corresponds to one or more tokens, depending on the model’s tokenizer. The input portion includes system prompts, conversation history, and new user content.

    This formula has clear boundaries. The table below lists several factors that are often ignored:

    Factor Impact on Actual Cost Included in Formula
    Cache hit Actual computation decreases when reusing the same prefix No
    Batch amortization Unit cost decreases when multiple requests are merged for inference No
    GPU utilization Unit cost increases when utilization is low No
    Cold start time Adds extra overhead during initial scaling No
    Price differences across models The same request costs vary significantly on different models Depends on the input price

    Therefore, the formula is only suitable for rough estimates. True costs should be tracked over the long term by reconciling actual bills and inference logs.

    Let’s break down a hypothetical price. Assume a request has 3,000 input tokens and 800 output tokens, with an input price of $0.002 per 1,000 tokens and an output price of $0.008 per 1,000 tokens. These prices are for demonstration only and do not reflect any real vendor’s pricing. The cost of this request is:

    3000 / 1000 × 0.002 + 800 / 1000 × 0.008 = 0.006 + 0.0064 = 0.0124

    Output prices are typically higher than input prices, making long-text generation requests more expensive. This means that limiting only the input length cannot control costs; the output length must also be included in the quota.

    Multi-turn dialogues cause costs to accumulate gradually. Assume a system prompt of 300 tokens, 200 new user tokens per turn, and 600 model output tokens per turn:

    • Turn 1 input: 300 + 200 = 500 tokens
    • Turn 2 input: Must carry the first turn’s Q&A, i.e., 300 + (200 + 600) + 200 = 1300 tokens
    • Turn 3 input: 300 + (200 + 600 + 200 + 600) + 200 = 2100 tokens

    The new content across three turns is 600 user tokens plus 1,800 model output tokens, totaling 2,400 tokens. However, the cumulative billed input tokens across three turns reach 3,900 tokens. The excess over the new content is the result of historical context being repeatedly billed.

    Beyond direct calculation costs, there are two hidden costs. The first is VRAM occupation. During inference, the model must cache intermediate results from attention calculations; longer contexts consume more VRAM, reducing the number of concurrent requests a single GPU can serve. The second is queueing cost. Once concurrency exceeds capacity, new requests must wait. Excessive waiting degrades the user experience and increases tail latency.

    What providers truly care about is resource occupation per unit of time. A long-context request might consume resources equivalent to multiple short requests. Thus, rate limiting based solely on request count is often insufficient.

    3. Common Quota Dimensions

    Quotas can be designed across multiple dimensions. Each dimension controls different bottlenecks and has different side effects.

    Dimension Controlled Object Typical Method Main Bottleneck Main Side Effect
    Token consumption Input plus output tokens per minute or day Token bucket based on token count Compute and VRAM Long-text users are more likely to be limited and need to estimate usage
    Concurrency Number of requests processing simultaneously Semaphore VRAM and queueing time Long requests fill up concurrency, affecting short requests
    Request frequency Number of requests per unit time Fixed window or token bucket Access layer pressure Ignores request length differences, underestimates large requests
    Context length Token limit for a single input Truncating history, rejecting excessively long inputs VRAM and repeated billing Users lose early conversation content
    Output length max_tokens limit Default value plus hard limit High output price, long generation time Long text responses are truncated
    Daily total quota Total free resource pool Quota pool and budget alerts Cost budget Limits are likely to be triggered collectively at the end of the month

    In practice, multiple dimensions are usually combined. Request frequency prevents instantaneous surges, token consumption controls overall compute power, concurrency protects tail latency, and context and output length limit the maximum cost of a single request.

    4. Token Bucket Rate Limiting Implementation

    The token bucket concept works as follows: the bucket holds a maximum of capacity tokens, refilled at a rate of refill_rate per second. A single request consumes cost tokens; if the bucket lacks sufficient tokens, the request is rejected. The bucket’s capacity determines the maximum allowed burst, while the refill rate determines the long-term average rate.

    Below is a single-process version using the Python 3 standard library, with no external dependencies:

    1. import threading
    2. import time
    3. class TokenBucket:
    4. def __init__(self, capacity: float, refill_rate: float):
    5. self.capacity = capacity # Bucket capacity, i.e., maximum allowed burst tokens
    6. self.refill_rate = refill_rate # Tokens refilled per second
    7. self.tokens = capacity
    8. self.updated_at = time.monotonic()
    9. self.lock = threading.Lock()
    10. def allow(self, cost: float) -> bool:
    11. with self.lock:
    12. now = time.monotonic()
    13. elapsed = now - self.updated_at
    14. self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
    15. self.updated_at = now
    16. if self.tokens >= cost:
    17. self.tokens -= cost
    18. return True
    19. return False
    20. buckets: dict[str, TokenBucket] = {}
    21. def check_quota(user_id: str, input_tokens: int, max_output_tokens: int) -> bool:
    22. # Pre-deduct based on "input tokens plus max output tokens" to avoid over-issuance
    23. cost = input_tokens + max_output_tokens
    24. bucket = buckets.setdefault(
    25. user_id,
    26. TokenBucket(capacity=20000, refill_rate=200), # Example params, not recommended values
    27. )
    28. return bucket.allow(cost)

    A few things to note in this code. First, use time.monotonic() instead of time.time() because system time can be calibrated or rolled back, whereas the monotonic clock is unaffected. Second, the buckets dictionary will grow indefinitely with the number of users; production environments must implement expiration and eviction. Third, it only exists within a single process; in multi-instance deployments, the buckets of each instance are independent.

    In multi-instance scenarios, the state needs to be placed in Redis, using a Lua script to ensure that reading, calculating, and writing are an atomic operation. The dependency is redis-py (pip install redis).

    1. local key = KEYS[1]
    2. local capacity = tonumber(ARGV[1])
    3. local rate = tonumber(ARGV[2])
    4. local cost = tonumber(ARGV[3])
    5. local t = redis.call('TIME')
    6. local now = tonumber(t[1]) + tonumber(t[2]) / 1000000
    7. local data = redis.call('HMGET', key, 'tokens', 'ts')
    8. local tokens = tonumber(data[1]) or capacity
    9. local ts = tonumber(data[2]) or now
    10. tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate)
    11. local allowed = 0
    12. if tokens >= cost then
    13. tokens = tokens - cost
    14. allowed = 1
    15. end
    16. redis.call('HSET', key, 'tokens', tokens, 'ts', now)
    17. redis.call('EXPIRE', key, math.ceil(capacity / rate) + 1)
    18. return {allowed, tostring(tokens)}

    The Python invocation is as follows:

    1. import redis
    2. r = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)
    3. bucket_script = r.register_script(open("token_bucket.lua").read())
    4. def check_quota_redis(user_id: str, input_tokens: int, max_output_tokens: int) -> bool:
    5. cost = input_tokens + max_output_tokens
    6. allowed, _remaining = bucket_script(
    7. keys=[f"quota:{user_id}"],
    8. args=[20000, 200, cost], # capacity, rate, cost, example params
    9. )
    10. return int(allowed) == 1

    Here are production environment considerations:

    1. Clock drift. System times across different machines may be inconsistent. The Lua script uses Redis’s own TIME command, so all instances calculate the refill amount using the same clock.
    2. Atomicity. Do not GET and then SET, or concurrent requests will read the same stale value, leading to over-issuance. Lua scripts execute serially in Redis, avoiding this issue.
    3. Burst traffic. capacity determines how many tokens a user can burst at once. If the capacity is too large, instantaneous traffic can crush the inference cluster; if too small, normal multi-turn dialogues will be frequently rejected.
    4. Multi-instance. If all instances share a single Redis bucket, the quota is global. If Redis becomes unavailable, a clear degradation strategy should be defined, such as falling back to local buckets on each instance with limits proportionally divided by the number of instances, while triggering an alert.
    5. Usage correction. Pre-deduct based on the maximum output before the request, and refund the difference based on actual usage after completion, otherwise users will exhaust their quota prematurely due to pre-deduction. The refund logic must be idempotent to prevent duplicate refunds caused by retries.

    5. Tiered Degradation and Core Monitoring

    Rate limiting only rejects requests; degradation allows the service to continue operating under increased pressure. It is recommended to design according to the following tiers, where trigger thresholds should be calculated based on your own capacity:

    • L0 Normal: All free features are open, using standard context length and output limits.
    • L1 Mild Tightening: Lower the max_tokens limit and maximum context length for free users, and disable non-core long output features.
    • L2 Moderate Degradation: Switch free requests to a smaller, cheaper model, and limit concurrency.
    • L3 Heavy Degradation: Only allow existing sessions to continue; new sessions return a queue or quota limit notification.
    • L4 Circuit Breaker: New free requests are suspended; paid users and core services are unaffected.

    Every tier switch should have clear trigger conditions, such as queue wait time exceeding a certain threshold, or GPU VRAM utilization reaching a specific limit.