Why LLM Inference Determines the Success or Failure of AI Infrastructure
Training a large language model is a one-time cost, but inference is a continuous expense that typically accounts for 70%–90% of a model's total lifecycle cost. This article explains why inference infrastructure is the decisive factor in AI system success: how to estimate per-token costs, how latency (TTFT and TPOT) affects user experience, how inference goals differ from training, a five-layer view of inference infrastructure, key optimization techniques such as continuous batching, quantization, KV caching, speculative decoding and model routing, capacity planning formulas, observability metrics, and practical deployment recommendations for balancing cost, latency, and stability.
1. After Training, the Real Costs Begin
Many teams treat the end of training as the milestone of an LLM project. Once model metrics hit their targets, resource investment seems to wind down. From a production perspective, however, this is exactly where the cost curve starts.
Training consumes resources once. No matter how large the model or the dataset, that expense is fixed once the training job finishes. Inference is different. As long as the service is online, every request and every generated token occupies GPU compute and memory, accruing real-time charges.
Statistics from the reference material show that over a one-year lifecycle of a large model, inference accounts for roughly 70%–90% of total cost, while training accounts for 10%–30%. This ratio makes clear that inference actually determines the bulk of total cost of ownership.
To judge whether inference costs are under control, break the cost down to the unit-token level. A common estimation approach:
Cost per token = GPU cost per hour ÷ effective output tokens per GPU hour
Effective throughput is influenced by batching strategy, sequence length, and memory footprint, so the same hardware can see unit costs vary severalfold under different loads. The following function provides a quick estimate:
def cost_per_million_tokens(gpu_hour_cost: float,tokens_per_second: float,utilization: float = 0.6) -> float:"""Estimate inference cost per million tokens.gpu_hour_cost: cost per GPU per hour (in CNY)tokens_per_second: per-GPU throughput at full load (tokens/second)utilization: average actual utilization, between 0 and 1"""effective_tps = tokens_per_second * utilizationtokens_per_hour = effective_tps * 3600return gpu_hour_cost / tokens_per_hour * 1_000_000# Example: assume 10 CNY per GPU-hour, 3000 tokens/s at full load, 60% average utilization# All inputs are hypothetical values, not actual pricingprint(round(cost_per_million_tokens(10, 3000, 0.6), 2)) # ~1.54 CNY
Utilization is the most direct cost lever. Under the assumptions above, raising utilization from 60% to 80% cuts unit cost by roughly 25%. This shows that scheduling and batching capability often matters more to cost than simply swapping hardware.
2. Latency Directly Shapes User Experience
Inference latency is the first metric users perceive. Two commonly used metrics should be distinguished:
- Time to First Token (TTFT): the time from request arrival to the first output token. It determines how quickly users feel the model has “started responding.”
- Time per Output Token (TPOT): the average time per token during generation. It determines whether streaming output feels smooth.
According to business data in the reference material, when latency of an e-commerce customer-service bot exceeded 300 ms during peak hours, consultation conversion rates dropped by about 20%; when on-device conversational responses took longer than 1 second, user retention declined noticeably, with a figure of around 50% cited in the reference. These numbers come from specific scenarios; sensitivity varies widely across businesses, so always rely on your own user behavior data.
End-to-end latency of a request typically consists of:
- Network transfer: round-trip time between client and server.
- Queuing: time spent waiting in the scheduling queue for compute resources.
- Prefill computation: the phase where the model processes the entire input before producing the first token.
- Decoding: token-by-token output, with duration proportional to output length.
- Post-processing: format conversion, content moderation, and other附加 steps.
Queuing is the most likely to spiral out of control during peak hours, amplifying a few hundred milliseconds of computation into multi-second waits. Optimizing inference latency therefore requires examining the entire path—queuing, network, and post-processing—not just the model’s forward pass.
3. How Inference Goals Differ from Training
The core goal of training is to push accuracy to its ceiling. Training a model with hundreds of billions of parameters may occupy thousands of GPUs continuously for weeks. Data processing can be done offline, and low efficiency in a single job is acceptable—once the final model meets its targets, the result can be reused across all subsequent inference.
Inference has entirely different goals: it must balance latency, cost, and stability. The specific differences:
| Dimension | Training | Inference |
|---|---|---|
| Core goal | Maximize accuracy | Balance latency, cost, and stability |
| Resource pattern | Centralized, long-duration occupation | Distributed, fluctuates with traffic |
| Request shape | Offline batch data | Online, concurrent, unpredictable requests |
| Time constraint | Days to weeks acceptable | Typically milliseconds to seconds |
| Cost of failure | Just rerun the job | Users directly perceive the failure |
Based on these differences, inference typically faces three categories of challenges.
Dynamic load. Traffic peaks and troughs vary significantly across businesses. Per the reference material, education-related models see evening request volumes around 3x daytime levels on weekdays, while e-commerce models can hit 10x normal traffic during major sales events. Provisioning resources permanently for peak load leaves utilization low most of the time; provisioning for the average causes heavy queuing and timeouts at peak.
Latency sensitivity. Inference services must return results within a bounded time. Average latency tends to hide problems; tail latency (such as the P99 percentile) better reflects real user experience. Even a small fraction of timed-out requests can damage overall reputation.
Cost and stability. Inference is a continuously running system that must reduce unit cost while maintaining availability. Hardware failures, out-of-memory errors, and overly long inputs can all cause service instability. Pushing too aggressively for low cost usually exacts a price in stability.
4. A Layered View of Inference Infrastructure
Inference infrastructure can be divided into five layers by responsibility. Each layer solves different problems, and a weakness in any one of them drags down overall performance.
- Compute resource layer: manages pools of GPUs and other accelerators, handling memory allocation, device health checks, and multi-instance isolation.
- Scheduling and batching layer: merges concurrent requests into batches for execution, deciding queue order and routing targets.
- Model optimization layer: reduces per-inference compute and memory overhead through quantization, KV cache reuse, speculative decoding, and model distillation.
- Service governance layer: provides gateway, rate limiting, circuit breaking, degradation, and canary release capabilities to protect backend services under overload.
- Observability and metering layer: collects latency, throughput, error rates, and resource utilization, and allocates costs by business, tenant, or feature.
These layers are not built in isolation. For example, throughput gains from model optimization only translate into real benefits if the scheduling layer can consistently feed enough requests.
5. Key Optimization Techniques and Trade-offs
5.1 Dynamic Batching
GPUs run at low utilization with small batches. Merging multiple requests for execution significantly improves throughput. Continuous batching allows new requests to join a batch as soon as existing sequences finish, without waiting for the whole batch to complete. The trade-off is that batch composition changes constantly, so a maximum wait time must be set to prevent individual requests from stalling.
The simplified scheduling example below illustrates the relationship between the two trigger conditions—batch size and wait timeout—but it does not handle concurrency safety or step-by-step decoding, so it cannot be used directly in production.
import timefrom collections import dequeclass DynamicBatcher:"""Dynamic batching scheduling sketch: form a batch when the queue reachesthe batch size, or the oldest request has waited past the timeout."""def __init__(self, max_batch_size: int = 8, max_wait_ms: float = 20.0):self.max_batch_size = max_batch_sizeself.max_wait_ms = max_wait_msself.queue = deque() # elements are (arrival_time, request)def submit(self, request):self.queue.append((time.monotonic(), request))def next_batch(self):if not self.queue:return []oldest_arrival, _ = self.queue[0]waited_ms = (time.monotonic() - oldest_arrival) * 1000if len(self.queue) >= self.max_batch_size or waited_ms >= self.max_wait_ms:batch = []while self.queue and len(batch) < self.max_batch_size:_, req = self.queue.popleft()batch.append(req)return batchreturn []
max_wait_ms is the core parameter. Increasing it makes batches fill up more easily, improving throughput; but under low load, first-token latency for individual requests rises. Teams need to weigh the two against their own SLOs.
5.2 Quantization
Quantization converts model weights and activations from high-precision representations to lower-precision ones, such as from FP16 to INT8 or INT4. It reduces memory footprint and memory bandwidth pressure, allowing larger batches or fewer accelerators.
Accuracy loss varies by task. Text classification and information extraction are usually robust, while mathematical reasoning and long-form generation are more precision-sensitive. Before rolling out a quantization scheme, compare output quality on your own business evaluation set—do not rely solely on general benchmarks.
5.3 KV Cache
In autoregressive generation, each new token attends to all previous tokens. The KV cache stores the key-value vectors of past tokens, avoiding redundant computation at each step and significantly reducing decoding cost.
The cost is that memory usage grows with context length and concurrency. Long contexts plus high concurrency can easily exhaust memory before compute. Common management approaches include allocating memory in fixed-size blocks to reduce fragmentation, and reusing shared prefixes (such as identical system prompts) to avoid duplicate storage.
5.4 Speculative Decoding
Speculative decoding uses a smaller draft model to predict multiple candidate tokens first, then has the large model verify them all at once. If the acceptance rate is high, overall decoding speed improves noticeably. If the acceptance rate is low, the extra draft computation actually slows things down.
The benefit depends heavily on how well the draft model matches the task. Teams should confirm gains through real load testing rather than theoretical reasoning alone.
5.5 Model Routing and Distillation
Model routing directs simple questions to small models and complex ones to large models based on request complexity. Knowledge distillation transfers capabilities from a large model to a smaller one. Both reduce average unit cost, but routing rules introduce quality variance, so the performance of each routing branch must be monitored continuously.
The table below summarizes the main benefits and costs of these techniques:
| Technique | Main benefit | Main cost |
|---|---|---|
| Dynamic batching | Higher throughput and utilization | Added waiting latency under low load |
| Quantization | Lower memory and bandwidth pressure | Possible output quality loss |
| KV cache | Eliminates redundant computation | Memory usage grows with context length |
| Speculative decoding | Faster token-by-token generation | Negative returns when acceptance rate is low |
| Model routing & distillation | Lower average unit cost | Quality variance from routing errors |
6. Elastic Scaling and Capacity Planning
Capacity planning starts with estimating the number of instances needed. Use this formula:
Required instances ≈ Peak requests per second × average request duration (seconds) ÷ concurrent capacity per instance × redundancy factor
The first part of the formula yields the number of concurrent requests at peak, following the basic relationship in queuing theory. The redundancy factor accounts for traffic bursts, instance failures, and deployment processes; an empirical value of 1.2 to 1.5 is commonly used in engineering practice.
Beyond the formula, keep the following points in mind.
- Baseline plus elasticity: baseline capacity covers daily traffic, with elastic scaling supplementing peaks. Loading model weights takes a long time, so scaling out involves noticeable cold-start delays. Keep some warm standby instances, or scale up ahead of known peaks.
- Exploit time patterns: evening peaks in education-related workloads follow predictable schedules, making them well suited for scheduled scaling policies.
- Isolate online from offline workloads: offline tasks such as data generation and model evaluation should use separate resource pools to avoid competing with online services for compute.
- Design degradation paths: under overload, shorten output length, switch to a smaller model, or return a queuing notice to users, keeping the core path available.
7. Observability and Cost Governance
Without measurement, there is no way to judge whether optimization is working. An inference service should collect at least these five categories of metrics:
- Latency: TTFT, TPOT, and P50, P95, P99 percentiles.
- Throughput: requests per second, output tokens per second.
- Resources: GPU utilization, memory usage, average batch size.
- Quality and stability: error rate, timeout rate, output length distribution, and quality scores from human or automated evaluation.
- Cost: per-token cost, and cost broken down by business line, feature, and tenant.
Alert thresholds should be set based on business SLOs rather than generic values. For example, an alert rule could be: “trigger scale-out or degradation when P99 TTFT exceeds the target for 5 consecutive minutes.”
Cost allocation depends on request-level labels. Every request should carry identifiers for business line, feature module, and tenant, so questions like “how much compute did this business consume?” can be answered. Without these labels, cost optimization can only remain at an aggregate level.
8. Implementation Recommendations
- Define service goals first: set explicit upper bounds for TTFT, availability, and unit cost, and align all subsequent optimization with these targets.
- Establish a load-testing baseline: test with the input lengths, output lengths, and concurrency distribution of real requests—do not rely only on fixed samples.
- Tier by business priority: core conversational paths get latency guarantees first; offline analytics tasks can tolerate queuing.
- Roll out changes in small, gated steps: change quantization, batching parameters, and routing rules one at a time, comparing quality and performance metrics each time.
- Recalculate models periodically: model versions, traffic structure, and business rules all change, so capacity and cost models need periodic updates.
Closing thought: training determines the ceiling of a model’s capability; inference determines whether that capability actually reaches users. Only by building inference as long-running infrastructure can teams find a sustainable balance among cost, experience, and stability.
