LLM Inference Optimization: A Practical Guide to Speed and Cost Reduction

    This guide breaks down how to improve large language model inference speed and control costs. It explains how to measure throughput and time-to-first-token, which architectural and infrastructure changes drive high-throughput low-latency serving, how reasoning tokens inflate real bills, and how to migrate safely when model versions are retired. Readers will find baseline measurement code, cost governance tactics, and scenario-based selection advice.

    1. The Signal Behind a Model Version Update

    A pattern has recently emerged in the industry: a model service launches an inference version focused on high throughput and low latency, while the previous high-capability version is being retired on a stated timeline. Setting aside the specific product, this pattern carries three reusable technical signals.

    First, the gains from inference-side engineering optimization have, in certain scenarios, surpassed the gains from simply scaling up parameters. Second, the compute cost of the high-capability version is considered too high, making its per-request cost hard to justify for long-tail usage. Third, the new version most likely involves structural changes to both architecture and serving infrastructure; otherwise it would be difficult to simultaneously achieve output throughput of hundreds of tokens per second and time-to-first-token in the hundreds of milliseconds.

    For developers and enterprise users, the real question is not “which version is stronger,” but rather: how to establish a performance baseline, how to evaluate the actual cost of reasoning models, and how to migrate smoothly during a version transition.

    2. Breaking “Fast” into Measurable Metrics

    When discussing inference performance, you must distinguish two metrics that are often confused:

    • Throughput (TPS): the number of output tokens per request per unit of time, which determines whether reading the output “feels responsive.”
    • Time-to-first-token (TTFT): the time from sending a request to receiving the first output token, which determines whether the service “feels stuck.”

    The two often trade off against each other. Batching can significantly improve overall cluster utilization and total throughput, but it raises single-request TTFT; conversely, reducing batch size and shortening queue time improves latency but sacrifices overall cost efficiency. Therefore, any claim of “300+ TPS, 500ms-class TTFT” should be understood as an operating point under a specific workload and context length, not a universal promise.

    Teams are advised to build their own baseline scripts that fix input length, output length, concurrency, and sampling parameters to produce comparable regression data:

    1. # Example: minimal viable inference performance baseline collection
    2. import time
    3. def measure(client, prompt, max_tokens=512):
    4. t0 = time.perf_counter()
    5. first_token_at = None
    6. text = []
    7. for chunk in client.stream(prompt, max_tokens=max_tokens):
    8. if first_token_at is None:
    9. first_token_at = time.perf_counter()
    10. text.append(chunk)
    11. t1 = time.perf_counter()
    12. out_tokens = len("".join(text)) # use real tokenization counts in actual projects
    13. return {
    14. "ttft_ms": (first_token_at - t0) * 1000,
    15. "tps": out_tokens / (t1 - first_token_at),
    16. "total_ms": (t1 - t0) * 1000,
    17. }

    3. Architecture and Infrastructure Changes Behind High Throughput and Low Latency

    To suppress both tail ends of latency simultaneously, engineering efforts usually need to be coordinated across the following layers, which are also widely recognized directions in the industry:

    1. Attention mechanism and memory management. Paged key-value cache management, prefix reuse, and more efficient attention implementations can significantly reduce memory fragmentation and redundant computation under long contexts.
    2. Scheduling layer. Continuous batching combined with priority queues prevents long requests from blocking short ones; latency-sensitive workloads can be assigned to a separate latency queue.
    3. Parallelism strategy. The combination of tensor parallelism, pipeline parallelism, and expert parallelism determines the balance point between single-card memory pressure and cross-card communication overhead.
    4. Transport and deployment form. Nearby access, connection reuse, streaming chunked output, and elastic scaling on container platforms all directly affect perceived latency.
    5. Observability. Logging and monitoring/alerting must cover queue time, batch size distribution, cache hit rate, and memory watermarks; otherwise performance issues cannot be attributed.

    A practical rule of thumb: if TTFT is mainly caused by queuing, optimize scheduling and capacity; if it is mainly caused by prefill computation, optimize parallelism and cache reuse. The remediation approaches for the two are entirely different.

    4. The Cost of “Overthinking”: Reasoning Tokens and the Real Bill

    Reasoning models first generate an internal reasoning segment before producing an answer. This improves accuracy on complex reasoning tasks, but it also introduces an often-underestimated problem: reasoning tokens count as output, directly amplifying both cost and latency.

    The key is to distinguish “tokens needed to complete the task” from “billed tokens.” When output is fast enough, the user’s subjective experience does not degrade as reasoning grows longer, but the bill faithfully reflects that overhead. Cost governance should therefore start from both the prompt and decoding sides:

    • Task tiering: route simple extraction, classification, and formatting tasks to low-reasoning-budget configurations; only open up reasoning for complex reasoning tasks.
    • Budget constraints: set reasoning or output limits on supported interfaces to avoid unbounded expansion.
    • Context slimming: in retrieval-augmented scenarios, compress redundant fragments to reduce prefill and repeated reasoning.
    • Result caching: apply semantic caching to idempotent requests so that a cache hit skips inference entirely.
    • Sampling convergence: reduce unnecessary diversity sampling to cut repeated self-correction.
    1. Request routing example
    2. ├─ Rule/classification pre-check
    3. ├─ Simple task → low reasoning budget + small output limit
    4. └─ Complex task → high reasoning budget + streaming output + timeout circuit breaker

    5. Engineering Response During Version Rollout and Retirement

    When a high-capability version enters its retirement countdown, the risks concentrate on compatibility and sudden cost changes. A four-step approach is recommended:

    1. Build a version abstraction layer. Business code depends only on your own gateway interface, with the model identifier kept in a configuration center to avoid hardcoding.
    2. Dual-track canary. Migrate gradually by traffic proportion, comparing accuracy, latency, and per-request cost on the same evaluation set.
    3. Regression and fallback. Keep a degradation path and timeout retry strategy to prevent the new version from regressing on specific tasks.
    4. Cost alerting. Set threshold alerts on per-task cost to avoid budget overruns caused by amplified reasoning tokens.
    1. # Example: configuration-driven model routing and canary
    2. ROUTES = [
    3. {"name": "fast", "weight": 70, "max_output": 1024, "think_budget": "low"},
    4. {"name": "strong", "weight": 30, "max_output": 2048, "think_budget": "high"},
    5. ]

    6. Selection Advice: By Scenario, Not by “Strongest”

    • High-concurrency online services, code completion, structured extraction: prioritize the high-throughput low-latency version, combined with caching and rate limiting.
    • Long-chain complex reasoning, low-frequency high-value tasks: keep the high-capability version and strictly constrain output size.
    • Cost-sensitive batch processing: run offline queues during off-peak hours, trading throughput for cost.

    If an enterprise wants elastic compute, containerized deployment, and full-chain observability in its own environment, it can build a unified model service gateway on general-purpose capabilities such as Baidu AI Cloud’s container platform, object storage, logging service, and monitoring/alerting, achieving configurable versions, measurable cost, and repeatable performance regression.

    7. Conclusion

    The essence of version iteration is a shift in the performance and cost operating point. Developers should focus on reproducible baselines, clear metric decomposition, reasoning budget governance, and smooth version migration mechanisms, rather than chasing a single leaderboard number. Only then can each service upgrade reliably deliver lower per-task cost and a better user experience.