Compute Constraints and Session Resource Governance in LLM Inference Services

    A practical guide to managing GPU compute constraints in large language model inference services, covering KV cache overhead, multi-layer rate limiting (session, input, and user levels), availability metrics conversion, and incident postmortem practices for engineering teams.

    Why Service Shape Changes When Compute Is Scarce

    The cost of serving large language model inference is dominated by GPUs. Every request consumes VRAM, compute units, and bandwidth, and neither GPU count nor memory capacity can be scaled linearly in the short term. When request volume grows quickly, service providers typically adjust the service shape first rather than immediately adding hardware. Common adjustments include tightening session duration, reducing per-request input length, setting user quotas, and degrading non-critical features during peak periods.

    These adjustments are not just product-level trade-offs; they directly affect system design. Engineering teams need to answer three questions: what exactly is consuming the resources, at which layer should limits be applied, and how should the reasons for those limits be communicated clearly to users? The rest of this article follows that order.

    KV Cache: The Hidden Cost of Long Sessions

    In autoregressive generation, every new token the model produces depends on the attention computation results of all previous tokens. To avoid recomputing them, inference engines cache the Key and Value tensors for each layer — commonly known as the KV cache.

    The KV cache has these characteristics:

    • Its size is proportional to the context length. The longer the context, the more VRAM it consumes.
    • It typically resides in GPU VRAM, with fast read/write access but limited capacity.
    • After a session ends, if the cache is not released promptly, it keeps occupying VRAM even after the user has left.

    As a result, a long-running session with no interaction continuously holds VRAM that could serve active requests. This is the direct justification for reclaiming idle sessions.

    The following example shows an idle-timeout-based eviction approach. The timeout value is illustrative only; in production, it should be determined by measuring actual traffic patterns and VRAM pressure.

    1. import time
    2. from dataclasses import dataclass, field
    3. IDLE_TTL_SECONDS = 30 * 60 # Example value: 30 minutes without interaction marks a session as idle
    4. @dataclass
    5. class Session:
    6. session_id: str
    7. kv_bytes: int
    8. last_active: float = field(default_factory=time.monotonic)
    9. class SessionManager:
    10. def __init__(self, idle_ttl: float = IDLE_TTL_SECONDS):
    11. self.idle_ttl = idle_ttl
    12. self.sessions: dict[str, Session] = {}
    13. def touch(self, session_id: str, kv_bytes: int) -> None:
    14. """Called on every user interaction to refresh the active timestamp and record current cache usage."""
    15. session = self.sessions.get(session_id)
    16. if session is None:
    17. session = Session(session_id, kv_bytes)
    18. self.sessions[session_id] = session
    19. session.kv_bytes = kv_bytes
    20. session.last_active = time.monotonic()
    21. def evict_idle(self) -> list[str]:
    22. """Scan for and remove idle sessions, returning the list of released session IDs."""
    23. now = time.monotonic()
    24. expired = [
    25. sid for sid, s in self.sessions.items()
    26. if now - s.last_active > self.idle_ttl
    27. ]
    28. for sid in expired:
    29. del self.sessions[sid] # The inference engine should also be notified here to release the corresponding KV cache
    30. return expired

    This code only describes the session-layer data structures. Actually freeing VRAM requires the inference engine to provide a corresponding eviction mechanism, as noted in the code comments.

    Three Layers of Rate Limiting

    Rate limiting should not be enforced at a single point. Based on resource type and blast radius, it can be divided into three layers.

    Session Layer: Controlling Idle Resources

    Session-layer policies target resources that are “held but not doing work.” Typical practices include:

    1. Setting an idle timeout, after which the cache is released.
    2. For evicted sessions, storing the conversation history as text so the context can be recomputed when the user returns. This frees VRAM without losing user data, at the cost of the latency introduced by recomputation.
    3. Showing an in-UI notice that the session will be reclaimed, with options to export or save it.

    Input Layer: Limiting Per-Request Size

    The longer a single input is, the higher the compute load and peak VRAM usage during the prefill stage. Capping input length prevents a few extremely long requests from monopolizing resources.

    1. MAX_INPUT_CHARS = 20_000 # Example threshold; should be determined based on the model's context window and cost analysis
    2. def validate_input(text: str) -> None:
    3. """Validate length before the request enters the inference queue; reject with a clear error if it exceeds the limit."""
    4. if len(text) > MAX_INPUT_CHARS:
    5. raise ValueError(
    6. f"Input is {len(text)} characters, exceeding the per-request limit of {MAX_INPUT_CHARS} characters. Please split it into segments."
    7. )

    Validation should happen at the entry point — the earlier a request is rejected, the less compute is wasted. Error messages should include both the current length and the limit so users can adjust on their own.

    User Layer: Daily Quotas and Smooth Throttling

    Daily quotas ensure most users get baseline service and prevent a few high-frequency users from exhausting capacity. A quota represents only a long-term average rate; short bursts still need smoothing. The token bucket is a common implementation: the bucket has a fixed capacity, tokens are replenished at a fixed rate, and each request consumes a corresponding number of tokens.

    1. import time
    2. class TokenBucket:
    3. def __init__(self, capacity: int, refill_per_sec: float):
    4. self.capacity = capacity
    5. self.refill_per_sec = refill_per_sec
    6. self.tokens = float(capacity)
    7. self.updated = time.monotonic()
    8. def allow(self, cost: int = 1) -> bool:
    9. now = time.monotonic()
    10. elapsed = now - self.updated
    11. self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_per_sec)
    12. self.updated = now
    13. if self.tokens >= cost:
    14. self.tokens -= cost
    15. return True
    16. return False

    Daily quotas can be combined with token buckets: the token bucket controls instantaneous rate, while a daily counter controls total volume. When a quota is exceeded, the error response should include a reason category (e.g., server busy or quota exhausted) and a suggested retry time, so users do not retry repeatedly.

    Converting Availability Metrics into Downtime

    Service availability is usually expressed as a percentage, but percentages are not intuitive. Converting them into annual or monthly downtime makes the impact easier to assess.

    The conversion formulas are:

    • Annual downtime = 8760 × (1 − availability)
    • Monthly downtime = 720 × (1 − availability), assuming a 30-day month

    The following examples help illustrate:

    Availability Annual Downtime (hours) Monthly Downtime (hours)
    99.0% 87.6 7.2
    99.5% 43.8 3.6
    99.9% 8.76 0.72
    1. HOURS_PER_YEAR = 365 * 24
    2. def downtime_hours(availability_pct: float, period_hours: float = HOURS_PER_YEAR) -> float:
    3. """Compute downtime hours within a reporting period from an availability percentage."""
    4. return period_hours * (1 - availability_pct / 100)
    5. print(round(downtime_hours(99.5), 1)) # 43.8

    When computing these numbers, pay attention to the measurement criteria. First, distinguish full outages from performance degradation. Slower responses, higher generation latency, and occasional request failures usually do not count as full downtime but still significantly affect user experience. Second, state the measurement time window. A few months of data can hide concentrated short-term failures, so weekly or daily statistics should be kept alongside longer windows. Third, state whether scheduled maintenance is included.

    Incident Classification and Postmortems

    Incident postmortems are the foundation of improving reliability. Each incident should at minimum record:

    • Start and end times, plus the criteria used to determine them.
    • Impact scope, including affected endpoints, features, and user groups.
    • Severity: full outage, partial outage, or performance degradation.
    • Root cause and trigger conditions.
    • Mitigation actions and the recovery process.
    • Follow-up improvement items, each with an owner and a deadline.

    Distinguishing severity levels helps allocate resources. For example, an incident affecting only auxiliary features can be assigned lower priority, while one affecting the core conversation flow should be handled immediately.

    For affected paying users or API users, a common remedy is granting credits based on downtime duration or the number of affected requests. Compensation rules should be published in advance and applied consistently; deciding them ad hoc after the fact invites disputes.

    Engineering Practice Recommendations

    Based on the analysis above, teams can proceed in the following order:

    1. Establish resource monitoring. Continuously collect VRAM usage, cache hit rate, queue length, and request latency, and set alert thresholds.
    2. Measure capacity limits. Based on peak traffic, average session length, and per-request VRAM usage, calculate how many concurrent sessions can be supported.
    3. Apply layered rate limiting. Define policies at the session, input, and user layers, and record the number of requests rejected at each layer.
    4. Adjust parameters gradually. Before changing timeouts, input limits, or quotas, validate them on a small fraction of traffic and monitor rejection rates and user feedback.
    5. Design clear user-facing messages. Messages should include the reason for the limit, the current limit value, and the actions users can take.
    6. Conduct regular postmortems. After every incident, update monitoring rules and rate-limiting parameters, and track whether improvement items are completed.

    There is no one-time optimal trade-off between reliability and cost. Restrictions reduce some users’ freedom, but they keep the core pipeline available when resources are tight. Engineering teams need to document restriction rules, impact scope, and recovery plans together — only then can they make explainable, reviewable decisions under pressure.