Engineering Governance for LLM Inference Latency and Long-Request Disconnects
This article examines why smaller or "faster" LLM variants often underperform their standard counterparts in production, clarifies key latency metrics (TTFT, TPS, end-to-end delay), and presents a reproducible methodology for benchmarking inference performance. It then analyzes the root causes of connection drops during long inference requests and provides a practical engineering solution using streaming output with heartbeat keep-alive mechanisms.
1. Problem Symptoms and Metric Definitions
In real-world usage, different versions of the same model family often produce counterintuitive results. Versions with fewer parameters—positioned as lightweight or fast—frequently deliver worse time-to-first-token (TTFT) and tokens-per-second (TPS) than the standard version. Users experience long waits before the first token appears, or output that arrives in inconsistent bursts. Before discussing such issues, it is necessary to align on metric definitions.
- TTFT (Time To First Token): The time from request submission to receipt of the first output token. It primarily reflects queueing wait, prefill computation, and network path overhead.
- TPS (Tokens Per Second): The number of tokens generated per second during the decoding phase, typically used to measure generation speed. It is primarily affected by memory bandwidth, batching strategy, and kernel efficiency.
- End-to-end latency: The total duration from request submission to completion of the full response. In long inference scenarios, end-to-end latency is the most likely metric to exceed a timeout threshold at some point in the chain.
These three metrics correspond to distinct phases of the request lifecycle. They should be measured and analyzed separately—never reduced to a single average.
2. Why Fewer Parameters Does Not Always Mean Faster
Intuitively, a smaller model should infer faster. This holds roughly true under identical hardware conditions with a single machine and a single request. However, online service performance is determined by multiple interacting factors, including the following.
2.1 Decoding Is Often Memory-Bound
During generation of each token, the model must read a substantial amount of weights and KV cache. A smaller model reduces compute, but decoding speed is frequently limited by memory bandwidth rather than raw FLOPs. If the inference framework has not fully optimized for a new model architecture, actual throughput can fall well below theoretical values.
2.2 Resource Allocation and Batching Strategy
Production servers typically use dynamic batching (e.g., continuous batching) to maximize hardware utilization. If a given model version has too few instances, or if per-instance concurrency parameters are set conservatively, requests queue during peak hours and TTFT rises accordingly. In this case, the model’s computational speed is not the bottleneck—queueing delay is.
2.3 Adaptation Cost for New Architectures
Novel attention mechanisms, mixture-of-experts structures, or other architectural changes generally require matching kernel implementations. If the inference engine has not yet been tuned for the new structure, certain operators fall back to generic implementations, and performance fails to meet expectations. This issue is especially common in the early release period of a new model; subsequent framework optimizations often improve the situation.
2.4 Increased Share of Fixed Overhead
Authentication, content moderation, request routing, logging, and similar steps incur roughly constant latency. When model inference becomes faster, these fixed costs account for a larger share of total latency, making the perceived speedup smaller than expected.
2.5 Quota and Priority Policies
Platforms may apply different quotas, priority levels, or rate-limiting rules to different model versions. Queueing policy directly affects user wait times—even when the underlying compute capability is identical, the perceived speed will differ.
The conclusion is that model specifications cannot be directly equated with production speed. Determining which version is actually faster requires measured data under identical conditions.
3. Reproducible Performance Evaluation Methodology
Benchmarking should produce reproducible results that reflect real traffic patterns. The following principles are recommended.
- Fix input conditions: Standardize input length, maximum output length, temperature, and sampling parameters so that per-request variability does not mask differences between model versions.
- Layer the concurrency tests: Run tests at low, medium, and peak concurrency levels. Many performance problems only emerge under high concurrency.
- Report percentiles: Track P50, P95, and P99. Averages hide long-tail requests, and long-tail requests are the primary source of user complaints.
- Sample across time periods: Run multiple tests at different times of day to distinguish transient jitter from stable differences.
- Separate successes from failures: Timeouts, 5xx errors, and connection resets should be counted independently—do not include only successful request latencies.
Below is a recommended metric tracking checklist:
| Metric | Definition | Primary Concern |
|---|---|---|
| TTFT percentiles | Distribution of time to first token | Queueing and prefill |
| TPS percentiles | Distribution of decoding speed | Resource allocation and kernel efficiency |
| End-to-end latency distribution | Total response duration | Timeout risk |
| Timeout and 5xx ratio | Proportion of failed requests | Pipeline stability |
| Tokens per output | Generation length distribution | Unbounded generation presence |
4. Why Long Inference Requests Get Disconnected
A long inference request traverses multiple components: client, load balancer, gateway or reverse proxy, and inference service. Each component typically sets an idle timeout—a connection that receives no data for a specified period is closed.
When a reasoning model spends an extended period generating internal reasoning steps without producing visible output text, the connection remains silent. The front-most component with the shortest timeout threshold will terminate the connection first. From the client’s perspective, this appears as a 502, 503, or 504 error, or a connection reset.
Several points deserve particular attention.
- Timeout thresholds are set by the deployment side. Common values range from tens of seconds to several minutes. The exact numbers must be confirmed with the service provider or operations team—do not assume from experience.
- Timeouts across layers can be inconsistent. Client, proxy, and server may each have different timeout parameters. The effective timeout is the shortest one in the chain.
- A disconnect does not mean the computation failed. The server may have already completed substantial work, but the result never reaches the client. If the client simply retries, it may cause duplicated computation, duplicated billing, or even inconsistent results.
Therefore, solving long-request disconnects requires both keeping the connection alive and designing a proper task submission and recovery mechanism.
5. Engineering Solutions
5.1 Streaming Output with Heartbeat Keep-Alive
Streaming output (e.g., SSE-based protocols) can continuously push data during generation. For inference phases where no output is produced for a long time, the server can periodically send a heartbeat comment line so intermediary nodes consider the connection still active. Below is an illustrative implementation where generate_tokens represents any asynchronous generation function:
import asyncioasync def stream_with_heartbeat(generate_tokens, interval=15):"""Send a heartbeat when no data has been generated for `interval` seconds to keep the connection alive."""queue = asyncio.Queue()async def producer():try:async for token in generate_tokens():await queue.put(("data", token))finally:# Notify the consumer that generation has finished, whether successful or notawait queue.put(("done", None))task = asyncio.create_task(producer())while True:try:kind, payload = await asyncio.wait_for(queue.get(), timeout=interval)except asyncio.TimeoutError:# Lines starting with a colon are comments in SSE and are ignored by the clientyield ": heartbeat\n\n"continueif kind == "done":breakyield f"data: {payload}\n\n"await task
Note that in this example, an exception only notifies the consumer to stop via finally—the error is not passed to the client. In a production system, errors should be sent to the client as distinct events; otherwise, the client cannot distinguish between a normal completion and a server-side failure.
