Inference System Design for Large Language Models: Deployment Architecture and Cost Optimization
Large language model (LLM) serving costs are determined not only by the model itself but largely by the inference system. This article discusses how to lower the cost per token while maximizing hardware utilization. It covers key deployment strategies such as separating prefill and decode phases, adapting to heterogeneous accelerators, reusing KV caches over long windows, and implementing cross-instance routing. It also dives into practical optimization techniques, including continuous batching, paged KV cache management, prefix caching, and speculative decoding. The goal is to move beyond "making models run" and toward "making models run at full capacity" with a clear focus on unit economics.
The capability boundary of a large language model is defined by the model itself, but the serving cost of a single token is often determined by the inference system. Public technical discussions commonly group two types of metrics: one is the daily throughput of a single cluster, representing scale; the other is the revenue or cost per GPU per hour, representing unit economics. Together, the real question is not “whether the model can answer,” but “whether the same hardware can serve more requests at a lower cost.” To achieve this, inference systems typically focus on three principles: supporting multiple types of accelerators, organizing hardware by stage, and reusing KV caches over longer windows. Each of these sounds like an architectural slogan, but in practice, each corresponds to specific cost-reduction paths and carries explicit trade-offs.
I. Clarify the Serving Boundary: Engine Is Not the Full Service
An offline inference engine typically only handles how a single request executes on one machine or one group of devices. A complete serving system, however, also requires a KV cache system, separated deployment of vision encoding, prefill, and decode phases, as well as load balancing across data-parallel replicas. The KV cache can be understood as the intermediate computation results left after the model processes context. The prefill phase consumes the input, while the decode phase generates output tokens sequentially. The longer the conversation history, the more likely reusing previously computed results can reduce the cost of new requests—but whether cache hits occur depends on the specific cache implementation, input fingerprinting, and consistency policies.
Therefore, when looking at a full architecture diagram that includes request routing, computation, and cache transfer, the first thing to recognize is the service boundary: it explains why a coordination layer outside the engine is necessary, but it does not prove that all modules are delivered with a given offline engine, nor does it demonstrate that your own cluster has the same capacity. There is also a common confusion between two types of load balancing: one is expert-parallel load balancing inside the engine, which aims to keep all participating devices evenly utilized; the other is at the service entry point, which decides which instance receives a request. The presence of expert-parallel load balancing in an engine does not mean it has full cross-instance routing capabilities.
II. Deployment Approach: Stage-Based Hardware Organization and Heterogeneous Adaptation
1. Prefill and Decode Separation
The prefill phase is compute-intensive: long inputs require large matrix operations, making them well-suited for high-compute nodes, and batch sizes can be relatively aggressive. The decode phase generates tokens one by one and is more sensitive to memory access and latency, with frequent KV reads. It benefits from large high-bandwidth memory and low-latency networks across large-scale supernodes. Deploying these two phases separately allows each to scale and be selected independently, improving overall utilization. The trade-off is that intermediate states and KV data must be transferred across nodes, increasing scheduling complexity, expanding the failure domain, and making resource fragmentation more likely. In practice, this requires establishing stage queues, capacity watermarks, transfer compression, timeout retries, and degradation strategies.
2. Heterogeneous Accelerator Adaptation
Supporting accelerators from multiple vendors cannot stop at “it runs.” Unified operator abstraction, numerical precision consistency, communication topology awareness, and failure fallback strategies all need to be covered. It is also essential to validate whether the hardware can be fully utilized: whether operator coverage is complete, whether fusion is sufficient, whether communication can overlap with computation, whether batch scheduling is efficient, and whether memory management is stable. Otherwise, migrating requests to another type of hardware may not actually reduce unit cost.
3. Long-Window KV Cache Reuse
Extending the cache retention window to multiple days can eliminate repeated prefill work, which is especially valuable for system prompts, long-document Q&A, and multi-turn conversations. But this is not a free lunch: a tiered cache spanning high-bandwidth memory, main memory, local flash, and object storage introduces storage costs, invalidation governance, tenant isolation, privacy compliance, and cache poisoning concerns. It requires designing prefix fingerprints, TTLs, eviction policies, hit-rate monitoring, and fallback paths.
4. Cross-Instance Routing
Entry-point routing cannot rely solely on instance load; it must also consider prefix affinity, estimated compute cost, queue length, and network distance. Session stickiness, backpressure, canary releases, and retry budgets must all be included. A simplified pseudocode example:
def route(req):cands = healthy_instances()best = Nonefor inst in cands:if inst.free_capacity() < req.estimate_cost():continueprefix = prefix_match(req.context_fingerprint, inst.cache)score = 0.5 * prefix+ 0.3 * (1 - inst.load)+ 0.2 * inst.network_score- 0.4 * inst.queue_lenif best is None or score > best.score:best = (score, inst)return best.inst if best else fallback_queue(req)
A configuration example should also separate stages, cache, and routing:
service:stages:prefill: {pool: compute_optimized, autoscale: true}decode: {pool: memory_optimized, autoscale: true}cache:prefix_reuse: truettl: multi_daytiers: [high_bandwidth_mem, main_mem, local_flash, object_storage]routing:policy: prefix_affinity_then_loadsticky: truebackpressure: true
III. Optimization Techniques: From “Runs” to “Runs at Full Capacity”
Performance optimization typically includes the following elements:
- Continuous batching and dynamic batching: grouping requests based on token budgets and memory budgets.
- Paged KV cache memory management: reducing fragmentation and enabling prefix sharing.
- Prefix caching: reusing system prompts, long documents, and multi-turn histories.
- Speculative decoding or parallel decoding: but the benefits must be validated against accuracy and draft generation costs.
- Quantization and operator fusion: paired with precision regression and outlier handling.
- Communication overlap and parallel strategies: arranging tensor parallelism, pipeline parallelism, and expert parallelism based on the topology.
- SLO tiering and elastic scaling: separating short and long requests to prevent mutual interference.
The pursuit of peak performance should not focus only on throughput. At the resource layer, track GPU utilization, memory watermarks, and network usage. At the engine layer, track throughput, cache hit rates, and batch sizes. At the service layer, track time-to-first-token, time-per-token, P99 latency, and error rates. At the economic layer, track cost per million tokens, which is the sum of compute, storage, network, idle time, and operations. When separating deployment phases, calculate the balance between transfer costs and utilization gains. When extending cache windows, calculate the balance between storage costs and prefill savings. When adapting to heterogeneous hardware, calculate the balance between migration costs and supply flexibility.
IV. Replication Checklist and Implementation Recommendations
To replicate such a system, it is advisable to proceed step by step: first, get the offline engine working with entry-point routing and cache affinity; then validate prefill/decode separation; then introduce long-window caching; and finally handle heterogeneous adaptation. Each step should have rollback plans and load-testing criteria in place. The checklist includes:
- The service boundary is clearly defined.
- The two types of load balancing are designed separately.
- Cache hits and invalidations are observable.
- Numerical precision is consistent across heterogeneous hardware.
- The cost model covers idle resources and operations.
- Failure recovery can rebuild the cache.
When deploying on Baidu AI Cloud, container platforms can support inference services, object storage can hold cold caches, and logging and monitoring systems can collect metrics. These are general-purpose capabilities; specific selections should still be evaluated based on SLAs, compliance, and cost. Ultimately, optimizing an inference system is not about stacking single-point technologies but about continuously approaching a lower unit token cost under SLO constraints.
