LLM Inference Performance and Cost Optimization: A Practical Guide

    This guide breaks down how to balance throughput, latency, quality, and cost when running large language models in production. It defines the core metrics (TPS, TTFT, end-to-end latency, and per-task token cost), explains the inference architecture and infrastructure choices behind high throughput and low latency, addresses the hidden cost of extended thinking tokens, and provides a migration checklist and cost governance strategy for moving between model versions. Readers will find benchmark pseudocode, routing configuration examples, and actionable practices for capacity planning and canary rollouts.

    1. Background: Engineering Lessons from a Version Switch

    A common pattern in LLM platform evolution is the launch of a new version optimized for high throughput and low latency, while a previous high-specification version is retired at the same time. Community discussions often focus on which generation is “more powerful.” From the perspective of developers and enterprise users, however, the more important questions are the engineering trade-offs behind the switch: compute cost per unit, service concurrency, inference pipeline redesign, and smooth migration of existing workloads.

    In the model service roadmap of a cloud provider, this kind of switch is rarely a simple replacement of old with new. It is usually the result of rebalancing three factors: compute overhead, training resource usage, and user experience. Setting aside specific product attributes, this article frames the issue as a general technical problem: how to make verifiable trade-offs among throughput, latency, quality, and cost.

    2. Define the Metrics First: Throughput, TTFT, and Total Cost

    Performance discussions require a shared vocabulary; otherwise, conclusions cannot be reproduced.

    • TPS (output tokens per second): reflects throughput during the generation phase and affects the perceived smoothness of long-form reading.
    • TTFT (time to first token): the time from request submission to the first returned token, which determines responsiveness in interactive scenarios.
    • End-to-end latency: TTFT plus the full generation time; this is the actual wait time experienced by the user.
    • Per-task token cost: includes input, output, and thinking tokens, and is the core variable for billing and capacity planning.

    A widely accepted rule of thumb is that interactive applications are more sensitive to TTFT, while batch and offline generation are more sensitive to TPS and total throughput. A target such as “300+ TPS with sub-500ms TTFT” is therefore about finding a balance between interactive experience and resource efficiency, rather than maximizing a single number.

    Illustrative benchmark pseudocode:

    1. def bench(endpoint, prompts, max_tokens=1024):
    2. for p in prompts:
    3. t0 = now_ms()
    4. first = None
    5. for tok in stream(endpoint, p, max_tokens):
    6. if first is None:
    7. first = now_ms()
    8. ttft = first - t0
    9. e2e = now_ms() - t0
    10. out_tokens = count(tok)
    11. yield ttft, e2e, out_tokens / ((e2e - ttft) / 1000)

    3. Architecture and Infrastructure: Where High Throughput and Low Latency Come From

    Significantly improving TPS and reducing TTFT without sacrificing quality typically requires coordinated evolution of both the inference architecture and the serving infrastructure. Common directions include:

    1. Inference engine layer: continuous batching, paged attention cache management, operator fusion, and efficient sampling can substantially improve GPU utilization.
    2. Parallelism and scheduling: a sensible mix of tensor parallelism and pipeline parallelism, combined with request priority queues, prevents long requests from blocking short ones.
    3. KV cache strategy: cache reuse, prefix sharing, and tiered storage reduce the compute wasted on repeated prefill.
    4. Service gateway and network path: streaming transport, connection reuse, and nearby access points reduce added network latency.
    5. Elasticity and observability: container-based autoscaling, combined with logging and monitoring/alerting, enables continuous profiling of TTFT, TPS, and queue time.

    By contrast, if a previous high-specification version did not evolve architecturally, it can lose its per-unit cost advantage even with a larger parameter count. This is the engineering root cause of being “overtaken on cost-efficiency,” not a simple “capability regression.”

    4. Overthinking and Token Overhead: The Underrated Cost Driver

    A common side effect of new versions is “longer thinking”: the model generates more intermediate reasoning tokens before producing an answer. High TPS can mask the perceived latency introduced by thinking, but it cannot eliminate the cost impact.

    • Approximate cost formula: total cost ≈ (input tokens + output tokens + thinking tokens) × unit price.
    • Thinking tokens are billed on the output side, so long reasoning chains can significantly raise per-task cost.
    • The result: the experience gains from higher speed may be offset by the increase in total tokens, leaving the actual bill only slightly lower.

    On the engineering side, this can be managed through prompt constraints, structured output, thinking budget limits, result caching, and batch consolidation, rather than indiscriminately compressing model capability.

    5. Version Migration: A Checklist Before Retiring the Old Version

    When a high-specification version enters its deprecation window, the business side should prepare in advance:

    1. Build an abstraction layer: wrap model invocation in a unified interface so business code does not hardcode specific version identifiers.
    2. Dual-run and canary: evaluate old and new versions in parallel, replaying real traffic to compare quality, latency, and cost.
    3. Regression baseline: build automated evaluation sets for critical tasks and define quality guardrail metrics.
    4. Fallback plan: rate limiting, queuing, and cached fallbacks to prevent capacity fluctuations during the switch window.
    5. Cost dashboard: break down token consumption by business line to locate sources of abnormal growth.
    1. {
    2. "routing": {
    3. "default": "flash_like",
    4. "fallback": "previous_gen",
    5. "canary_percent": 5,
    6. "guardrails": {"ttft_ms": 800, "max_thinking_tokens": 2048}
    7. }
    8. }

    6. Cost Governance and Capacity Planning

    Under mixed workloads, it is advisable to tier tasks: route interactive Q&A through a low-latency channel, and route long-form generation and offline batch jobs through a throughput-first channel. Enable result caching for repeated requests and prefix cache reuse for stable prompts. Capacity planning should be modeled on “peak concurrency × per-request token distribution,” with elastic headroom reserved. If an organization already uses relevant general-purpose capabilities from Baidu AI Cloud, it can combine object storage, message queues, container platforms, and monitoring/alerting to build a complete inference operations loop.

    7. Conclusion

    The essence of a version switch is rebalancing resource efficiency and user experience. Developers should focus on reproducible benchmark definitions, rollback-capable migration paths, and a sustainable cost structure, rather than debating the merits of a single model type. Building metrics, architecture, token budgets, and canary mechanisms into a coherent system is what allows each iteration to deliver stable gains.