Compute Scheduling and Rate Limiting in High-Concurrency LLM APIs

    This article explains why LLM inference clusters overload under peak demand, which peak-shaving measures providers use, and how developers can design applications to handle API volatility. It covers KV Cache memory pressure, pricing and access controls, and a rate limiter that combines token quotas with concurrency limits.

    Recently, the API price of a newly released large language model rose sharply. Public reports described the increase as reaching 300% at one point. The exact figures should be checked against the vendor’s official pricing page and announcement dates. After the price change, request volume for the model remained high. This suggests that among models with similar capabilities, compute supply constraints directly affect a provider’s pricing and access policies.

    Several LLM providers have seen similar situations when releasing new versions. Request volume exceeds the capacity of the inference cluster within a short period, and providers can only protect their systems through rate limiting or price adjustments.

    This article explains three things from a system architecture perspective: why inference clusters overload, which peak-shaving measures providers commonly use, and how developers can design applications to handle API fluctuations.

    1. Why Inference Clusters Overload

    LLM inference uses resources differently from traditional web services. Traditional web services mainly consume CPU and network bandwidth, so they are I/O-intensive or lightweight in computation. LLM inference reads historical information each time it generates a token, which places heavy demands on both GPU memory and compute.

    During autoregressive generation, the model stores the KV Cache (key-value cache). The KV Cache holds the attention keys and values of previous tokens, so the model does not need to recompute the entire context for each new token. You can estimate the size of the KV Cache with the following approximate formula:

    1. Total KV Cache ≈ 2 × concurrent sequences × average sequence length × number of layers × KV heads × head dimension × bytes per element

    The factor of 2 accounts for the two caches, K and V. Consider a model with 80 layers, 8 KV heads, a head dimension of 128, and FP16 precision (2 bytes per element). Each token occupies 2 × 8 × 128 × 2 × 80 = 327,680 bytes, or about 320 KB. A single 4,096-token sequence therefore needs about 1.25 GiB of GPU memory.

    The formula shows that KV Cache grows roughly linearly with the number of concurrent sequences and the sequence length, not exponentially. Linear growth is still dangerous in practice. Long-context requests consume large amounts of memory. When several long requests arrive at the same time, peak memory usage can exceed the reserved capacity. Memory fragmentation also makes free space non-contiguous. Even when the total free memory looks sufficient, an allocation can fail because no contiguous block is large enough, which causes an out-of-memory (OOM) error. When an OOM occurs, the requests being processed either queue up or fail. Client retries then add to the load, which can eventually cause the cluster to collapse.

    In short, cluster overload happens when instantaneous demand for GPU memory and compute exceeds available resources. Average load often hides this problem. Teams need to monitor both peak load and the share of long requests.

    2. Common Peak-Shaving Measures

    When traffic spikes, the most direct response is to limit the number of requests entering the cluster. Providers use economic and technical measures for this.

    2.1 Pricing

    Higher prices can reduce low-value or latency-tolerant requests in the short term. This lets limited compute serve high-value use cases first. This demand-regulation approach is grounded in queueing theory. Its cost is that some users have a worse experience, and some may switch to other models. The effectiveness depends on the price elasticity of demand and the availability of alternative models.

    2.2 Access Thresholds

    Restricting premium subscriptions and tightening call quotas for new users can control concurrency at the source. This also reduces malicious calls and sudden surges. However, these measures affect legitimate new users’ onboarding experience, so they are usually suitable only as temporary measures.

    2.3 API Gateway Rate Limiting

    Providers typically deploy rate limiting and circuit breaking at the API gateway. Two common algorithms are used. The token bucket allows bursts of traffic to a certain degree, which suits workloads with unstable request patterns but a controllable average rate. The leaky bucket shapes traffic into a constant rate, which suits protecting downstream services that are sensitive to rate.

    For LLM workloads, limiting by requests per second (QPS) alone is often not enough, because the token length of individual requests can differ by dozens of times. A more reliable approach combines concurrency limits, token budgets, user tiers, and priority queues.

    The following pseudocode shows an implementation approach for a single process:

    1. import asyncio
    2. import time
    3. class ModelAPIRateLimiter:
    4. def __init__(self, max_tokens_per_minute, max_concurrent_requests):
    5. self.max_tokens_per_minute = max_tokens_per_minute
    6. self.max_concurrent = max_concurrent_requests
    7. self.current_concurrent = 0
    8. self.used_tokens = 0
    9. self.window_start = time.monotonic()
    10. self._lock = asyncio.Lock()
    11. def _reset_window_if_needed(self, now):
    12. if now - self.window_start >= 60:
    13. self.window_start = now
    14. self.used_tokens = 0
    15. async def handle_request(self, user_request):
    16. estimated_tokens = user_request.estimate_tokens()
    17. async with self._lock:
    18. self._reset_window_if_needed(time.monotonic())
    19. if self.current_concurrent >= self.max_concurrent:
    20. # The inference cluster has reached its concurrency limit. Retry later.
    21. raise ServiceUnavailableError("The inference cluster has reached its concurrency limit. Please retry later.")
    22. if self.used_tokens + estimated_tokens > self.max_tokens_per_minute:
    23. # The token quota for the current time window is exhausted.
    24. raise RateLimitExceededError("The token quota for the current time window is exhausted.")
    25. # Reserve quota before forwarding so that concurrent requests
    26. # cannot all pass the check at the same time.
    27. self.used_tokens += estimated_tokens
    28. self.current_concurrent += 1
    29. try:
    30. return await self.forward_to_inference_cluster(user_request)
    31. except Exception:
    32. # The request failed, so return the reserved quota.
    33. async with self._lock:
    34. self.used_tokens = max(0, self.used_tokens - estimated_tokens)
    35. raise
    36. finally:
    37. async with self._lock:
    38. self.current_concurrent -= 1

    The code highlights four key points. First, quota is reserved before forwarding, which prevents multiple requests from passing the check together and exceeding the limit. Second, the reserved quota is returned when a request fails. Third, the time window resets every minute.