Architecture Design and Cost Optimization Practices for Large-Scale LLM Inference Systems

    This article presents a systematic framework for designing and optimizing large-scale LLM inference systems. It covers how to define meaningful efficiency metrics beyond raw token throughput, why separating prefill and decoding stages enables independent resource optimization, how to choose parallelism strategies based on model structure and communication topology, how to design tiered KV cache systems around reuse value rather than retention time, how scheduling should target stable delivery instead of maximal batch size, and how to validate architectural changes through reproducible experiments and full-scope cost accounting. The goal is to help engineering teams serve more effective requests with fewer total resources under clear latency, quality, and reliability targets.

    Architecture Design and Cost Optimization Practices for Large-Scale LLM Inference Systems

    The model determines the upper bound of response quality; the inference system determines whether that quality can be delivered continuously at acceptable cost, latency, and stability.

    For large-scale online services, peak speed measured in a single offline test does not directly translate into production efficiency. Request lengths keep changing, popular prefixes recur, and different computation stages demand different hardware resources. If every request is processed with the same deployment strategy, even high-spec hardware can suffer from idle compute, memory pressure, communication congestion, and long-tail latency all at once.

    Therefore, evaluating an inference framework requires more than asking “how many tokens per second can it generate.” We should further ask: how many of those tokens involved actual computation? Do requests meet latency constraints? Are cache and storage consumption counted? How much effective throughput survives failures and traffic fluctuations?

    This article does not endorse the performance of any specific implementation. Instead, it builds an analysis framework—from architecture to economics—around the common challenges of large-scale cloud inference.

    1. Align the Metrics First: Service Scale Is Not Computational Efficiency

    1.1 Distinguish Input, Output, and Cache-Hit Tokens

    An online inference service typically handles three types of tokens:

    • Input tokens: the user prompt, conversation history, and retrieved content.
    • Output tokens: content actually generated by the model through autoregressive decoding.
    • Cache-hit tokens: portions of the input whose intermediate states can be reused without full recomputation.

    These three types consume resources differently. Input processing usually offers high parallelism; output generation is sequentially dependent; cache hits mainly consume indexing, reading, transfer, and state-restoration resources.

    Adding them together into a single “served token throughput” figure therefore does not represent the device’s model computation speed. In long-prefix, high-reuse scenarios, service scale can significantly exceed what full recomputation capacity would allow.

    This does not make service throughput worthless—it answers “how much business did the system absorb,” not “how much new computation did the hardware perform.”

    1.2 Performance Metrics Must Carry Constraints

    A meaningful throughput result should at least specify:

    • Input and output length distributions;
    • Request arrival pattern and concurrency level;
    • The definition of cache hit rate;
    • Model precision and runtime configuration;
    • Time-to-first-token (TTFT), inter-token latency (ITL), and their percentiles;
    • The set of devices participating in computation;
    • Whether cache nodes, networking, and storage costs are included.

    TTFT reflects how long a user waits for the first result; ITL reflects the smoothness of generation. Averages alone are insufficient—for interactive workloads, high-percentile latency often better represents the risk users actually experience.

    1.3 Revenue, Cost, and Profit Must Be Calculated Separately

    Device-hour revenue is not device-hour profit. Even with accurate revenue accounting, depreciation, energy, networking, storage, operations, and redundant capacity cannot be ignored.

    Metrics better suited to engineering decisions include:

    Cost per successful request = total cost over the period ÷ number of successful requests

    Cost per effective output = total cost over the period ÷ number of output tokens meeting service requirements

    “Successful” must mean more than “no error returned”—it should include meeting latency targets and producing complete results. Otherwise, trading unbounded queuing for high throughput can produce impressive but business-meaningless numbers.

    2. Organize Resources by Computation Stage, Not by Making Every Device Do Everything

    2.1 Prefill and Decoding Have Different Bottlenecks

    LLM inference can be divided into two main stages: prefill and decoding.

    The prefill stage processes the prompt sequence in one pass. With suitable batch and length conditions, it forms large matrix operations and tends to utilize compute units well.

    The decoding stage repeatedly reads model parameters and existing attention states. Its bottleneck may come from memory bandwidth, cache capacity, or cross-device communication, and it is also affected by batch size and model architecture—it cannot be reduced to a single resource shortage.

    This means the same hardware configuration may not suit both stages equally.

    2.2 The Value of Disaggregation Lies in Independent Optimization

    Deploying the two stages as separate resource pools allows independent tuning of:

    • Batch size;
    • Parallelism strategy;
    • Device count and topology;
    • Request queuing policy;
    • Cache capacity and reserved space.

    The prefill pool can prioritize batch compute efficiency, while the decoding pool focuses on sustained output, state capacity, and load stability.

    If the service also involves image or audio input encoding, it may be worth evaluating whether to deploy encoding separately. But only when load scale and resource differences are large enough can such splitting outweigh the extra scheduling and data-transfer costs.

    2.3 Disaggregation Is Not an Unconditional Win

    After stage separation, the attention cache produced by prefill must be handed to decoding nodes. The larger the state, the higher the cost of network transfer and memory allocation on the receiving end.

    The benefit holds only under a basic condition:

    Gains from improved resource utilization must exceed losses from state handoff, queuing, and added system complexity.

    For short requests, low concurrency, or clusters with limited network capacity, colocated deployment may be simpler and more economical. For long inputs, high concurrency, and clearly distinct compute characteristics, disaggregation is worth validating.

    The sensible approach is therefore not a wholesale switch, but routing by request length, business priority, and cache-hit profile.

    3. Parallelism Strategy Should Be Determined by Model Structure and Communication Topology Together

    3.1 Different Parallelism Modes Address Different Constraints

    Common parallelism modes include:

    • Data parallelism: serving more requests through multiple replicas.
    • Tensor parallelism: splitting per-layer computation across devices to overcome single-device capacity or compute limits.
    • Pipeline parallelism: placing different network layers on different devices.
    • Expert parallelism: distributing different experts across devices for mixture-of-experts (MoE) architectures.
    • Context parallelism: sharing the compute and state pressure of long sequences.

    None of these has a universally valid priority. The choice must jointly consider model size, activation size, interconnect bandwidth, communication latency, and business latency targets.

    3.2 Expert Parallelism Expands Capacity but Amplifies Tail Risk

    In MoE architectures, different tokens are routed to different experts. Wider expert parallelism helps distribute expert parameters, but it also introduces cross-device data exchange.

    If certain experts persistently receive more tokens, the corresponding devices become bottlenecks. Since a computation step typically waits for the slowest participant, a lower average load does not necessarily mean lower overall latency.

    Key metrics to monitor:

    • Number of tokens received per expert;
    • Ratio of the busiest device’s load to the average;
    • Distribution of expert computation time;
    • Dispatch and aggregation time;
    • Impact of communication congestion on tail latency.

    The goal of load balancing is not merely “making averages look better,” but shortening the slowest link on the critical path.

    3.3 Replicating Hot Experts Requires Evaluating the Overhead

    Replicating hot experts and adjusting routing can relieve skew in some scenarios, but it increases parameter memory footprint and introduces placement, migration, and routing-consistency issues.

    Although parameters rarely change during inference, replica loading and switching can still disrupt online service. A safer strategy combines historical statistics with real-time signals and applies cooldown periods, preventing the system from chasing short-term noise with repeated migrations.

    4. Tiered Caching Is About Reuse Value, Not Retention Duration

    4.1 Why Multi-Level Storage Is Needed

    The attention key-value (KV) cache avoids recomputing existing prefixes, but its size grows with sequence length, concurrency, and model configuration.

    A common tiered design:

    • Device high-bandwidth memory: states urgently needed by ongoing generation;
    • Host memory: states likely to be reused soon;
    • Shared storage: larger volumes of less frequently accessed reusable states.

    The closer to the compute device, the faster the access—and the higher the per-unit capacity cost. The purpose of tiered caching is to reserve limited high-speed space for the most valuable data.

    4.2 A Cache Hit Is More Than “Found It”

    A complete cache-reuse process includes index lookup, data reading, network transfer, device memory allocation, and execution-state restoration.

    At minimum, distinguish:

    • Request hit rate: what fraction of requests reused cache;
    • Token hit rate: what fraction of input tokens were reused;
    • Effective hit rate: the fraction of reuses that actually reduced end-to-end latency or cost.

    Even if a short prefix is found in remote storage, reading it may be slower than recomputing. A “hit” does not equal a “benefit.”

    A more rational decision condition is:

    Cache read and restoration cost < recomputation cost of the corresponding prefix.

    This judgment also shifts with network congestion, compute queue length, and storage load.

    4.3 Longer Retention Does Not Necessarily Save More Money

    Keeping cold data long-term continuously occupies storage and adds indexing, cleanup, and access-control costs. Retention policy should weigh reuse probability, recomputation cost, read cost, and occupied space together.

    For example, long and stable shared prefixes may deserve longer retention; inputs full of random, rarely repeated content should not occupy expensive cache tiers.

    Cache keys must also include every condition that affects results—model version, tokenization rules, and relevant configuration. Otherwise, identical text may incorrectly reuse incompatible states.

    For multi-tenant services, cache isolation, sharing authorization, and deletion mechanisms must be explicit. Data boundaries must never be bypassed for the sake of hit rate.

    4.4 Do Not Assume All States Can Be Restored by Short-Range Replay

    Local attention, global attention, and other state structures depend on history differently.

    Some local states may depend only on a limited window, but a full model may still have cross-layer propagation or global dependencies. Therefore, “replaying only the last short segment of input precisely restores all states” is not a universal conclusion.

    When designing a state-reconstruction scheme, specify separately:

    • Which states can be read directly;
    • Which states require recomputation;
    • What historical inputs or checkpoints the recomputation needs;
    • Whether the restored result is equivalent to full computation;
    • If an approximation is used, how its error is evaluated.

    Specific window lengths, cache byte counts, and replay ranges must be measured against the actual model architecture—not borrowed from other implementations.

    5. Scheduling Aims at Stable Delivery, Not Infinitely Larger Batches

    5.1 Input Chunking Should Be Budget-Driven

    Executing a long input in one shot can occupy a device for a long time and starve other requests. Chunked prefill balances compute efficiency against fairness across requests.

    Rather than a fixed token count, a more robust approach selects chunk size based on a time budget. The scheduler estimates the next chunk’s execution time using current sequence length, batch composition, cache state, and recently measured durations.

    This requires continuous calibration, because the same token count can cost noticeably different time under different context lengths and load conditions.

    5.2 Decoding Scheduling Must Manage Compute and State Together

    The pressure from decoding requests comes not only from the number of active sequences, but also from context length and state occupancy.

    Two batches with the same request count can exert very different memory and attention-compute pressure if one contains more long-context requests. The scheduler should therefore consider:

    • Number of active requests;
    • Context length distribution;
    • Available cache capacity;
    • Estimated computation and communication time;
    • Request priority and latency budget.

    For expert-based architectures, routing skew also needs attention. Blindly maximizing batch size may raise local throughput while worsening overall tail latency.

    5.3 Cancellation and Backpressure Belong in Core Design

    If a request keeps consuming generation resources after the user disconnects, the computation yields no business value.

    The system should promptly propagate cancellation signals, reclaim state, and enforce queue limits. When traffic exceeds capacity, risk should be controlled through rate limiting, tiered service, or acceptable degradation—rather than letting queues grow without bound.

    6. Heterogeneous Hardware Support Should Proceed in Layers

    Supporting different compute devices is more than getting the model to launch—it involves adapting operators, numerical behavior, memory management, communication primitives, and scheduling parameters.

    A sensible layered approach:

    • Upper layer: unified request semantics, cache management, and scheduling interfaces;
    • Middle layer: abstraction of execution plans and resource management;
    • Bottom layer: hardware-specific operator and communication-path optimization.

    Note carefully: a unified interface does not mean different devices can efficiently join the same fine-grained parallel computation. Differences in interconnect capability, execution rhythm, and numerical implementation can all limit mixed deployment.

    In practice, start with independent resource pools per device type, schedule them uniformly at the service layer, and then evaluate tighter cooperation based on measurements.

    7. Use Reproducible Experiments to Decide Whether an Architecture Deserves Production

    The recommended validation sequence:

    Step 1: Establish baselines. Measure throughput, latency, and memory usage across input lengths, output lengths, and batch sizes to identify the dominant bottleneck.

    Step 2: Validate cache benefits. Compare configurations with caching disabled, local-only caching, and shared caching, recording both cold-start and steady-state phases.

    Step 3: Validate stage disaggregation. Keeping model and request distribution constant, compare colocated versus disaggregated deployment, separately accounting for state-transfer and queuing overhead.

    Step 4: Introduce dynamic traffic. Cover bursts, hotspot shifts, mixed long/short requests, and different priority classes—avoid drawing conclusions under stable load only.

    Step 5: Run failure drills. Inject compute-node exits, cache-service unavailability, and network slowdowns, and observe whether concentrated recomputation and cascading congestion occur.

    Step 6: Account for cost across the full resource scope. Beyond compute devices, include host memory, shared storage, networking, spare capacity, and necessary operational expenses.

    Comparisons are only decision-relevant under identical service targets. If a scheme delivers higher throughput but requires longer waiting times or more peripheral resources, it cannot be declared more economical outright.

    Conclusion

    Optimizing a large-scale inference system is fundamentally the co-design of computation, state, communication, and scheduling.

    Stage-disaggregated deployment resolves mismatched resource demands; well-chosen parallelism fits the model to the hardware; tiered caching reduces redundant computation; and dynamic scheduling turns these capabilities into stable online service. Yet every optimization introduces new costs, constraints, and failure modes.

    What is truly worth pursuing is not peak numbers detached from business conditions, but serving more effective requests with fewer total resources under explicit latency, quality, and reliability targets. Continuous measurement, validation, and iteration around that goal is the reliable path to cost efficiency in inference systems.