LLM Inference and AI Infrastructure: How Serving Workloads Shape the Stack

    This article explains why inference, not training, defines the economics of large language model systems, and how that reality reshapes AI infrastructure. It contrasts inference and training workloads across persistence, latency constraints, memory composition, failure cost, and cost attribution, then breaks a single request into prefill, decode, KV cache usage, and scheduling overhead, with a sample capacity estimation model. It also outlines a five-layer infrastructure stack, four key optimization levers (batching with memory paging, cache reuse, elastic scaling with mixed workloads, and model routing), the metrics needed for observability and cost attribution, and a practical rollout path for teams building or operating LLM serving platforms.

    1. A Cost-Magnitude Problem: Why Inference Is the Main Battleground for Infrastructure

    A frequently cited magnitude relationship in LLM engineering is this: pretraining a general-purpose large model can require tens of millions of dollars in compute, while serving that model afterward can cost millions of dollars per day in inference. Placing these two numbers on the same timeline leads to a counterintuitive conclusion: training is a one-time capital expenditure, whereas inference is a recurring operational expense. Within a short period, inference accumulates to the same order of magnitude as the total training cost, and from then on it dominates the compute bill over the long term.

    The real value of these numbers is not the absolute figures but the structural fact they reveal: the economic model of a large model system is defined by inference, not by training. Training sets the upper bound of model capability; inference determines whether that capability can be delivered reliably, cheaply, and predictably. As a result, the design focus of AI infrastructure must shift from “how to train the model” to “how to keep serving the model well.”

    Note that the magnitudes above are only order-of-magnitude references. Model size, context length, concurrency distribution, and hardware conditions can all introduce significant variance. Engineering teams should model costs from their own load-testing data rather than applying external numbers directly.

    2. How Inference and Training Workloads Fundamentally Differ

    To understand why infrastructure is shaped in reverse by inference, start with how differently the two workload types look in terms of resource profiles.

    • Persistence vs. burstiness: Training is a long-running, schedulable batch job; inference is a 24/7 online service with clear daily traffic cycles and burst peaks.
    • Latency constraints: Training cares about throughput and convergence time; inference must constrain both time to first token and inter-token latency, with a latency budget typically in the range of hundreds of milliseconds to a few seconds.
    • Memory composition: Training must retain activations, gradients, and optimizer states; inference only needs weights and a growing key-value cache, so the sources of memory pressure are entirely different.
    • Cost of failure: An interrupted training run can resume from a checkpoint; a failed inference request shows up directly as an error perceived by end users.
    • Cost attribution: Training cost can be collected in a single lump; inference cost must be broken down by business, by caller, and by feature, or it cannot be governed.

    These differences mean that a resource pool optimized for training (high-bandwidth interconnects, centralized scheduling, tolerance for long-tail queuing) cannot be transplanted directly into inference scenarios.

    3. The Resource Ledger of a Single Inference Request

    Breaking inference cost down to request granularity is the prerequisite for capacity planning and cost optimization. A typical request breaks into four parts:

    1. Prefill phase: Parallel computation over the input prompt; compute-intensive and determines time to first token.
    2. Decode phase: Token-by-token autoregressive generation; memory-access-intensive and constrained by memory bandwidth, determining generation speed.
    3. Key-value cache usage: Grows linearly with context length and concurrency, and is the main variable in memory consumption.
    4. Queuing and scheduling overhead: Batch waiting, cross-node communication, serialization and deserialization.

    This yields a simplified model that is convenient for engineering estimation:

    1. # Illustrative capacity estimation; replace parameters with measured values
    2. def estimate_daily_cost(tokens_in, tokens_out, qps,
    3. gpu_mem_gb, kv_bytes_per_token,
    4. gpu_price_per_hour, target_batch):
    5. # Upper bound on concurrent sequences a single GPU can hold (rough)
    6. max_seq = int(gpu_mem_gb * (1 << 30) / kv_bytes_per_token)
    7. batch = min(target_batch, max_seq)
    8. # Time per batch is determined by measured throughput; this only expresses the dependency
    9. sec_per_batch = (tokens_in + tokens_out) / (batch * THROUGHPUT_PER_GPU)
    10. batches_per_day = 86400 * qps / batch
    11. gpu_hours = batches_per_day * sec_per_batch / 3600
    12. return gpu_hours * gpu_price_per_hour

    The value of this model is that it exposes the sensitive parameters: key-value cache bytes per token, effective throughput per GPU, and target batch size. Improving any one of the three affects the bill proportionally.

    4. The Capability Layers of AI Infrastructure

    The foundation supporting these workloads can usually be divided into five layers, each solving a different problem:

    • Compute layer: A general-purpose GPU resource pool with unified management of heterogeneous compute, paired with high-speed interconnects to meet distributed communication needs.
    • Scheduling layer: A container platform handling resource isolation and orchestration, supporting mixed deployment of batch jobs and online services with priority preemption.
    • Model serving layer: Responsible for batch scheduling, paged key-value cache management, and tensor and pipeline parallel partitioning.
    • Data and cache layer: Object storage holding model files and datasets; distributed cache holding hot prefixes and retrieval results.
    • Observability and governance layer: Log services, metrics monitoring and alerting, and distributed tracing together form a closed loop for observing latency and cost.

    In general cloud environments such as Baidu AI Cloud, these capabilities are typically offered as standard categories that enterprises can combine as needed, rather than building every component themselves.

    5. Four Key Optimization Levers

    Lever 1: Batching and memory paging. Static batching produces substantial padding waste when long and short sequences are mixed; continuous batching replaces a sequence with a new request the moment it finishes, and combined with paged cache management it can significantly raise effective throughput.

    Lever 2: Cache reuse. System prompts, long documents, and few-shot examples often repeat across large numbers of requests, and prefix caching can amortize that portion of prefill computation down to zero. On the business side, a semantic cache can reuse results directly for highly similar queries.

    Lever 3: Elastic scaling and mixed deployment. Trigger scale-out based on queue length and time to first token rather than utilization alone; scale online services down at night and give the resources to batch and evaluation jobs.

    Lever 4: Model tiering. Routing requests to models of different parameter sizes by difficulty, with simple intents going to small models and complex reasoning going to large models, is one of the most direct ways to cut cost.

    6. Observability and Cost Attribution

    Without attribution there is no governance. At minimum, collect three categories of metrics: latency (time to first token, inter-token interval, queue time), throughput (output tokens per second, effective batch size, cache hit rate), and cost (cost per token, amount allocated by caller). On top of that, build a unit-economics dashboard that treats “cost per thousand calls” as the core north-star metric, and configure threshold alerts to prevent abnormal traffic or excessively long contexts from blowing up the bill.

    7. A Practical Rollout Path

    1. Establish a baseline: load-test with real traffic distributions to obtain throughput and latency curves.
    2. Prioritize caching and prefix reuse, which typically offers the best return on investment.
    3. Introduce continuous batching and memory paging to raise effective per-GPU utilization.
    4. Build elastic scaling and priority queues to handle peak-to-trough differences.
    5. Complete cost attribution and quota mechanisms to close the governance loop.
    6. Build a capacity model and regress it regularly so estimates stay calibrated as the business evolves.

    Conclusion

    Inference is not an afterthought once training is done; it is the main engineering effort that determines whether large models can be delivered at scale. Break the cost ledger down to request granularity, divide infrastructure into clear capability layers, and then apply pressure lever by lever with batching, caching, elasticity, and model routing. Only then can intelligent services reach a sustainable balance within the triangle of latency, throughput, and cost.