Troubleshooting Slow LLM Inference and Dropped Connections for Long Requests
When large language model (LLM) services respond slower than expected, or when long-running reasoning tasks are unexpectedly disconnected, the root cause often lies not in the model itself, but in the serving layer. This article provides a structured approach to diagnosing these issues by breaking down latency into measurable metrics like Time To First Token (TTFT), generation speed, and end-to-end time. It then examines why long requests fail—often due to idle timeouts at the client, proxy, or gateway layers—and offers practical engineering solutions including heartbeat mechanisms, asynchronous task queues, resumable execution, and idempotent retries. The article also discusses prompt-level controls to limit output length, the importance of separating quality from speed evaluation, and a set of observability metrics and a checklist to help you identify bottlenecks before they escalate into user-facing incidents.
Introduction
In production environments, LLM-powered applications often exhibit two common issues. First, a lightweight model on the same service may respond more slowly than a standard model under certain conditions or on specific endpoints. Second, complex reasoning tasks that run for an extended duration are sometimes interrupted mid-stream, with the client receiving a gateway error code.
These problems are frequently attributed to the model itself, but in most cases, the root cause lies within the serving layer—specifically, its scheduling policies, quota management, and network paths. To accurately determine which layer is responsible, you first need to break down the notion of “slow” into measurable metrics.
Decomposing “Slowness” into Measurable Metrics
When evaluating LLM response speed, three key metrics are typically tracked:
- Time To First Token (TTFT): The time from request submission to the arrival of the first generated token at the client. This is primarily affected by queueing delays and the computational load of the input-processing (prefill) phase.
- Generation Speed (Tokens Per Second, TPS): The number of tokens generated per second during the output phase. This is largely influenced by memory bandwidth, batch size, and server load during the decoding stage.
- End-to-End Latency: Approximately equal to the sum of TTFT, the output token count divided by TPS, and network round-trip time (RTT).
A lightweight model might consistently underperform a standard model for several reasons:
- Insufficient Resource Pools: A lightweight model sharing a small compute pool with a high volume of requests will experience significantly longer queueing times.
- Oversubscription and Rate Limiting: To manage costs, providers may oversubscribe resources, relying on rate limiting or graceful degradation during peak traffic to maintain overall availability.
- Inconsistent Deployment Environments: Models may reside in different clusters or run on different versions of the inference engine, leading to varying levels of optimization.
- Batching Effects: Under high load, the scheduler may group requests into batches. A single request has to wait for the entire batch to be filled before processing begins.
These are all general mechanisms. To diagnose the specific cause, you must rely on real-world measurement data rather than anecdotal evidence. The following Python code demonstrates a measurement approach that works for any interface supporting streaming output.
import timedef measure_stream(stream_iter):"""Measure TTFT, generation speed, and total latency for a streaming output."""start = time.perf_counter()first_token_at = Nonechunk_count = 0for _chunk in stream_iter:now = time.perf_counter()if first_token_at is None:first_token_at = nowchunk_count += 1 # Approximate token count by chunk countend = time.perf_counter()if first_token_at is None:return {"ttft_s": None, "tps": 0.0, "total_s": end - start}gen_time = end - first_token_attps = chunk_count / gen_time if gen_time > 0 else 0.0return {"ttft_s": first_token_at - start,"tps": tps,"total_s": end - start,}
It is recommended to repeat this measurement for the same task at different times of day and analyze the median and P95 (95th percentile) values. Single measurements are susceptible to transient fluctuations.
Why Long-Running Inferences Break
A disconnection during a long inference task usually means the model is not necessarily at fault; rather, an intermediate network component has determined the connection to be idle or invalid. Common timeout layers include:
- Client Read Timeouts: The client stops waiting for data after a configured period.
- Proxy/Gateway Idle Timeouts: An intermediary closes a connection that has seen no network traffic for a certain duration.
- Load Balancer Duration Limits: The load balancer forcefully ends requests that exceed a maximum time limit.
- Server-Side Task Time Limits: The inference service has a cap on the maximum execution time for a single task.
The idle timeout is the most frequently overlooked culprit. If the model performs a long internal “chain of thought” process without emitting any output, the streaming connection will remain silent. The intermediary, seeing only a lack of data, assumes the connection is stale and terminates it. The client then receives errors like 502, 503, or 504. These errors indicate an interrupted connection, not a failure of the inference process itself.
Engineering Solutions for Long-Task Stability
Addressing these causes requires a multi-faceted approach to the application architecture:
1. Streaming Output and Managing Silence Periods
Streaming output allows data to reach the client as soon as it is generated. For tasks that require significant “thinking time”, the server can periodically send intermediate status messages (e.g., “Processing step two…”) to keep the connection active. Whether to expose this intermediate state depends on the product experience.
2. Heartbeat Mechanism
A server can send a lightweight heartbeat, such as an empty event or a comment line, at fixed intervals to prevent the intermediary from declaring an idle timeout. In the Server-Sent Events (SSE) protocol, comment lines (starting with :) are not parsed as part of the response body by the client. Before implementing this, ensure that both the proxy layer and the client fully support this part of the protocol.
3. Asynchronous Task Pattern
For tasks lasting several minutes or more, a synchronous HTTP connection is inherently fragile. A more robust pattern is to submit the task and immediately receive a task ID. The client can then poll for the result or use a webhook callback. The following example shows a basic polling structure.
import timedef run_long_task(submit, poll, payload, interval=5, max_wait=900):"""Submit a long-running task and poll for the result."""task_id = submit(payload)waited = 0while waited < max_wait:status, result = poll(task_id)if status == "done":return resultif status == "failed":raise RuntimeError(f"Task {task_id} failed")time.sleep(interval)waited += intervalraise TimeoutError(f"Task {task_id} timed out after {max_wait} seconds")
The polling interval is a trade-off. Too short, and you generate unnecessary load; too long, and you increase perceived latency. An exponential backoff strategy—starting with short intervals and gradually increasing them—is often a good balance.
4. Chunked Execution and Checkpointing
Break a complex task into discrete steps and persist the output of each step. If the task fails, it can resume from the last successful step rather than restarting from scratch. This also reduces the execution time of any single request, lowering the probability of triggering a timeout.
5. Idempotency and Safe Retries
Assign a unique request ID to every task. The server can use this ID to de-duplicate requests, ensuring that a client retry—even if the original request succeeded—does not execute the operation twice or generate duplicate charges.
Controlling Inference Length at the Prompt Level
Overly long inference times can often be traced back to prompt design. The following practices help manage output length and scope:
- Explicitly define a strict output length limit, and configure the maximum token count in the API parameters.
- Structure the prompt to request a rigid output format, such as providing a conclusion before its justification.
- For complex, multi-part problems, instruct the model to first produce an execution plan and then tackle each step.
- Remove irrelevant background information that may cause the model to spend tokens on tangential reasoning.
These changes can affect output quality. After adjusting the prompt, always validate the results against a fixed evaluation set to ensure correctness, rather than solely evaluating improvements in response speed.
Evaluating Speed and Quality Separately
A faster response time does not automatically mean better performance. A model that scores high on public benchmarks or internal test sets may not be stable on novel tasks. Overfitting is a critical risk. Models can excel on their training or testing distribution but degrade significantly on out-of-distribution inputs.
Establish an independent evaluation set, retaining sample points not used for any tuning. After every model or parameter change, track the following metrics in tandem:
- Task Accuracy: Whether the output satisfies the business requirements.
- Format Compliance: Whether the output structure adheres to the agreed-upon schema.
- Result Consistency: The stability of a conclusion given multiple runs on the same input.
- Performance Metrics: TTFT, TPS, and end-to-end latency.
Only by considering quality and speed together can you accurately determine if an adjustment is genuinely beneficial.
Designing a Robust Observability Stack
The reliability of long-running tasks depends on continuous monitoring. It is recommended to collect at least the following metrics:
| Metric | Description | Monitoring Focus |
|---|---|---|
| TTFT P50 / P95 | Median and tail latency for first token | Compare across different models and time segments |
| TPS | Token generation speed during output phase | Compare against historical baselines to spot significant drops |
| Silence Duration | Longest period without data flow on a connection | Alert when approaching the intermediary’s timeout threshold |
| Gateway Error Rate | Percentage of requests resulting in 502, 503, or 504 | A sudden spike warrants immediate investigation into network and timeout configurations |
| Task Completion Rate | Percentage of successfully executed tasks versus submitted tasks | Analyze across various task duration brackets |
Cloud platforms like Baidu AI Cloud provide logging and monitoring services that can consolidate these metrics into a unified dashboard. Logs should record the request identifier, model version, submission time, time-to-first-token, and completion time, allowing for easy post-incident analysis.
Actionable Checklist for Implementation
- Use a measurement script to record TTFT and TPS across different times of day for at least one week to identify any time-related patterns.
- Map out all middleware layers a request passes through and document their respective timeout configurations.
- For tasks expected to exceed one minute, assess the feasibility of migrating to an asynchronous processing pattern.
- Implement heartbeats or periodic status updates for streaming interfaces to eliminate long periods of silence.
- Attach idempotency keys to all write-bearing requests.
- Create a fixed evaluation set and run it after every parameter or prompt adjustment.
- Configure alerts for gateway error rates and silence durations to detect issues before they lead to user complaints.
The stability of long-running inference tasks is a collaborative effort between the inference service, the intermediary network, and the client application. By quantifying the issue first and then methodically investigating each layer, you can uncover the true bottleneck and build a reliable and fast AI application.
