High-Speed LLM Inference Services: Design, Metrics, Engine Optimization, and Cost Control
This article explains how to design and operate high-speed inference services for large language models as request volume grows. It covers four core metrics—throughput, time to first token (TTFT), time per output token (TPOT), and unit cost—along with capacity estimation and resource scheduling. It then reviews inference engine techniques such as continuous batching, KV cache management, quantization, speculative decoding, and kernel optimization, and provides a streaming benchmark script. The article also describes layered validation across unit, service, and business levels, service tiers and pricing principles, and a practical rollout sequence with risk controls. The goal is to use reliable measurements to balance latency, throughput, stability, and cost as demand scales.
1. Background: Inference Pressure from Growing Request Volume
After an LLM service goes live, request volume often grows quickly. As traffic rises, service operators commonly face three problems: longer queueing time, slower individual responses, and compute costs that rise linearly with request volume. These problems are related. Longer queues increase tail latency; higher tail latency causes clients to retry; retries further amplify load, creating a vicious cycle.
Therefore, the goal of building an inference service cannot be limited to model quality. Service operators also need to answer several questions: How many requests can be processed per unit time? How long does it take to return the first token for each request? What is the cost per thousand output tokens? Can the service remain stable during peak hours? These questions determine whether the service can support business growth.
2. Core Metrics
When evaluating an inference service, it is advisable to track at least the following four types of metrics.
1. Throughput
Throughput is usually measured as the number of output tokens generated per second. The formula is:
Throughput = Total number of output tokens generated within the measurement window / Window length in seconds
Throughput reflects the overall output capacity of a cluster or a single instance and directly affects the cost per unit of compute.
2. Time to First Token (TTFT)
TTFT is the time from sending a request to receiving the first output token. This metric is mainly affected by queueing and prompt preprocessing (prefill) speed, and it has the greatest impact on the experience of interactive applications.
3. Time per Output Token (TPOT)
TPOT is the average time required to generate each token during the generation phase, and it determines the perceived speed of streaming output. This metric is mainly affected by computation and memory bandwidth during the decode phase.
4. Unit Cost
Unit cost is commonly measured as the compute cost per million output tokens. Cost is directly related to hardware price, utilization, and throughput. Improving utilization is usually more effective than simply reducing hardware unit price.
These four metrics need to be considered together. Pursuing throughput alone may push TTFT beyond the tolerance of interactive scenarios. Pursuing only low latency may reduce batching efficiency and increase unit cost.
3. Capacity Expansion and Resource Scheduling
Scaling out is the most direct approach, but capacity should be estimated before adding machines to avoid blind expansion. A common estimation method is:
Required instances = Peak requests per second × Average number of output tokens / Stable throughput per instance × Redundancy factor
The redundancy factor is usually set to 1.2 to 1.5 to handle traffic spikes and single-instance failures. The following hypothetical numbers illustrate the calculation process (these numbers are examples only, not measured data):
- Peak requests per second: 20
- Average number of output tokens: 500
- Stable throughput per instance: 2000 token/s
- Redundancy factor: 1.3
The result is 20 × 500 / 2000 × 1.3 = 6.5, which means about 7 instances are needed.
For resource scheduling, consider the following practices:
- Divide resource pools by model and request type to prevent long-text tasks from occupying the entire cluster and affecting short-request latency.
- Use autoscaling triggered by queue length rather than CPU or GPU utilization alone, because queue length more directly reflects user waiting time.
- Set independent quotas for different service levels to guarantee response times for core business workloads.
4. Inference Engines and Optimization Techniques
Beyond compute capacity, inference engines also offer substantial room for optimization. The following techniques are widely used in the industry.
1. Continuous Batching
Traditional static batching must wait for an entire batch of requests to finish before starting the next batch, so short requests are slowed down by long requests. Continuous batching checks for completed requests at each decoding step and immediately fills the batch with new requests, improving GPU utilization and reducing queueing time.
2. KV Cache Management
The key-value cache in attention mechanisms consumes a large amount of GPU memory, and insufficient memory limits concurrency. Common practices include allocating cache in blocks on demand, reusing cache for identical prefixes (prefix caching), and scheduling requests appropriately when memory is tight.
3. Quantization
Converting weights or activations from higher precision to lower precision can reduce memory usage and improve bandwidth utilization. Quantization introduces some accuracy loss, so regression evaluation on target tasks is required; speed metrics alone are not sufficient.
4. Speculative Decoding
A smaller draft model first proposes several candidate tokens, which are then verified by the target model in one pass. Tokens that pass verification can be accepted in batches, reducing the number of forward computations in the target model. The benefit depends on how well the draft model matches the target model and on the task type.
5. Operator Fusion and Kernel Optimization
Combining multiple small operators into one kernel reduces memory reads and writes and kernel launch overhead. Such optimizations usually need to be verified item by item against hardware characteristics.
Optimization results should be confirmed through benchmarks. The following script measures TTFT and generation speed for a single request.
import osimport timeimport jsonimport requestsBASE_URL = os.environ["LLM_BASE_URL"]API_KEY = os.environ["LLM_API_KEY"]MODEL = os.environ["LLM_MODEL"]def measure_stream(prompt: str, timeout: int = 120) -> dict:"""Send one streaming request and return TTFT and generation speed."""payload = {"model": MODEL,"messages": [{"role": "user", "content": prompt}],"stream": True,}headers = {"Authorization": f"Bearer {API_KEY}"}start = time.perf_counter()first_token_at = Nonechunk_count = 0with requests.post(f"{BASE_URL}/chat/completions",json=payload,headers=headers,stream=True,timeout=timeout,) as resp:resp.raise_for_status()for line in resp.iter_lines():if not line or not line.startswith(b"data: "):continuedata = line[len(b"data: "):]if data == b"[DONE]":breakevent = json.loads(data)delta = event["choices"][0].get("delta", {})if not delta.get("content"):continueif first_token_at is None:first_token_at = time.perf_counter()chunk_count += 1end = time.perf_counter()if first_token_at is None:raise RuntimeError("No output content received")ttft = first_token_at - startdecode_seconds = end - first_token_at# Approximate output tokens by content chunks; exact counting requires the model's tokenizerspeed = chunk_count / decode_seconds if decode_seconds > 0 else 0.0return {"ttft_s": round(ttft, 3), "approx_tokens_per_s": round(speed, 1)}if __name__ == "__main__":prompts = ["Explain the role of continuous batching in three sentences."] * 5results = [measure_stream(p) for p in prompts]for i, r in enumerate(results, 1):print(f"Run {i}: {r}")
When using this type of script, keep several points in mind. First, tests should cover the real distribution of input and output lengths, not just short prompts. Second, compare versions under the same concurrency conditions. Third, take multiple samples and report percentiles such as P50 and P95 rather than only the average.
5. Infrastructure Automation and Layered Validation
The stability of inference services increasingly depends on the degree of infrastructure automation. Deployment, configuration tuning, rollback, and monitoring can all be managed through pipelines, with tools executing tasks automatically and recording results.
With this approach, optimization work can be validated at three layers:
- Unit-level validation: Check numerical error and performance changes for a single operator, kernel, or configuration item.
- Service-level validation: Run benchmarks on the complete inference service and check throughput, latency, and error rate.
- Business-level validation: Use real business data to evaluate output quality and confirm that optimization has not harmed core task performance.
The value of layered validation is that each layer can detect problems early and prevent lower-level performance regressions from reaching production. Infrastructure changes should follow the same principle: first roll out to a small scope, then gradually increase the percentage, while retaining the ability to roll back quickly.
In addition, automation tools can help engineers with repetitive work such as generating configuration candidates, running batch benchmarks, and summarizing comparison reports. Engineers define goals and judge results, while tools execute and record. This division of labor shortens iteration cycles while preserving human review.
6. Cost and Service Tiers
The same model often needs to provide multiple service tiers. A common approach is to distinguish between standard service and high-speed service: standard service focuses on cost and is suitable for offline batch tasks; high-speed service focuses on low latency and is suitable for interactive scenarios. High-speed service usually requires more reserved compute capacity, so its unit price is higher.
Pricing design should follow these principles:
- Price differences should correspond to real cost differences, rather than using pricing to hide resource allocation problems.
- Clearly explain the applicable scenarios of each tier to users, so they do not place batch tasks on the high-speed channel.
- Set usage monitoring and alerts to prevent abnormal calls from causing budget overruns.
7. Implementation Recommendations and Risks
When implementing inference optimization, proceed in the following order:
- Establish a baseline: record current throughput, latency, cost, and error rate.
- Identify bottlenecks: distinguish between compute-bound, memory-bound, and scheduling-bound scenarios.
- Validate in small steps: change only one variable at a time and keep comparison data.
- Roll out gradually: increase traffic by percentage and observe metric changes.
- Monitor continuously: set alert thresholds and periodically review cost and quality.
Risks to note include the following: optimization may introduce accuracy loss, which should be confirmed through business evaluation; resource contention under high concurrency may increase tail latency, so timeouts and rate limiting should be configured; changes in hardware and software versions may affect results, so benchmarks should be rerun after changes.
In summary, optimizing inference services is a systems engineering effort. It requires capacity planning, engine optimization, scheduling strategy, automated validation, and cost management to work together. By using reliable metrics as the basis and validating each item step by step, teams can keep services stable as business grows and control unit cost.
