LLM Inference Capacity: Where Compute Goes and How to Handle Traffic Surges
LLM inference services often face sudden capacity pressure when usage grows, integrations multiply, prompts get longer, and batch jobs arrive in bursts. This article traces where compute is consumed across prefill, decode, and KV cache, then presents practical guidance for capacity planning, tiered queues, continuous batching, token-based rate limiting, degradation, cost control, and observability.
1. Background: Why Request Volume Can Jump Suddenly
In recent months, many large language model services have seen similar patterns: weekly request volume grows severalfold within a few months, followed by longer queues, response timeouts, and rate-limit errors on the server side. These incidents do not always come from a single product going viral. They often result from several common factors叠加.
- User growth: New feature launches, marketing campaigns, or word-of-mouth can bring in a large number of new users within a short period.
- Changes in integration patterns: More business systems connect to models through APIs, and automated calls occur far more frequently than manual usage.
- Heavier request shapes: Prompts are getting longer, carrying more conversation history, retrieved snippets, and tool outputs, so input token counts rise.
- Concentrated batch submissions: Offline summarization, data cleaning, batch review, and similar jobs often trigger at fixed times, creating bursty traffic.
Tokens are the basic unit for model metering and compute consumption. Both input tokens and output tokens consume compute resources, but their costs differ. Output tokens usually need to be generated one by one, which takes longer and consumes more resources. Therefore, evaluating capacity by request count alone is far from enough; token volume must be considered at the same time.
2. Where Compute Goes: The Resource Path of a Request
To understand capacity problems, it helps to look at the stages an inference request goes through. A typical flow is as follows:
- The request passes through the gateway, where authentication, rate limiting, and routing are completed.
- The request enters a queue and waits for an available compute instance.
- In the prefill stage, all input tokens are processed at once. This stage is compute-intensive and mainly consumes compute power.
- In the decode stage, output tokens are generated one by one. Each generated token requires reading model weights and historical cache, so this stage is mainly limited by memory bandwidth and cache capacity.
- The result is post-processed, returned, and recorded for metering.
The most easily overlooked part of this path is the KV cache. It stores the attention keys and values for each processed token to avoid repeated computation, but it consumes a large amount of GPU memory. The KV cache size per token can be estimated with the following formula:
bytes per token = 2 × layers × KV heads × head dimension × bytes per element
The coefficient 2 accounts for both Key and Value data. Consider a hypothetical configuration: 32 layers, 8 KV heads, head dimension 128, and 16-bit floating-point storage. Each token then occupies about 128 KB. A request with a 32K context length needs about 4 GB of GPU memory for KV cache alone. The more long requests run concurrently on the same GPU, the fewer concurrency slots remain available. This means long-context requests crowd out resources far beyond their literal token count.
When GPU memory is exhausted, new requests can only wait in the queue, and queue time grows. This is the direct reason users perceive the service as “getting slower.”
3. Capacity Evaluation: Deriving Resource Requirements from Business Metrics
Capacity planning starts by converting business volume into resource requirements. At minimum, break down the following metrics:
- Peak requests per second (peak QPS): Use the real value during business peak hours, not the daily average.
- Average input tokens and average output tokens: Measure them based on the request distribution, and distinguish between short and long requests.
- Time to first token (TTFT): The time users wait for the first token to appear, mainly affected by prefill and queueing.
- Time per output token (TPOT): Determines generation speed and is mainly affected by the decode stage.
- Stable throughput per instance: The token rate a single instance can sustain while meeting the target latency.
Per-instance throughput must be obtained through load testing. It cannot be copied directly from vendor claims or others’ experience. Load tests should use request samples close to the real distribution, including length distribution, concurrency patterns, and multi-turn conversation shapes. Fixed-length load tests often overestimate system capacity.
The following example estimates the number of instances required. All throughput parameters are hypothetical and must be replaced with your own load-test data:
import mathdef estimate_instances(peak_qps, avg_in, avg_out,prefill_tps, decode_tps, headroom=1.3):"""peak_qps: Peak requests per secondavg_in: Average number of input tokensavg_out: Average number of output tokensprefill_tps: Prefill throughput per instance (input tokens/second)decode_tps: Decode throughput per instance (output tokens/second)headroom: Redundancy factor for fluctuations and failures"""need_prefill = peak_qps * avg_in / prefill_tpsneed_decode = peak_qps * avg_out / decode_tps# Prefill and decode share the same instance pool; the larger value is the bottleneckreturn math.ceil(max(need_prefill, need_decode) * headroom)# Example: peak 200 QPS, average input 1500 tokens, average output 400 tokensprint(estimate_instances(200, 1500, 400, 40000, 3000)) # Output: 35
This result shows that the decode stage is the bottleneck in this example. If output length is optimized or decode throughput is improved, the required number of instances will drop noticeably. The estimate should also be compared with historical peaks, and procurement and onboarding lead times should be reserved, because new instances often take days or even longer from request to readiness.
4. Elasticity and Scheduling: Serving More Important Requests with Limited Compute
Capacity planning addresses whether total capacity is sufficient. Scheduling addresses who gets limited resources first.
4.1 Tiered Queues
Different businesses tolerate latency very differently. Conversational interaction is sensitive to time to first token, while batch summarization can accept minute-level waits. At minimum, separate three types of queues:
- Real-time queue: For online interaction, with strict timeout thresholds and highest scheduling priority.
- Near-real-time queue: For asynchronous tasks, allowing moderate queueing and volume limiting by time window.
- Offline queue: For batch jobs, running during off-peak hours or on idle capacity, and preemptible.
After tiering, bursty submissions from offline jobs will not squeeze online requests.
4.2 Continuous Batching
Continuous batching is a common technique for improving utilization. It allows a slot to be released to a new request as soon as one request finishes, avoiding a whole batch waiting for the slowest request. Compared with fixed batching, this can significantly improve resource utilization in the decode stage. However, when request lengths within a batch vary widely, long requests can still slow the overall pace.
4.3 Choosing Scaling Metrics
Scaling by CPU utilization often fails for LLM services, because when GPU utilization is high, the system may already be in a queueing state. More reliable signals include:
- Waiting queue depth and queue time;
- P95 or P99 time to first token;
- GPU memory usage and KV cache usage;
- The proportion of requests rejected or timed out per unit time.
Scaling must also consider cold start. Loading model weights and warming caches can take a long time, so scale ahead or keep a number of warm standby instances.
5. Rate Limiting, Degradation, and Fairness
Even with reasonable capacity planning, burst traffic can still exceed expectations. In that case, rate limiting and degradation are needed to protect core services.
5.1 Token-Based Rate Limiting
Rate limiting by request count alone cannot reflect real load. One long-context request may consume the resources of dozens of short requests. A token bucket metered by tokens is closer to actual load:
class TokenBucket:def __init__(self, rate, capacity):self.rate = rate # Token quota replenished per secondself.capacity = capacity # Bucket capacity, i.e., allowed burst quotaself.tokens = capacityself.last = now()def allow(self, cost):t = now()self.tokens = min(self.capacity,self.tokens + (t - self.last) * self.rate)self.last = tif self.tokens >= cost:self.tokens -= costreturn Truereturn False # Return a rate-limit response with a suggested retry time
Rate limits should be set by tenant or application dimension, with configurable quota tiers. This prevents a single large customer from consuming all resources and affecting other users.
5.2 Tiered Degradation
Degradation means deliberately reducing service quality under resource pressure rather than letting all requests fail together. Common strategies include:
- Limit the maximum output length to reduce decode time per request;
- Temporarily disable non-core features, such as long-form generation or complex tool calls;
- Route some requests to smaller models and indicate this in the response;
- Return cached results for identical requests.
Each degradation strategy must define trigger and recovery conditions in advance and be validated through drills.
5.3 Semantics of Queue Timeouts
Queue timeouts should return clear error codes, such as 429 for rate limiting and 503 for temporary service unavailability, along with a retry interval. Clients need exponential backoff and jitter to avoid many requests retrying at the same moment and creating a second surge.
6. Cost Control: Reducing Wasteful Token Consumption
When compute is tight, cost and stability become the same problem. Reducing wasteful consumption is often more effective than adding resources.
- Prefix caching: When multiple requests share the same system prompt or document prefix, reuse the already computed KV cache to reduce prefill overhead. Verify the cache hit rate and pay attention to cache isolation between tenants.
- Semantic caching: Return existing answers for highly similar questions. This approach suits knowledge question answering and similar scenarios, but it must handle stale answers and private data. It is not suitable for personalized content.
- Prompt trimming: Remove duplicate instructions and redundant conversation history, keeping only the context relevant to the current question.
- Output length constraints: Use a reasonable maximum output length parameter to prevent the model from generating content beyond requirements.
- Cost breakdown: Measure cost per thousand tokens by feature, tenant, and API to identify high-consumption areas.
Cost data should be placed on the same dashboard as business metrics so teams can judge whether a given increase in call volume is reasonable.
7. Observability: Using Metrics to Determine Whether the System Is Actually Under Stress
Observability determines whether a team can detect problems early. Monitor the following metrics:
- P50, P95, and P99 time to first token and time per output token;
- Waiting queue depth and queue time;
- GPU memory usage and KV cache usage per instance;
- Prefix cache hit rate;
- Ratios of 429, 503, and timeouts;
- Token usage and growth trends by tenant.
Alerts should be tiered. For example, send a notification when queue depth exceeds a threshold, and trigger urgent handling when time to first token remains above target and the rejection ratio rises. Alerts must map to clear runbooks; otherwise, they only add noise.
8. Implementation Checklist
- Load testing has been completed with a realistic request distribution, and per-instance throughput has been recorded.
- A prediction model for peak QPS and token volume has been established, with headroom reserved.
- Real-time, near-real-time, and offline queues have been separated, and offline jobs are preemptible.
- Scaling is based on queue and latency metrics, with cold-start time considered.
- Rate limiting is metered by tokens and differentiated by tenant tier.
- Degradation strategies have defined trigger and recovery conditions and have been drilled.
- Error codes and client retry policies have been unified, including backoff and jitter.
- Cost and cache hit rate are included in daily dashboards.
- Procurement and scaling lead times are included in planning, and capacity trends are reviewed weekly.
The core work during compute-constrained periods is to allocate limited resources to the most important requests while continuously calibrating the capacity model with data.
