Engineering Design and Optimization for High-Throughput LLM Inference Services

    This article explores the engineering design and optimization strategies for high-throughput Large Language Model (LLM) inference services. It covers balancing throughput, latency, and costs under growing demand, defining key performance metrics, capacity planning, service tiering, common inference optimization techniques, infrastructure automation, and phased rollout practices.

    1. Capacity Pressure from Growing Demand

    When API calls for a model surge, service providers typically face three types of pressure simultaneously: longer queue times, slower per-request responses, and costs scaling linearly with call volume. These issues are interconnected. Longer queues increase user-perceived latency, and temporary scaling to mitigate queues drives up unit costs. Therefore, the design goal of an inference service is not just speed, but finding a sustainable long-term balance among throughput, latency, and cost.

    2. Unifying Performance Metrics

    Before discussing inference performance, it is necessary to unify several metrics:

    • Time to First Token (TTFT): The time from request arrival to the output of the first token. It is primarily affected by queue waiting, prefill computation, and network transmission.
    • Generation Speed (tokens/s): The number of tokens generated per second during the output phase, determining the full return time for long texts.
    • System Throughput (requests/s or tokens/s): The total work completed by the entire cluster per unit of time, which is the basis for capacity planning.
    • Tail Latency (P95, P99): The percentile where slow requests fall, reflecting real user experience better than the average.

    Generation speed figures are only comparable under the same input length, maximum output length, concurrency, and hardware conditions. Otherwise, the measured numbers are not comparable. The following function calculates the mean and P95 of latency samples:

    1. def summarize_latency(samples_ms):
    2. """Calculate the mean and P95 of latency samples in milliseconds."""
    3. ordered = sorted(samples_ms)
    4. mean = sum(ordered) / len(ordered)
    5. idx = max(0, int(round(0.95 * len(ordered))) - 1)
    6. return {"mean_ms": round(mean, 1), "p95_ms": ordered[idx]}

    When comparing two solutions, you should fix the input length distribution, maximum output length, and concurrency gradient, and then record the above metrics respectively. Looking only at a single peak speed number easily ignores changes in queueing and tail latency.

    3. Estimating Compute Capacity from Demand

    Capacity planning can start with a simple model:

    Required instances ≈ Peak requests per second × Average processing time per request ÷ Concurrency per instance × Redundancy factor

    Example: Assuming a peak of 200 requests per second, each request averages 2 seconds of inference resource occupation, a single instance can process 8 requests in parallel, and the redundancy factor is 1.3. Plugging this in: 200 × 2 ÷ 8 × 1.3 = 65 instances. These numbers are only for illustrating the calculation method; actual values need to be obtained through stress testing.

    The redundancy factor is used to cover traffic spikes, node failures, and capacity drops during releases. Stress testing must be repeated after scaling. As concurrency increases, memory usage and scheduling overhead change, and the true capacity of a single instance may be lower than the linearly extrapolated result.

    4. Service Tiering: Trade-offs within the Same Service

    Not all calls require the highest speed. A common practice is to divide the service into several tiers:

    • Standard Tier: Low unit cost, suitable for offline batch processing, bulk summarization, and latency-insensitive tasks.
    • High-Speed Tier: High unit cost, suitable for conversational interaction, real-time completion, and other scenarios requiring low latency.
    • Elastic Tier: Reserved surplus resources for burst traffic, billed based on actual usage.

    Pricing should reflect unit cost and service level. The high-speed tier typically occupies more high-performance resources or retains more headroom, so it is reasonable for its price to be higher than the standard tier. When designing tiers, the team should calculate the per-token cost, target latency, and gross margin for each tier, rather than just comparing speed multiples. If the price difference between tiers exceeds the cost difference, users will flock to the lower-priced tier, leaving high-speed resources idle.

    5. Common Inference Optimization Techniques

    1. Dynamic Batching: Combines multiple requests into the same batch for computation to improve hardware utilization. The key is controlling the wait window to avoid increasing TTFT just to fill a batch.
    2. KV Cache Management: Caches intermediate results of attention computation to avoid redundant calculations. Excessive caching will fill up memory, so capacity limits and eviction policies are needed.
    3. Prefix Reuse: Reuses cached prefixes for identical system prompts or documents to reduce prefill overhead.
    4. Quantization: Reduces the numerical precision of weights or activations in exchange for memory and bandwidth benefits. After quantization, the magnitude of output quality degradation must be evaluated.
    5. Speculative Decoding: A small model first generates candidate tokens, which are then verified in batches by the large model. Scenarios with longer outputs and more predictable patterns benefit more obviously.

    The core of batch scheduling is assembling batches according to a memory budget. Below is a simplified illustration:

    1. def build_batch(queue, max_tokens_per_batch):
    2. """Assemble a batch based on token budget to prevent OOM caused by oversized batches."""
    3. batch, used = [], 0
    4. while queue and used + queue[0]["prompt_tokens"] <= max_tokens_per_batch:
    5. req = queue.pop(0)
    6. batch.append(req)
    7. used += req["prompt_tokens"]
    8. return batch

    A real scheduler must also consider output length estimation, request priority, and timeout cancellation. Before any optimization goes live, output quality evaluation should be regressed simultaneously, because throughput improvements sometimes come with quality degradation, and looking only at speed metrics will miss such issues.

    6. Infrastructure Automation and Closed-Loop Validation

    Large teams often delegate configuration generation, deployment script writing, troubleshooting, and performance regression to automated processes. Whether automation can run reliably depends on whether a verifiable feedback environment has been established:

    • Break down infrastructure tasks into measurable sub-tasks, each with clear pass criteria.
    • Execute changes in an isolated environment, recording changes in throughput, error rate, and resource usage.
    • Adopt tiered validation: unit level checks script syntax and parameters, integration level checks service availability, and system level checks end-to-end stress test results.
    • Only changes that pass all levels of validation can proceed to canary release.

    When service optimization and model iteration form a mutually reinforcing loop, validation signals must be reliable. If the evaluation criteria themselves are biased, automation will only amplify errors faster. Therefore, validation sets need to be updated regularly and should cover real-world failure and load scenarios.

    7. Integration and Canary Deployment Practices

    When integrating clients, interface URLs, API keys, and model identifiers should be placed in environment variables or a secret management service, rather than hardcoded. Below is an example of making a request using the standard library; specific request fields should follow the service provider’s API documentation:

    1. import json
    2. import os
    3. import urllib.request
    4. API_URL = os.environ["LLM_API_URL"]
    5. API_KEY = os.environ["LLM_API_KEY"]
    6. MODEL_KEY = os.environ["LLM_MODEL_KEY"]
    7. def chat(prompt, timeout_s=30):
    8. body = json.dumps({
    9. "model": MODEL_KEY,
    10. "messages": [{"role": "user", "content": prompt}],
    11. }).encode("utf-8")
    12. req = urllib.request.Request(
    13. API_URL,
    14. data=body,
    15. headers={
    16. "Authorization": f"Bearer {API_KEY}",
    17. "Content-Type": "application/json",
    18. },
    19. method="POST",
    20. )
    21. with urllib.request.urlopen(req, timeout=timeout_s) as resp:
    22. return json.loads(resp.read().decode("utf-8"))

    For canary releases, it is recommended to initially switch 1% to 5% of traffic, compare error rates, P95 latency, and output quality, and gradually increase traffic after confirming no anomalies. Each stage should have a pre-set rollback threshold, such as automatically rolling back if the error rate exceeds a certain multiple of the baseline.

    8. Checklist

    • Did you fix the input length distribution and concurrency gradient during stress testing?
    • Are you tracking TTFT, generation speed, and P95 simultaneously?
    • Did you re-stress test after scaling up, rather than relying on linear extrapolation?
    • Have you calculated the unit cost and gross margin for each tier in tiered pricing?
    • Have you re-completed output quality evaluation after performance optimization?
    • Are API keys and interface URLs sourced from configuration or a secret management service, rather than hardcoded?