Inference Service Architecture for Rapidly Growing Large Language Model Traffic
As LLM usage scales, request count is no longer sufficient for capacity planning. This article explains how to build a scalable inference service around token-based measurement, layered architecture, continuous batching, KV-cache reuse, tiered model routing, token-aware rate limiting, cost governance, observability, and realistic load testing. The goal is to maintain predictable latency, throughput, and cost as traffic grows.
1. The Unit of Measurement Has Changed: From Requests to Tokens
API load was traditionally measured by QPS. In LLM systems, however, token volume is the primary driver of resource consumption. A request containing ten thousand Chinese characters can require orders of magnitude more compute than one containing ten characters. Capacity planning should therefore focus on token throughput, measured in tokens per second, and total daily token volume, while QPS remains a secondary metric.
This shift has three direct consequences:
- Traffic is difficult to predict: The cost variance between requests can be extremely large. Average values are not sufficient; capacity should be modeled using P95 and P99 workloads.
- Cost grows with context length: Long contexts, multi-turn conversations, and code completion can significantly increase input-side processing costs.
- Traffic is concentrated: A small number of high-volume tenants may generate most of the traffic, making multi-tenant isolation essential.
2. Define the Metrics First: Six Core Measurements
Before optimizing the system, standardize the measurement definitions. Otherwise, optimization results cannot be validated consistently.
- TTFT (Time to First Token): Determines interactive responsiveness and is primarily affected by queueing and the prefill stage.
- TPOT (Time Per Output Token): Determines the smoothness of streaming generation.
- End-to-end latency: Calculated as
TTFT + TPOT × output length. - System throughput: The total number of tokens generated by the entire cluster per unit of time.
- Cache hit rate: The proportion of requests served through prefix-cache reuse, which directly affects effective compute utilization.
- Cost per token: Total cost divided by the number of useful tokens. This should distinguish useful output from tokens consumed by unnecessary retries.
3. Layered Architecture: Contain Complexity at Each Layer
A high-concurrency inference service typically consists of five layers:
- Ingress layer: Terminates TLS, authenticates requests, validates request-body size and context length, and rejects invalid requests as early as possible.
- Gateway and scheduling layer: Identifies tenants, enforces quotas and rate limits, routes requests to models, and handles retries and circuit breaking.
- Inference layer: Hosts model instance pools grouped by GPU memory and concurrency characteristics, allowing independent scaling.
- Caching layer: Provides prefix KV caching, semantic caching, and result caching. Cache hits are often the least expensive source of performance improvement.
- Observability layer: Includes logging, monitoring and alerting, distributed tracing, and token-based usage accounting.
Message queues and object storage can decouple these layers. Bursty traffic can first enter a queue for smoothing, while asynchronous workloads such as batch summarization and offline evaluation can be written to object storage and processed by consumers. This prevents long-running tasks from blocking synchronous request paths.
4. The Key to Throughput: Continuous Batching and Cache Reuse
Three general techniques are particularly important for inference throughput:
- Continuous batching: Instead of waiting for every request in a batch to finish, immediately release the slot when one sequence completes and add a new request. This can significantly improve GPU utilization.
- Chunked prefill: Split long-input prefill into smaller chunks and interleave it with decoding. This prevents a long request from blocking short requests and causing TTFT spikes.
- Paged KV-cache management: Allocate GPU memory in pages to reduce fragmentation. Prefix caches can be reused for identical system prompts and repeated code contexts.
In production, fixed prefixes should be designed explicitly. Place system prompts, tool definitions, and few-shot examples at the beginning of the prompt, and keep them stable whenever possible. This maximizes prefix-cache reuse.
5. Tiered Routing: Use Smaller Models for Frequent Short Requests
In many deployments, traffic growth is driven by short, high-concurrency tasks. Dividing models into three capability tiers—lightweight, standard, and flagship—and routing requests according to task complexity can substantially reduce the cost per request with little impact on user experience:
def route(task):# Determine complexity based on length, multi-step reasoning, and tool usageif task.input_tokens < 2048 and not task.needs_reasoning:return "light" # Lightweight model: classification, extraction, rewritingif task.needs_tools or task.input_tokens > 32768:return "flagship" # Flagship model: complex reasoning, long contextreturn "standard"
6. Stability: Token-Aware Rate Limits and Quotas
Request-count-based rate limiting is ineffective for LLM workloads. Requests must be weighted by their token requirements:
class TokenBucket:def __init__(self, tpm, burst_ratio=1.2):self.capacity = int(tpm * burst_ratio)self.tokens = self.capacityself.rate = tpm / 60.0 # Refill rate per seconddef try_acquire(self, need_tokens):self.refill()if need_tokens > self.capacity:return False # Reject oversized requests with a clear messageif self.tokens >= need_tokens:self.tokens -= need_tokensreturn Truereturn False
Supporting policies should include tenant-level quotas with global safeguards, priority queues that favor interactive requests over offline batch jobs, retry guidance in 429 responses, exponential backoff with jitter, and redundant instances across availability zones. Circuit breaking and graceful degradation should also be part of the design.
7. Cost Governance and Observability
Token accounting should be treated as a first-class capability. For every invocation, record the tenant, model tier, input and output token counts, cache-hit volume, and latency. Write detailed records to a logging service, send aggregated metrics to monitoring and alerting systems, and archive raw data in object storage for offline analysis.
These metrics help identify three major sources of waste:
- Excessively long contexts that provide little useful information
- Failed requests and repeated retries
- Requests that could have been handled by a lightweight model
On Baidu AI Cloud, this type of architecture can typically use a container platform to host inference instances, message queues to smooth traffic spikes, object storage and logging services for data retention, and monitoring and alerting services to support SLA management. These are general product categories that can be combined according to deployment requirements.
8. Capacity Planning and Load Testing
Load tests should reflect real traffic distributions rather than uniform random traffic:
- Replay traffic according to the token-length distribution observed in production, including the long tail.
- Apply load in steps and record where TTFT and TPOT begin to change sharply as concurrency increases. Use this to determine the safe operating level for a single instance.
- Validate how changes in cache hit rate amplify or reduce throughput.
- Conduct failure drills, including instance termination, dependency timeouts, and sudden tenfold traffic increases.
- Evaluate the system using both cost per token and P99 latency, rather than QPS alone.
9. Conclusion
Rapid growth in LLM traffic is not simply a scaling problem. It changes the measurement model, scheduling strategy, and cost structure at the same time.
Treating tokens as the primary unit of measurement, using a layered architecture to contain complexity, improving effective compute through continuous batching and cache reuse, and protecting both user experience and cost with tiered routing and token-aware rate limiting are the foundation of a scalable inference service. Combined with comprehensive observability, these practices help inference systems scale predictably while maintaining a more linear cost curve as demand increases.
