LLM Latency: Why Faster Tokens Do Not Mean Faster Tasks
Lightweight models are often marketed as fast because they offer faster per-token generation and lower prices, but end-to-end task latency depends on first-token latency, output throughput, total output tokens, queueing, timeouts, and retries. This article explains how to measure these components separately, diagnose common latency gaps, and apply streaming, task splitting, output budgets, retry controls, and evaluation practices for model selection and cloud deployment.
1. The Problem: Speed Metrics Are Often Mixed Together
Model vendors commonly describe lower-tier models with terms such as “lightweight,” “fast,” and “economical.” These terms usually point to two things: faster per-token generation and a lower call price. They do not promise that a task will take less total time to complete.
Many developers conflate these concepts. When they see the word “fast,” they assume the entire request will finish sooner. In reality, the duration of a call depends on how much content the model generates for that task, not only on how many tokens it can emit per second.
Within the same model family, a lightweight tier and a flagship tier may show the following differences on the same task:
- The lightweight tier has higher per-token speed, but generates longer intermediate reasoning content, so the overall duration may actually be longer.
- The lightweight tier produces lower-quality output, requiring multiple rounds of self-correction and increasing total task time.
- The lightweight tier is allocated fewer service resources, so queueing during peak periods becomes longer and first-token return is slower.
Therefore, when judging whether a model is fast or slow, “speed” needs to be split into metrics that can be measured separately.
2. Breaking “Fast” into Measurable Metrics
Evaluating a model call requires at least the following four metrics:
- First-token latency (TTFT): The time from sending a request to receiving the first output token. It reflects queueing, network, and preprocessing overhead, and directly affects interactive experience.
- Output throughput (TPS): The number of tokens output per second after the first token is received. It reflects speed during the generation phase.
- Total output tokens: The total number of tokens the model generates to complete the task, including implicit reasoning content and the final answer.
- End-to-end latency: The complete time from task start to task end.
End-to-end latency can be approximated as:
end-to-end latency ≈ queue wait + first-token latency + total output tokens / output throughput + tool-call wait + retry overhead
This formula shows that even if output throughput doubles, end-to-end latency can still increase if total output tokens more than double.
The following example uses a streaming interface to collect these metrics. Here, stream_fn represents the streaming call function actually used in the project and should be replaced according to the real SDK. Token counts are approximated by the number of returned chunks; for exact statistics, use the usage fields returned by the model.
import timedef measure_task(stream_fn, model, messages):"""Collect first-token latency, total latency, and approximate throughput for a single call."""start = time.monotonic()first_token_at = Nonechunk_count = 0for chunk in stream_fn(model=model, messages=messages):now = time.monotonic()if first_token_at is None:first_token_at = nowchunk_count += 1end = time.monotonic()if first_token_at is None:return {"ttft": None, "total": end - start, "chunks": 0, "tps": 0.0}generation_time = end - first_token_attps = chunk_count / generation_time if generation_time > 0 else 0.0return {"ttft": first_token_at - start,"total": end - start,"chunks": chunk_count,"tps": tps,}
Single-sample measurements fluctuate significantly. For formal comparisons, call the same batch of tasks multiple times and record P50 and P95 percentiles rather than looking only at averages or single results.
3. Common Reasons End-to-End Latency Deviates from Intuition
3.1 Different Reasoning Lengths
Some models generate a long reasoning process before answering. For the same task, a lightweight tier may output two thousand tokens while a flagship tier needs only five hundred. Even if the former outputs more tokens per second, total latency may still be longer.
The way to judge this is to count total output tokens, not just throughput. If a model’s per-task token count is clearly higher, end-to-end latency will be longer even if its nominal speed is high.
3.2 Server Resources and Queueing
Low-price or lightweight models are often hosted on shared resources. As request volume increases, queueing time grows, and both first-token latency and tail latency rise. This kind of fluctuation is more noticeable when a model has just been released and traffic is concentrated.
Service providers usually do not disclose capacity planning. What developers can do is monitor queueing time for their own requests and adjust calling strategies by time period.
3.3 Gateways and Connection Timeouts
Long requests pass through multiple components such as the client, proxy, load balancer, and gateway. These components usually have idle connection timeouts or maximum request durations. A request with a long inference time may be cut off by an intermediate layer after tens of seconds to several minutes, and the client sees a connection interruption or a 5xx error.
Such errors are easily mistaken for model failures. When troubleshooting, distinguish three cases: the model returned an error, an intermediate layer closed the connection, and the client itself timed out.
3.4 Client Retries Amplify Latency
When the client encounters a timeout and retries automatically, the same task may be executed multiple times. Without idempotency controls, this can also produce duplicate output or duplicate billing. The more retries there are, the longer the total latency perceived by the user.
4. Engineering Responses: Streaming, Timeouts, and Retries
Use Streaming Output to Keep Connections Active
Streaming output lets the server continue returning data during generation, reducing the probability that an intermediate layer closes the connection because of idleness. For user-facing interactive scenarios, streaming output also lets users see content earlier and improves perceived latency.
Split Long Tasks
Split a large task into multiple stages, call the model separately for each stage, and save intermediate results. In this way, even if one step times out, only that step needs to be retried rather than starting over from the beginning.
Limit the Output Budget
Specify output length and reasoning depth in the prompt, and set a reasonable maximum output token count. For example, asking the model to give a conclusion first and then list key evidence can reduce unnecessary expansion. The output budget should be determined together with quality testing; do not sacrifice result reliability only to shorten latency.
Exponential Backoff and Idempotency Controls
The following example shows retry logic with a timeout and exponential backoff. For tasks that produce side effects, include an idempotency key in the request to ensure the server executes only once.
import asyncioimport randomasync def call_with_retry(call, timeout_s=300, max_retries=3):"""Set a timeout for an async call and retry with exponential backoff after failure."""for attempt in range(max_retries + 1):try:return await asyncio.wait_for(call(), timeout=timeout_s)except (asyncio.TimeoutError, ConnectionError):if attempt == max_retries:raisedelay = min(2 ** attempt, 30) + random.random()await asyncio.sleep(delay)
The timeout should be slightly longer than the maximum latency allowed by the business and should reference the timeout configuration of intermediate layers. If the intermediate layer’s idle timeout is short, rely on streaming output to keep the connection alive rather than simply extending the client timeout.
5. Model Selection Evaluation Framework
When choosing a model, do not look only at nominal speed or price. Build an evaluation set aligned with the business and judge models across the following dimensions:
| Dimension | Measurement | Focus |
|---|---|---|
| First-token latency | P50, P95 | Interactive experience |
| Output throughput | Generated tokens divided by generation time | Long-text generation efficiency |
| Total output tokens | Usage statistics per task | Hidden reasoning cost |
| End-to-end latency | Full time from task start to end | Batch processing and automation workflows |
| Task completion rate | Proportion completed without timeout or error | Stability |
| Quality score | Human or rule-based scoring | Result usability |
| Cost per task | Calculated from token usage and unit price | Economics |
The evaluation set should include 50 to 200 real tasks, covering common scenarios and edge cases. Tests should be run at different times to observe how load changes affect results.
6. Reference Architecture for Cloud Deployment
When deploying such tasks on cloud platforms such as Baidu AI Cloud, a general asynchronous architecture can be used:
- Receive tasks through a message queue, and have worker nodes consume and call the model, reducing timeout pressure on the request side.
- Deploy worker nodes on a container platform and autoscale based on queue length.
- Use a logging service to record first-token latency, total latency, token usage, and error codes for each call.
- Set thresholds for P95 latency and timeout rate through monitoring and alerting, and trigger degradation or switching strategies.
An asynchronous architecture decouples “user waiting” from “model execution.” After submitting a task, the user can immediately receive a task ID and obtain the result later through a callback or polling. This approach is suitable for long-running tasks that do not require high real-time responsiveness.
7. Implementation Checklist
- Metrics: Record first-token latency, throughput, total output tokens, and end-to-end latency together.
- Testing: Use real task samples, repeat sampling across time periods, and report percentiles.
- Timeouts: Clarify intermediate-layer timeout configurations, and use streaming output or asynchronous execution for long tasks.
- Retries: Set maximum retry counts and backoff strategies, and enable idempotency controls for write operations.
- Cost: Track token usage per task and include output length in cost accounting.
- Decision-making: Use end-to-end latency, completion rate, and quality score as primary criteria; treat a single nominal speed value only as a reference.
Model speed is a composite result of multiple metrics. Only by measuring first-token latency, throughput, output length, and stability separately can you determine whether a given tier fits a specific workload.
