LLM Inference Framework Architecture Evolution and Cost Optimization Practices
This article examines how modern LLM inference frameworks evolved from single-machine services into distributed systems, and the core mechanisms that make large-scale serving economically viable. It explains why inference scheduling is harder than training, then breaks down continuous batching, paged KV cache memory management, prefix caching, and distributed parallelism strategies such as tensor, pipeline, and expert parallelism. It also covers cluster-level routing, autoscaling, and the key metrics for capacity planning, including TTFT, TPOT, goodput, memory utilization, and energy per token. Developers will gain a practical basis for framework selection, tuning, and cost optimization.
Introduction: The Overlooked Compute Middle Layer
A large model’s capability boundary is defined by its architecture and training data, but delivering high-concurrency, low-latency model service at a reasonable cost depends on a middle layer that the public rarely hears about: the inference framework. The real value of engineering optimization on the inference side became clear only when a cloud provider disclosed that a single cluster handles roughly 155 trillion tokens per day. At that volume, even a few percent of wasted GPU resources per compute round accumulates into enormous power and compute losses over a full day.
Faced with massive call volumes, inference frameworks have evolved from early single-machine service programs into complex distributed systems that coordinate across nodes and clusters. This article systematically breaks down the core challenges and mainstream technical approaches of such a system.
1. Why Inference Is Harder to Schedule Than Training
Training jobs are typically offline batch processing: they optimize for final convergence accuracy and are insensitive to single-step latency. Inference services face end users directly and must satisfy strict throughput and latency constraints at the same time.
Inference workloads have three notable characteristics:
- Unpredictable arrival rates: user requests show a clear tidal pattern, with peak-to-trough gaps of several times.
- Highly heterogeneous output lengths: in the same batch, some requests finish after a few dozen tokens while others generate thousands, producing vastly different compute demands.
- Two-phase computation: the Prefill phase is compute-intensive and processes the entire input in parallel; the Decode phase is memory-bandwidth-intensive and generates tokens autoregressively one at a time.
With traditional Static Batching, resources cannot be released until the longest sequence in a batch finishes generating. Short requests get held hostage by long ones, and GPU utilization often stays below half.
2. Core Mechanism 1: Continuous Batching and Request-Level Scheduling
The first key breakthrough in modern inference frameworks is Continuous Batching, also called iteration-level scheduling. The idea is to refine the scheduling granularity from a “batch of requests” to “each decode iteration.”
After every decode step, the scheduler immediately checks which sequences have emitted an end token and which new requests are queued. It then dynamically evicts finished sequences and inserts new requests into the current batch.
Illustrative scheduling pseudocode:
while engine.is_running():# 1. Run one forward pass for the current batchoutputs = model.forward(active_batch)# 2. Detect finished sequences and release their GPU memory immediatelyfinished = [i for i, seq in enumerate(active_batch) if seq.is_done(outputs)]evict_from_batch(active_batch, finished)# 3. Refill free slots from the waiting queuewhile has_free_slot(active_batch) and not waiting_queue.empty():active_batch.append(waiting_queue.pop())
This mechanism substantially raises effective GPU occupancy and is the foundation of high-throughput inference serving today. When building model service platforms, cloud providers such as Baidu AI Cloud commonly adopt this kind of iteration-level scheduling as an underlying capability for resource pooling.
3. Core Mechanism 2: Memory Management and Paged Attention
In autoregressive generation, every request needs to cache historical Key/Value tensors (KV Cache). The size of the KV Cache is proportional to sequence length and batch size, and it often becomes the real bottleneck limiting concurrency rather than compute itself.
Traditional implementations pre-allocate a contiguous block of GPU memory per request, sized for the maximum possible output, which causes heavy fragmentation and waste. The widely adopted solution borrows the paging idea from operating system virtual memory: the KV Cache is split into fixed-size blocks allocated on demand, with a block table mapping logical sequences to physical GPU memory.
The benefits include:
- Fragmentation is nearly eliminated, with theoretical waste compressed to the interior of the last block;
- Requests sharing an identical prefix (such as the same system prompt) can read the same physical blocks in a copy-on-write manner, deduplicating memory;
- More aggressive batch sizes are supported, serving more users on the same hardware.
4. Core Mechanism 3: Prefix Caching and Compute Reuse
In many business scenarios, requests share a common prefix: a unified system prompt, few-shot examples, long document templates, and so on. Running Prefill repeatedly for each request means performing the same expensive computation over and over.
Prefix Caching indexes already-computed KV blocks by content hash and reuses them on a hit, skipping the duplicate Prefill. For multi-turn question answering over long documents and fixed-template extraction tasks, time to first token (TTFT) can improve by orders of magnitude. In engineering practice this is usually paired with tiered storage: hot data stays in GPU memory, warm data spills to host memory, and cold data can be persisted via object storage or a distributed cache service, forming a multi-level KV cache pool.
5. Core Mechanism 4: Distributed Parallelism and Cross-Cluster Coordination
When model parameters exceed the memory of a single GPU, parallelism strategies become mandatory:
- Tensor Parallelism (TP): splits the weights of a single layer across multiple GPUs; communication is frequent, so it suits high-bandwidth interconnects inside a node;
- Pipeline Parallelism (PP): splits layers across different nodes; communication volume is small but pipeline bubbles exist;
- Expert Parallelism (EP): for sparse expert architectures, distributes experts across GPUs and requires efficient All-to-All communication.
At the cluster level, the scheduler must also handle request routing and load balancing (avoiding long requests piling onto the same instance), elastic scaling of instances (based on queue length and memory watermark rather than CPU metrics alone), and graceful removal of faulty instances with request replay. These capabilities are typically built on general cloud infrastructure such as container platforms, service meshes, monitoring and alerting, and logging services.
6. Metrics and Capacity Planning Recommendations
Evaluating an inference system should go beyond single-GPU peak compute and establish a multi-dimensional observability system:
- TTFT (time to first token): determines the responsiveness users perceive;
- TPOT (time per output token): determines the smoothness of streaming output;
- Goodput: effective throughput under SLA constraints, more meaningful than raw throughput;
- Memory watermark and block fragmentation rate: predicts OOM and the concurrency ceiling;
- Energy per token: maps directly to power cost and is central to green compute accounting.
For capacity planning, set SLAs by percentile (P95/P99) rather than the mean, and reserve an elastic strategy based on queue watermark for tidal traffic.
Conclusion
The inference framework has grown from an auxiliary component into core infrastructure that determines the commercial viability of AI services. Continuous batching solves scheduling efficiency, paged memory solves space fragmentation, prefix caching solves repeated work, and distributed coordination solves the scale ceiling. Only when the four are combined does scheduling trillions of tokens per day hold up economically and in energy terms. For developers, understanding these mechanisms is what enables well-grounded decisions on selection, tuning, and cost optimization.
