Low-Latency LLM Mode Selection: When to Pay for Speed and How to Fall Back

    This article explains how to choose between default and low-latency LLM inference modes using TTFT, TPOT, end-to-end latency, P95 measurements, and a per-request benefit formula. It provides a routing and fallback implementation, monitoring thresholds, and common pitfalls.

    1. Align on Metrics First: TTFT, TPOT, and End-to-End Latency

    LLM inference has two phases. The model first processes the input prompt, which is called prefill. It then generates output tokens one by one, which is called decode. Mode selection should use three metrics to describe the user experience:

    • TTFT (Time To First Token): The time from sending a request to receiving the first token. It determines how long users wait before they start seeing a response.
    • TPOT (Time Per Output Token): The average time to generate each subsequent token. It determines how fast the text flows.
    • End-to-end latency: The complete time the user waits, calculated as:

    End-to-end latency ≈ TTFT + output tokens × TPOT

    Measure from the moment the client sends the request to the moment the last token is received. Server-side log durations usually exclude network round-trip time and cannot directly replace client-side data.

    Three factors change these metrics:

    • Longer input increases prefill time, which increases TTFT.
    • Longer output makes the cumulative effect of TPOT more obvious, and end-to-end latency grows fastest in this case.
    • Higher concurrency increases queueing time and pushes up TTFT. Batching can improve overall throughput, but it may increase TPOT for individual requests.

    Therefore, mode selection should use P95 rather than averages. Averages can hide long-tail requests.

    2. Default Mode vs. Low-Latency Mode

    The multipliers in the table below come from vendor nominal values. Before launch, verify them against billing and measured data.

    Mode Price multiplier Speed multiplier Suitable requests Unsuitable requests
    Default mode 1× 1× Offline batch processing, document archiving, summary generation, background jobs insensitive to waiting First-screen replies where users are watching the screen and waiting
    Low-latency mode 2× 2.5× First screen of a conversation, real-time input assistance, interactive requests with explicit timeout budgets Batch jobs, long-form generation that users do not read token by token, requests with strict budget caps

    The speed multiplier should be understood as end-to-end latency. If the vendor only improves the decode phase and TTFT does not improve, the savings must be recalculated separately using the formula in Section 3.

    3. Per-Request Benefit Formula and Example

    To decide whether to pay for acceleration, compare the value of saved waiting time with the extra cost:

    Single-request benefit = value of saved waiting time − extra cost

    The components are calculated as follows:

    • Saved time: ΔT = T_default × (1 − 1 / 2.5) = 0.6 × T_default
    • Extra cost: C_extra = C_default × (2 − 1) = C_default
    • Value of saved waiting time: ΔT × V, where V is the business value of one second of waiting (CNY/second), provided by the product or business team

    This gives the break-even point. When V = C_default / (0.6 × T_default), the single-request benefit is zero.

    Example (with the following assumptions):

    • Default-mode cost per request: C_default = CNY 0.02
    • Default-mode end-to-end latency: T_default = 10 seconds
    • Cost is billed per request, with input and output priced the same
    • The speed improvement applies to both TTFT and TPOT

    Then:

    • Saved time: ΔT = 0.6 × 10 = 6 seconds
    • Break-even value: V* = 0.02 / 6 ≈ 0.0033 CNY/second

    If the business determines that one second of waiting is worth CNY 0.005, the single-request benefit is 6 × 0.005 − 0.02 = CNY 0.01, so low-latency mode should be used. If one second is worth only CNY 0.002, the single-request benefit is 6 × 0.002 − 0.02 = −CNY 0.008, so default mode should be kept.

    4. Routing and Fallback Code

    The code depends only on the Python 3.9+ standard library. The caller must provide a client object whose chat(model, prompt, timeout) method returns text. Model names are injected through environment variables, and keys are read by the client SDK from environment variables rather than written into the code.

    1. import logging
    2. import os
    3. import time
    4. from dataclasses import dataclass
    5. logging.basicConfig(level=logging.INFO, format="%(message)s")
    6. log = logging.getLogger("llm_router")
    7. FAST_MODEL = os.environ.get("LLM_FAST_MODEL", "your-fast-model")
    8. DEFAULT_MODEL = os.environ.get("LLM_DEFAULT_MODEL", "your-default-model")
    9. PRICE_RATIO = 2.0 # Low-latency mode price multiplier
    10. SPEEDUP = 2.5 # Low-latency mode speed multiplier
    11. MIN_FALLBACK_MS = 1500 # Do not fall back when remaining budget is below this value
    12. BREAKER_ERROR_RATE = 0.05 # Trip breaker when fast-mode error rate exceeds this value
    13. BREAKER_WINDOW = 100 # Count the most recent N fast-mode calls
    14. BREAKER_COOLDOWN_S = 600 # Breaker cooldown duration (seconds)
    15. class FastBreaker:
    16. def __init__(self):
    17. self.results = []
    18. self.open_until = 0.0
    19. def allow(self) -> bool:
    20. return time.monotonic() >= self.open_until
    21. def record(self, ok: bool) -> None:
    22. self.results = (self.results + [ok])[-BREAKER_WINDOW:]
    23. if len(self.results) >= BREAKER_WINDOW:
    24. error_rate = self.results.count(False) / len(self.results)
    25. if error_rate > BREAKER_ERROR_RATE:
    26. self.open_until = time.monotonic() + BREAKER_COOLDOWN_S
    27. self.results.clear()
    28. log.warning("event=breaker_open error_rate=%.3f", error_rate)
    29. breaker = FastBreaker()
    30. @dataclass
    31. class Request:
    32. request_id: str
    33. kind: str # "interactive" or "batch"
    34. prompt: str
    35. budget_ms: int # End-to-end timeout budget (milliseconds)
    36. max_cost: float # Per-request cost cap (CNY)
    37. est_default_cost: float # Historically estimated default-mode cost (CNY)
    38. est_default_latency_ms: float # Historical P95 latency for default mode (milliseconds)
    39. value_per_ms: float # Business value of waiting per millisecond (CNY)
    40. def choose_mode(req: Request) -> str:
    41. if req.kind != "interactive" or not breaker.allow():
    42. return "default"
    43. if req.est_default_cost * PRICE_RATIO > req.max_cost:
    44. return "default"
    45. saved_ms = req.est_default_latency_ms * (1 - 1 / SPEEDUP)
    46. extra_cost = req.est_default_cost * (PRICE_RATIO - 1)
    47. if saved_ms * req.value_per_ms <= extra_cost:
    48. return "default"
    49. return "fast"
    50. def run(client, req: Request) -> str:
    51. mode = choose_mode(req)
    52. model = FAST_MODEL if mode == "fast" else DEFAULT_MODEL
    53. started = time.monotonic()
    54. fallback = False
    55. try:
    56. text = client.chat(model=model, prompt=req.prompt, timeout=req.budget_ms / 1000)
    57. if mode == "fast":
    58. breaker.record(True)
    59. except Exception as exc: # In production, narrow this to the provider SDK's specific exception types
    60. if mode == "fast":
    61. breaker.record(False)
    62. elapsed_ms = (time.monotonic() - started) * 1000
    63. remaining_ms = req.budget_ms - elapsed_ms
    64. if mode != "fast" or remaining_ms < MIN_FALLBACK_MS:
    65. log.error("event=request_failed id=%s mode=%s err=%s",
    66. req.request_id, mode, type(exc).__name__)
    67. raise
    68. fallback = True
    69. text = client.chat(model=DEFAULT_MODEL, prompt=req.prompt,
    70. timeout=remaining_ms / 1000)
    71. elapsed_ms = (time.monotonic() - started) * 1000
    72. log.info("event=done id=%s mode=%s fallback=%s elapsed_ms=%.0f",
    73. req.request_id, mode, fallback, elapsed_ms)
    74. return text

    The breaker state in the code is stored in process memory. In multi-process or multi-machine deployments, put the breaker counters in shared storage such as Redis. Otherwise, each process keeps its own statistics, and the breaker effect will be weaker than expected.

    5. Monitoring Thresholds and Fallback Checklist

    The thresholds below are starting values. It is recommended to collect two weeks of baseline data from default mode first, then calibrate against the baseline.

    Metric Alert threshold Action
    Low-latency mode P95 TTFT Exceeds 80% of the budget for that request class for 5 minutes Alert; check queueing and concurrency
    Low-latency mode P95 TTFT Exceeds 100% of the budget for 5 minutes Disable low-latency routing for that request class
    Low-latency mode P95 TPOT Rises 30% above baseline for 10 minutes Alert; check provider service status
    Fast-mode error rate Exceeds 2% for 5 minutes Alert; manually confirm the cause
    Fast-mode error rate Exceeds 5% in the most recent 100 calls Trip the breaker for 10 minutes; already implemented in the code
    Fallback rate More than 10% of requests trigger fallback Check low-latency mode capacity; lower the routing share if necessary
    Daily cost Reaches 80% of the daily budget Alert; review high-cost request types
    Daily cost Reaches 100% of the daily budget Stop adding low-latency routing; keep default mode only

    Fallback and logging requirements to confirm item by item before launch:

    1. When fast mode returns an error or times out, fall back to default mode only if the remaining budget is greater than 1.5 seconds.
    2. Mark fallback responses in logs with fallback=true so fallback reasons can be counted.
    3. For each request, record request_id, request type, actual mode, model name, whether fallback occurred, TTFT, total latency, input and output token counts, and estimated cost.
    4. Do not log prompt text, keys, or user identity information. If troubleshooting is needed, redact the content before storage.
    5. Sample fallback requests every week and review their outputs to confirm that degradation has not significantly affected result quality.

    6. Common Mistakes and Risks

    • Looking only at average latency. When the average drops, long-tail requests may still be slow. Observe P95 and P99 as well.
    • Assuming low-latency mode is cost-effective for all requests. Batch jobs and short-output requests save little time, while the extra cost ratio stays the same, so they are usually not cost-effective.
    • Ignoring output differences caused by degradation. Different models may use different wording and structure, and the post-fallback experience needs separate evaluation.
    • Treating multipliers as guarantees. A 2× price and 2.5× speed are only assumptions. Run an A/B test with a small share of real traffic first, then decide the routing share.