Long-Running LLM Inference Without Dropped Connections: Engineering Practices for Timeouts and Stability
This article explains why long-running LLM inference requests get cut off, how to separate latency problems from connection design problems, and which engineering patterns keep requests stable. It covers the timeout chain, streaming, asynchronous task handling, idempotent retries, prompt-level cost control, and observability.
1. The Root Cause: Why Long Inference Requests Get Cut Off
Inference time depends on the number of tokens the model generates. A complex task that involves multi-step reasoning, long outputs, or tool calls can take several minutes for a single request. Such requests pass through multiple infrastructure layers, and each layer may set an idle timeout or a maximum total duration. When any one of these layers expires first, the client receives a closed connection or a gateway error, even though the server may still be computing.
“Slow inference” and “broken inference” are different problems. Slow inference is a performance issue. Broken inference is a link design issue. The two often occur together, but they need to be investigated separately.
2. Breaking Down Latency Metrics
When you measure inference experience, distinguish at least the following three metrics.
- Time to First Token (TTFT): The time from sending a request to receiving the first output token. It determines whether users perceive the system as responsive.
- Tokens Per Second (TPS): The number of output tokens generated per second during the generation phase. It determines how quickly long outputs finish.
- End-to-end latency: The total time from the start of the request to its completion. It equals queueing time plus prefill time plus decoding time.
Each metric has a different bottleneck. TTFT depends largely on queue length, input length, and prefill computation. TPS depends largely on model size, batching strategy, and memory bandwidth. End-to-end latency combines both of these with output length. Looking at a single metric can lead to a wrong diagnosis.
3. Checking the Timeout Chain Layer by Layer
A request typically passes through the following stages.
- The client’s read timeout and total timeout settings
- Local or enterprise proxies and gateways
- Load balancers and edge nodes
- The inference service’s queue and worker processes
Each stage may have its own idle timeout, which closes a connection if no data is transmitted within a set period. If the server writes no bytes to the connection during the model’s internal reasoning phase, before any tokens are generated, intermediate devices may classify the connection as idle and cut it off.
To investigate, you can follow these steps.
- Use packet captures or access logs to find the moment the connection drops, and compare that time with the timeout values configured at each layer.
- Reproduce the problem both by connecting directly to the server and by going through the gateway. This shows which layer closes the connection.
- Record the HTTP status code at the time of disconnection. A 5xx error usually indicates an upstream timeout or service unavailability, so confirm it with gateway logs.
4. Keeping Connections Alive with Streaming Output
The most direct way to keep a connection alive is to send data while the response is still being generated. Streaming output lets the server push content continuously, token by token or chunk by chunk. Data keeps flowing on the connection, so the idle timeout does not trigger.
The following pseudocode is illustrative and shows the logic structure.
def stream_completion(request, idle_timeout=30):response = http_client.post_stream(url, body=request)last_chunk_at = now()for chunk in response.iter_chunks():if now() - last_chunk_at > idle_timeout:raise TimeoutError("Connection idle time exceeded threshold")last_chunk_at = now()yield parse_delta(chunk)
While the model is reasoning internally and has not yet produced visible tokens, the server can also send comment frames or heartbeat frames at regular intervals, provided the protocol allows them. The client should recognize and ignore these frames so they are not counted as business content.
Streaming only solves idle timeouts at intermediate devices. It cannot bypass a maximum total duration set by a gateway. If total duration is limited, you still need to split the task or switch to an asynchronous model.
5. Asynchronous Task Pattern
Synchronous long-lived connections are not a reliable choice for tasks that clearly take several minutes. The recommended approach splits the request into two steps: submission and retrieval.
- The client submits a task, and the server immediately returns a task ID.
- The task runs in a background queue, and the result is written to persistent storage.
- The client retrieves the task status and final result by polling or through a callback.
This pattern separates connection lifetime from task execution time. Generic infrastructure such as message queues and object storage can support it without relying on vendor-specific features.
An example API shape looks like this:
POST /tasks -> 202 Accepted, {"task_id": "..."}GET /tasks/{id} -> 200 OK, {"status": "running", "progress": 0.4}GET /tasks/{id}/result -> 200 OK, final output
6. Client-Side Fault Tolerance
Retries must follow idempotency principles. Even with identical input, a generation request may produce different output each time, and repeated execution wastes billing and compute resources. For this reason, requests should carry an idempotency key, which the server uses to deduplicate.
A recommended retry strategy includes the following points.
- Retry only on retryable errors, such as dropped connections and gateway timeouts. Return deterministic errors, such as invalid parameters or content policy violations, immediately.
- Use exponential backoff with random jitter to prevent many clients from retrying at the same time and creating traffic spikes.
- Set a maximum number of retries and a total time budget. Once the budget is exhausted, return a clear error.
- Keep any partial output already received. On retry, use it as context to continue generation instead of starting over.
The backoff interval can be expressed as follows.
delay = min(base * 2 ^ attempt, max_delay) * random(0.5, 1.0)
7. Reducing Inference Cost at the Prompt Level
Output length and reasoning depth directly affect latency, so prompt design is also part of stability engineering. You can take the following steps.
- Specify the output format and a length limit for the task to prevent unbounded expansion.
- Break complex tasks into stages, and have each stage output only its own conclusions.
- Write intermediate results to external storage or task state, instead of keeping everything in one response.
These measures do not change the model’s capabilities, but they reduce the amount generated in each request, making it more likely to finish before a timeout.
8. Building Observability
Without metrics, you cannot tell which layer causes a problem. Collect at least the following data.
- Queue time, TTFT, TPS, and end-to-end latency for each request.
- The configured value of each timeout layer, and how often each one actually triggers.
- Failure rates grouped by status code and error type.
- Disconnection rates grouped by output length bucket.
If the disconnection rate rises noticeably with output length, the problem is concentrated in the timeout chain. If TTFT rises with concurrency, the problem is concentrated in server-side scheduling capacity. These two signals point to different optimizations, so handle them separately.
9. Summary
The stability of long-running inference depends mainly on three things: keeping data flowing on the connection, moving long tasks from synchronous requests to asynchronous tasks, and implementing bounded, idempotent retries on the client. Latency metrics should be observed separately, and the timeout chain should be checked layer by layer. Applying these measures usually improves completion rates for complex tasks. Actual results depend on the deployment environment, so teams should rely on their own monitoring data.
