High-Concurrency LLM Inference Architecture: From Prototype to Production
This article breaks down the engineering practices required to scale large language model applications from internal testing to public, high-traffic services. It covers capacity planning based on token length distributions, scheduling with continuous batching and paged caching, multi-layer cache reuse, queue-driven autoscaling, cost governance, observability, and a phased rollout roadmap for building inference systems that meet P95/P99 latency targets under a fixed budget.
1. Background: From “It Runs” to “It Scales”
When an AI coding assistant or conversational application moves from internal testing to public availability, the most immediate change is not a longer feature list but the shape of the traffic curve: predictable, gradual growth gives way to spiky, pulsing demand with pronounced peaks and troughs. Milestones such as “one million users,” often highlighted in public announcements, mean something specific from an engineering standpoint: concurrent sessions, the distribution of context lengths, and the depth of tool-call chains all shift upward at the same time, while the compute cost of a single request is far higher than that of a traditional web API.
Conventional services scale with a simple formula: stateless plus horizontal replication. LLM inference does not fully satisfy that assumption, for three reasons:
- GPU memory is a hard constraint and cannot be oversubscribed for density the way CPU capacity can.
- A single request takes hundreds of milliseconds to several seconds, and long-tail requests occupy slots for extended periods.
- Context, in the form of the KV cache, carries state, so moving an instance arbitrarily loses the benefit of reuse.
The architectural goal therefore has to shift from “requests do not fail” to “meet P95/P99 latency targets under a given cost budget while retaining headroom for bursts.”
2. Capacity Planning: Quantify First, Scale Second
The core of capacity planning is translating business metrics into resource metrics. At minimum, define these inputs:
- Daily active sessions, requests per user, and peak concentration windows.
- Percentiles (P50/P90/P99) of input and output token lengths, not averages.
- Whether long context is enabled and whether multi-turn memory is on.
- The share of streamed responses, which directly determines how long connections are held.
A simplified estimation approach:
Required concurrent slots ≈ peak QPS × average request residency time (seconds)Required GPU memory ≈ resident weights + concurrent slots × per-sequence KV cache + activation and fragmentation headroom
Average token counts are nearly useless as a planning input; long-tail requests are the real threat to both memory and latency. In practice, apply tiered handling to oversized inputs: truncation, summarization-based compression, or routing to a dedicated long-context resource pool, so that a few requests cannot drag down an entire instance.
3. Scheduling: Batching and Queues Drive Throughput
Under a fixed memory budget, the most effective way to raise throughput is continuous batching: instead of waiting for every request in a batch to finish, sequences are swapped in and out at each decoding step, keeping the GPU highly utilized. The natural companion is paged cache management, which splits the KV cache into fixed-size blocks allocated on demand and keeps fragmentation waste low.
Design the scheduling strategy in layers:
Ingress: authentication, rate limiting, per-tenant quotasQueue: priority queues (interactive > offline batch)Execution: continuous batching + preemptive swapping, with degradation for long requests
Priority and preemption are both required. Rate limiting without tiering lets offline batch jobs inflate interactive latency several times over; tiering without preemption still leaves long requests holding slots indefinitely. Illustrative enqueue logic:
def enqueue(req):if req.kind == "interactive":priority = 0 if req.stream else 1else:priority = 3scheduler.push(priority, req)if scheduler.queue_size > HIGH_WATER:scheduler.preempt_longest() # Preempt the longest sequence to protect interactive latency
4. Cache Reuse: The Undervalued Cost Lever
Repeated computation often accounts for a substantial share of the cost structure in LLM serving. Reuse can be applied at three levels:
- Prefix caching: fixed prefixes such as system prompts, tool definitions, and coding conventions share the same KV blocks across requests; on a hit, the prefill stage can be skipped entirely.
- Semantic caching: build a vector index over frequent, similar questions and return historical results on a hit, combined with a similarity threshold and an invalidation policy to avoid stale answers.
- Result caching: deterministic tasks such as structured queries and document summarization can use a longer TTL.
The key implementation detail is that cache keys must include the model version, sampling parameters such as temperature, and a fingerprint of the relevant context. Otherwise a subtle failure appears: the parameters changed but the answer did not.
5. Elastic Scaling and Cost Governance
Autoscaling should not rely on CPU utilization alone; for model serving, the right signals are queue wait time and slot occupancy. A recommended scaling loop:
- Collect queue residency time, slot occupancy, and P95 latency.
- Trigger scale-out primarily on queue wait time, rather than acting only after latency has already degraded.
- Scale in with a cooldown window plus connection draining so streaming sessions are not interrupted.
- Keep a minimum number of resident replicas and warm-up traffic, because cold starts are slow.
For cost governance, route by request characteristics: short requests go to smaller models or a high-throughput configuration, while complex reasoning goes to a larger-model pool; run offline jobs in batches during off-peak hours; and put cache hit rate on the cost dashboard, since it usually improves per-request cost more than simply adding capacity.
6. Observability and Stability
Establish three categories of metrics: throughput (QPS, tokens/s), latency (time to first token, end-to-end P95/P99), and quality (truncation rate, tool-call failure rate, cache hit rate). Time to first token has the largest impact on the streaming experience and deserves its own threshold-based alerting.
For stability, deploy across multiple availability zones and run health checks at the gateway with automatic removal of unhealthy instances; enforce hard limits on context length and return explicit error codes when exceeded; and build a degradation path that switches to a smaller configuration or disables non-core enhancements when the primary pool is saturated, keeping basic conversation available. Load tests must replay real traffic distributions; a test set built from average lengths will barely surface fragmentation and long-tail problems.
7. Rollout Roadmap
Start by filling in measurement: build dashboards for token length distribution, time to first token, and slot occupancy. Next, introduce continuous batching and paged cache management, a step that typically yields a significant throughput gain on the same hardware. Then add prefix and semantic caching along with priority preemption. Finally, complete autoscaling and the degradation plan. If the whole system runs in the cloud, a container platform can host the stateless gateway, object storage can hold models and datasets, a message queue can buffer requests and smooth peaks, and logging plus monitoring and alerting close the loop, letting the team focus on scheduling and caching, the parts that genuinely determine cost and user experience.
