Designing Service Quotas for LLM Inference Under Compute Shortages

    This article explains why LLM service providers impose usage quotas when accelerator capacity runs short. It covers the main quota types, server-side rate limiting and tiered quota design, capacity planning, client-side retry and session handling, monitoring, and steps for teams that face quota limits.

    1. Where Quotas Come From

    LLM inference depends on large amounts of accelerator resources. Each concurrent request occupies GPU memory, including the KV Cache, which stores context beyond the model parameters. Longer conversations create larger caches, so each session consumes more resources.

    Resource shortages usually result from three factors that often occur together:

    1. Sudden demand spikes: A new feature launch, a viral event, or traffic routed from third-party aggregator platforms can multiply call volume within a short time.
    2. Long-session occupancy: Inactive long conversations still hold KV Cache. If the system does not reclaim these resources, they reduce capacity for active users.
    3. Limited supply: Accelerator procurement, data center expansion, and model deployment all take time, so supply cannot respond immediately to demand.

    When these pressures exceed what the system can handle, providers usually impose quotas rather than let all requests slow down or fail. The goal of a quota is to direct limited resources to the requests that need them most and keep the overall service available.

    2. Common Quota Types

    Quota Type Target Typical Purpose
    Session retention policy Long-idle sessions Reclaim KV Cache
    Per-request input length limit Length of a single request’s text Control computation cost per request
    Daily or monthly quota Accounts or applications Balance resource allocation among users
    Rate limits (RPM, TPM) Requests per minute and tokens per minute Smooth out short-term peaks
    Queuing and degradation Requests beyond capacity Keep core paths available

    These policies are often combined. For example, a system might first smooth traffic with rate limits, then cap total volume with a daily quota, and finally reclaim resources from long sessions.

    2.1 Session Retention Policy

    A session retention policy determines how long a conversation keeps its context after it becomes inactive. Two factors need to be balanced. A retention period that is too short interrupts users who are working across multiple sessions. A period that is too long wastes resources.

    A better approach is to store session history in external storage and load only the key context on the server when needed. Even if a session is reclaimed, users can resume their work when they return by restoring it from a history summary.

    2.2 Input Length Limit

    An input length limit directly caps the size of a single computation. It should be based on the model’s maximum context window, the response latency target, and the cost model. Text that exceeds the limit usually needs to be split into segments rather than simply truncated.

    The following function splits text into fixed-length chunks and keeps some overlap so that sentences are not cut apart at the boundaries:

    1. def split_text(text: str, max_chars: int = 20000, overlap: int = 200) -> list[str]:
    2. """Split long text into overlapping chunks."""
    3. if overlap >= max_chars:
    4. raise ValueError("overlap must be smaller than max_chars")
    5. chunks = []
    6. start = 0
    7. while start < len(text):
    8. end = min(start + max_chars, len(text))
    9. chunks.append(text[start:end])
    10. if end == len(text):
    11. break
    12. start = end - overlap
    13. return chunks

    In practice, it is better to split along paragraph or sentence boundaries rather than at fixed character counts. The example above only illustrates the basic idea.

    3. Server-Side Quota Design

    3.1 Token Bucket Algorithm

    The token bucket is one of the most widely used rate-limiting algorithms. The bucket generates tokens at a fixed rate, and each request consumes a certain number of tokens. The bucket’s capacity determines the maximum burst size that is allowed.

    1. import threading
    2. import time
    3. class TokenBucket:
    4. def __init__(self, rate: float, capacity: int):
    5. self.rate = rate # tokens added per second
    6. self.capacity = capacity # maximum burst size
    7. self.tokens = float(capacity)
    8. self.updated = time.monotonic()
    9. self.lock = threading.Lock()
    10. def acquire(self, n: int = 1) -> bool:
    11. with self.lock:
    12. now = time.monotonic()
    13. elapsed = now - self.updated
    14. self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
    15. self.updated = now
    16. if self.tokens >= n:
    17. self.tokens -= n
    18. return True
    19. return False

    In a multi-instance deployment, the token state must live in shared storage. Otherwise, each instance counts separately, and the quota stops working.

    3.2 Tiered Quotas

    A single quota struggles to balance fairness and efficiency. A common approach is to set quotas at multiple levels:

    • Global level: Protects the overall capacity ceiling of the service.
    • User level: Prevents a single account from consuming all available resources.
    • Application level: Allocates separate budgets to different business lines.

    The limits at each level should be calculated together. A global limit alone can allow a few heavy users to crowd out others. A user limit alone may not protect the service when overall capacity drops.

    3.3 Capacity Planning

    Capacity planning starts from peak traffic, not average traffic. Operators should collect the following metrics:

    • Peak requests per second and their distribution
    • Average input and output length per request
    • Target values for time to first token and full response latency
    • The number of concurrent requests a single accelerator can handle within the target latency

    Based on this data, teams can estimate the number of accelerators needed and reserve a margin for traffic bursts. The size of the margin depends on how much availability the business requires. No single standard applies.

    4. Client-Side Adaptation

    4.1 Exponential Backoff with Jitter

    When a response indicates rate limiting or service overload, clients should back off and retry instead of sending the same request immediately. Retrying at fixed intervals causes many clients to return at the same moment, which creates a new peak.

    1. import random
    2. import time
    3. class TransientError(Exception):
    4. """Raised when the response indicates rate limiting or temporary overload."""
    5. def call_with_backoff(fn, max_retries: int = 5, base: float = 0.5, cap: float = 30.0):
    6. for attempt in range(max_retries + 1):
    7. try:
    8. return fn()
    9. except TransientError:
    10. if attempt == max_retries:
    11. raise
    12. # Full jitter: pick a random wait time within an exponentially growing window.
    13. delay = min(cap, base * (2 ** attempt))
    14. time.sleep(random.uniform(0, delay))

    Apply backoff only to retryable errors, such as rate limits and temporary overload. Return errors such as invalid parameters or authentication failures immediately. Retrying them only wastes quota.

    4.2 Externalizing Session State

    If session history is stored only on the server, users lose their context once the session is reclaimed. A more reliable approach is to keep the full history on the client or in the business database. After a session expires, restore it as follows:

    1. Generate a structured summary of the earlier conversation that keeps the user’s goals, confirmed conclusions, and open action items.
    2. When a new session starts, inject the summary as system context instead of replaying the full history.
    3. Keep the most recent conversation turns in their original form so the context stays coherent.

    This approach reduces context length and limits long-term use of server resources.

    4.3 Input Preprocessing

    Cleaning and compressing input on the client side reduces wasted token consumption. Common techniques include removing duplicate content, stripping irrelevant formatting markup, and splitting large documents into sections before processing them. For very long documents, a smaller model can first extract a summary, and the summary can then be passed to the main model.

    5. Observability and Alerting

    After a quota policy goes live, teams need to monitor its effects continuously. At a minimum, track the following metrics:

    Metric Description Alerting Guidance
    Rate-limit response ratio Share of requests that receive rate-limit or busy errors Alert when the ratio stays above a threshold for several minutes
    Queue wait time percentiles P95 and P99 queue wait times Alert when wait times exceed the latency target
    Session reclamation count Number of long sessions reclaimed per hour Check whether the retention policy is too strict when the count spikes
    Per-user usage distribution How usage concentrates among users Investigate possible abuse when usage becomes abnormally concentrated

    Logs should record the request identifier, the quota type, and the reason for rejection so that issues can be traced afterward. Logs should not contain users’ raw input content or secret keys.

    6. A Checklist for Business Teams

    When quotas limit service, teams can handle the situation in the following order:

    1. Map the call paths: Identify which features depend on long sessions or large text inputs, and decide whether they can be split or shortened.
    2. Set up fallback options: When the service is busy, serve cached results, offer simplified features, or show queue notifications instead of returning bare errors.
    3. Manage cost and quota: Schedule batch jobs for off-peak hours, and reserve priority quota for interactive tasks.
    4. Communicate clearly: Explain the quota rules and the expected recovery process to users. If no official timeline exists, avoid promising one.

    Quotas are a normal resource management tool. When well designed, they protect core user experience under heavy load and keep the system operating within manageable limits.