LLM Inference Latency and Throughput Optimization: A Practical Guide

    This article breaks down large language model inference performance into two core metrics, TTFT and TPS, and explains why latency rises during queueing and prefill while throughput drops due to memory bandwidth limits during decoding. It covers practical techniques such as prefix caching, context trimming, continuous batching, KV cache reuse, quantization, and speculative decoding, along with tiered reasoning budgets, graceful degradation, observability, cost control, and a checklist for deciding whether a model is good enough for your workload.

    1. Background: What Subscription Caps Reveal About Rigid Compute Supply

    Recently, an AI coding tool paused new membership subscriptions because compute capacity was tight, and several mainstream assistants in the industry soon showed similar capacity constraints. For developers, this is not an isolated piece of business news. It signals that compute supply for LLM inference is rigid in the short term: demand often grows faster than clusters can scale.

    This article does not evaluate any specific product. Instead, it abstracts the phenomenon into a general engineering problem: when inference capacity becomes a scarce resource, how can the application layer use architecture and invocation strategies to spend limited compute on the most critical tasks while preserving the interaction experience?

    One valuable observation from the original discussion is that the author did not make the highest-tier model the default option, because mid-tier models are already sufficient for everyday tasks, while higher-tier models are “slow to first token and slow to stream.” This is exactly the right approach to engineering选型 — model choice should be driven by task requirements, not by chasing whatever is newest.

    2. Defining “Slow”: Standard Latency Metrics

    Before discussing optimization, we need a shared set of measurements. Two core metrics are widely accepted in the industry:

    • TTFT (Time To First Token): the time from sending a request to receiving the first token. It determines “how long until something happens after I click.”
    • TPS (Tokens Per Second): the number of output tokens per second during decoding. It determines “how smoothly the text scrolls.”

    The total time of a request can be approximated as:

    1. Total latency ≈ queue wait + prefill + first token generation + decode
    2. TTFT ≈ queue wait + prefill + first token generation
    3. Total output time ≈ number of output tokens / TPS

    The value of this breakdown is that high TTFT is usually a queueing and prefill problem, while low TPS is usually a memory bandwidth and batching problem in the decode phase. The optimization techniques for the two are completely different, and discussing them together is inevitably inefficient.

    3. Why TTFT Is High: Queueing and Prefill Pressure

    Elevated TTFT generally comes from three places:

    1. Queue wait. When cluster concurrency is saturated, requests enter a waiting queue, and users perceive it as “spinning for a long time before text appears.” This is a capacity problem and can only be mitigated by scaling out, rate limiting, and priority scheduling.
    2. Prefill computation. The longer the input context, the larger the computation in the prefill phase. A request carrying a very long codebase context naturally has a higher first-token latency than a short question.
    3. Cold start and scheduling overhead. Instance startup, model weight loading, and connection establishment all add to the first-token time.

    Viable engineering measures include: reusing prefix caches for system prompts and long documents; retrieval-based trimming of very long contexts to keep only truly relevant fragments; and splitting requests into priority queues so interactive requests take precedence over batch jobs.

    1. # Example: reducing prefill overhead by trimming context
    2. def build_context(query, chunks, max_tokens=4000):
    3. ranked = rank_by_relevance(query, chunks) # rank by relevance
    4. picked, used = [], 0
    5. for c in ranked:
    6. if used + c.tokens > max_tokens:
    7. break
    8. picked.append(c)
    9. used += c.tokens
    10. return concat(picked)

    4. Why TPS Is Low: Physical Limits of the Decode Phase

    Decoding is token-by-token autoregressive generation. Each step must read all model weights and the growing KV cache, so the bottleneck is usually memory bandwidth rather than peak compute. The longer the context and the higher the concurrency, the less bandwidth each request gets, and the lower the TPS.

    Common optimization directions include:

    • Continuous batching: dynamically batching different requests to improve memory and compute utilization;
    • KV cache reuse and compression: reducing the memory footprint of long contexts;
    • Quantization and more efficient attention implementations: improving bandwidth efficiency within acceptable accuracy loss;
    • Speculative decoding: using a small model or draft mechanism to guess multiple tokens first, then verifying them with the large model, reducing the average number of decode steps.

    These are general techniques on the inference serving side. What the application side can do is “generate less and generate accurately,” for example by constraining output formats, reducing redundant explanations, and splitting long-form generation into multiple parallel segments.

    5. High and Low Modes: Tiered Reasoning Depth and Its Cost

    The original discussion mentions that the platform opened two thinking modes, high and low, which alleviated over-thinking, but throughput and first-token latency did not change. This reflects a general rule: reasoning depth (chain-of-thought length) is roughly linearly related to latency and cost.

    The engineering recommendation is to make the “thinking budget” configurable rather than globally fixed:

    1. Task tiering strategy
    2. ├─ Simple rewriting/completion → low mode, short output, prioritize interaction speed
    3. ├─ Routine coding and debugging → medium tier, moderate reasoning
    4. └─ Architecture design/hard debugging → high mode, allow longer reasoning and higher cost

    The key is routing: a lightweight classifier or set of rules judges task difficulty and allocates expensive compute only to requests that truly need it. This both keeps the bill down and improves overall throughput when capacity is tight.

    6. Stability Design When Capacity Is Tight

    When supply tightens, the application must degrade gracefully instead of failing outright:

    1. Multi-level fallback chain: when a high-tier model is unavailable, automatically fall back to a mid-tier model, then to a small-parameter model or rule-based template.
    2. Rate limiting and queue feedback: clearly show users their queue position or estimated wait to avoid long, feedback-free blanks.
    3. Result caching and idempotency: apply semantic caching to high-frequency repeated requests and return on a hit, saving an inference entirely.
    4. Asynchronous and streaming output: move long tasks to background execution with polling or push, and keep interactive tasks streaming to improve perceived experience.
    5. Observability: instrument TTFT, TPS, error rate, and queue time separately, configure monitoring and alerts, and judge bottlenecks with data rather than intuition.
    1. async def call_with_fallback(prompt, models):
    2. for m in models: # try from high to low
    3. try:
    4. return await stream_call(m, prompt, timeout=m.timeout)
    5. except (CapacityError, TimeoutError):
    6. continue
    7. return template_answer(prompt) # final fallback

    7. Cost Perspective: Spending Compute Where It Matters

    The other side of tight capacity is rising cost. General measures include: routing model tiers by task difficulty; compressing context and output length; switching deterministic tasks to caching or small models; scheduling batch jobs during off-peak hours; and setting quotas and budget alerts for different business lines. If you use cloud inference services, you can combine container platforms for elastic scaling, use object storage to persist caches and results, and use logging and monitoring services to close the loop.

    8. Selection Checklist: How to Tell Whether a Model Is “Good Enough”

    Do not look only at leaderboards. It is better to run a small-scale evaluation on your own business samples and focus on four things:

    • Whether first-token latency meets interaction expectations;
    • Whether output speed makes long-form generation tolerable;
    • Whether task accuracy reaches the usable line;
    • Whether the cost per task is within budget.

    The conclusion is usually consistent with the original discussion: for most everyday coding tasks, a mid-tier model is already sufficient; high-tier models should be reserved for the few high-value hard problems. Choose the tier by task and choose capacity by data — that is the right way to get through compute cycles.