Tutorial

Handling LLM Timeouts and Partial Responses

Set timeouts that match the task, keep partial output useful when a call fails mid stream, and retry only the work that is safe to repeat.

On this page

  1. Introduction
  2. Why a Single Fixed Timeout Fails
  3. Streaming Changes What a Timeout Means
  4. Keeping Partial Output Useful
  5. Retrying Only Idempotent Work
  6. Cancelling Cleanly
  7. Debouncing and Deduplication
  8. Graceful Degradation
  9. Observability for Timeouts
  10. Testing Timeout Paths
  11. Sources

Introduction

A model call is a remote request with a long and highly variable duration, often streaming for tens of seconds. Treating it like a fast API call is how you get hung workers, duplicate charges and users staring at a frozen screen. Timeouts must reflect the task, partial output must be handled rather than discarded, and retries must be limited to work that is safe to repeat. Getting these three right is the difference between a flaky feature and a dependable one.

Why a Single Fixed Timeout Fails

A timeout that is generous enough for a long generation will let a hung connection occupy a worker for minutes, while one tuned for short answers kills legitimate long ones. Distinguish connect timeout from read timeout from total deadline, because a connection that opens quickly but never returns needs a read timeout, not a longer total. Set the total deadline from the task: a classification may need five seconds, a long report a minute. The deadline is a budget the whole call chain must respect.

import httpx, asyncio

class IdleTimeout(Exception):
    pass

async def stream_with_idle_timeout(url: str, payload: dict, idle_s: float, total_s: float):
    chunks: list[str] = []
    async with httpx.AsyncClient(timeout=httpx.Timeout(total_s, connect=5.0)) as client:
        async with client.stream("POST", url, json=payload) as resp:
            resp.raise_for_status()
            it = resp.aiter_text()
            while True:
                try:
                    chunk = await asyncio.wait_for(it.__anext__(), timeout=idle_s)
                except asyncio.TimeoutError:
                    # No bytes for idle_s seconds: treat as dead, keep what we have.
                    raise IdleTimeout(f"no data for {idle_s}s after {len(chunks)} chunks")
                except StopAsyncIteration:
                    break
                chunks.append(chunk)
    return "".join(chunks)

Streaming Changes What a Timeout Means

Once tokens stream, a long total duration is normal as long as bytes keep arriving. The useful signal is inactivity: if no chunk arrives for N seconds, the connection is likely dead even though total elapsed time is small. Implement a read idle timeout that resets on each chunk, and a separate absolute cap for pathological cases. Without an idle timeout, a half open socket that never sends data hangs until the OS gives up, which can be many minutes later.

import random

async def generate_with_fallback(primary, fallback, prompt: str, attempts: int = 2):
    last = None
    for i in range(attempts):
        try:
            return {"text": await primary(prompt), "degraded": False}
        except (IdleTimeout, httpx.TimeoutException) as e:
            last = e
            await asyncio.sleep((2 ** i) + random.random())  # exponential backoff + jitter
    # Fall back rather than failing the feature.
    try:
        return {"text": await fallback(prompt), "degraded": True, "reason": str(last)}
    except Exception as e:
        return {"text": "The model is unavailable right now. Please retry.", "degraded": True, "reason": str(e)}

Keeping Partial Output Useful

When a stream is interrupted, the tokens already produced often contain most of an answer and are worth keeping. Buffer the partial text, mark the response as truncated, and let the interface render what exists with a clear indication that generation stopped. Decide per use case whether a partial answer is acceptable: a chat reply usually is, a JSON object destined for a parser usually is not. Never present a truncated structured payload as complete, because downstream code will act on missing fields.

Retrying Only Idempotent Work

A retry is safe only if repeating the work cannot duplicate a side effect. Reading a model answer is safe to retry if you discard the first attempt; an action the model triggers, such as sending an email, is not, so separate generation from execution. Use an idempotency key when the provider charges per request so a retry is recognised and not double billed. Cap retries with exponential backoff and jitter, and treat a timeout as distinct from a rate limit because their backoff strategies differ.

Cancelling Cleanly

When the user navigates away or the deadline passes, propagate cancellation to the upstream request so the provider stops generating and you stop paying. Thread an abort signal through the call, the HTTP client and any streaming loop, and close the response body on abort so sockets are released. Clean up timers and listeners in a finally block to avoid leaks, because long running processes that leak aborted requests eventually exhaust file descriptors.

Debouncing and Deduplication

Users type faster than models respond, so a naive interface launches a call per keystroke and pays for answers nobody reads. Debounce input and cancel the in-flight request when a newer one arrives. Deduplicate identical in-flight requests with single flight so two callers asking the same question share one generation. Both reduce load and improve perceived speed, and both are cheaper than buying more capacity.

Graceful Degradation

When the primary model times out, a fallback path keeps the feature alive: a smaller faster model, a cached answer, a template response, or an explicit apology with a retry button. Choose the fallback by task, since a summariser can fall back to an extractive summary while a structured extractor may have to fail. Log every degradation with the reason so you can see how often the happy path is unavailable, and alert when the rate rises.

Observability for Timeouts

Record timeout type, the deadline configured, the elapsed time at failure, and whether any output was produced. Distinguish provider slowness from your own network issues by measuring the time to first byte separately from total time. Track the timeout rate by model and by prompt version, because a prompt that produces very long outputs will time out more often than a concise one. These metrics turn timeout handling from guesswork into tuning.

Testing Timeout Paths

Use a server that can delay or drop responses to test that connect, read and idle timeouts trigger as intended, that a partial stream is retained and marked, and that cancellation aborts upstream work. Assert with a fake clock that backoff delays grow and that retries stop at the cap. Timeout bugs surface only under failure, so the only way to trust the handling is to simulate the failures deliberately in tests.

Sources

Sources: httpx timeouts, MDN AbortController, Rust cancellation safety.

FAQ

What timeout should I set for a streaming call?
Use an idle timeout that resets on each chunk plus a separate absolute cap. Total duration grows with answer length, so idle time is the reliable signal that a connection has died.
Is retrying a timed out model call always safe?
Only if repeating it cannot duplicate a side effect. Separate generation from execution, use an idempotency key, and discard the first partial attempt before retrying.

Related Examples