Sub topic 12
Handling Failures in the Middle of a Stream
This chapter assumes you know the retry basics from earlier chapters: retryable versus permanent errors, exponential backoff with jitter, and attempt limits. It also assumes you have used a streaming LLM API and can read Python async code.
Why streams fail differently
A non-streaming call has two outcomes. You get a complete response, or you get an error and nothing else. A streaming call adds a third: some of the response arrives, then something goes wrong.
The cause is the order of events. The server sends the HTTP status line and headers first. For a successful stream, that status is 200. Everything after it is a sequence of chunks, usually server-sent events (SSE). If the provider fails after the first chunk, it can no longer change the status code. Three things can happen instead:
- The connection drops, and your code sees an exception while reading the next chunk.
- The server sends an error event inside the stream, and your SDK raises an exception or hands you an error object.
- The stream goes quiet, with no data and no close, until something times out.
This breaks a habit from earlier chapters. Checking resp.status_code is no longer enough, because a 200 response can still fail. The retry logic has to live around the reading of the stream, not only around opening it.
The ways a stream can end badly
| What you observe | Likely cause | Usual action |
|---|---|---|
| Exception while iterating (reset, read error) | Network drop, proxy or load balancer closing the connection | Retry |
| No chunk for longer than your idle limit | Stalled connection, overloaded provider | Cancel and retry |
| Error event in the stream (for example "overloaded") | Provider-side failure after the stream started | Retry, as with a 5xx |
| Stream ends cleanly, finish reason is `length` | Output hit the token limit | Not an error. Raise the limit or continue |
| Stream ends cleanly, finish reason is a content filter | Policy block on the output | Surface it. A retry will usually give the same result |
| Stream ends with no finish reason at all | Truncated stream | Treat as interrupted |
The last row matters most. A closed connection is not proof of success. Always check that the stream reported a normal finish reason before you treat the text as complete.
Timeouts for streams
A single total timeout fits poorly. A long answer can legitimately take a minute of wall-clock time while chunks arrive steadily. A dead connection can sit silent for the same minute. Use two separate limits:
- An idle timeout (also called a per-chunk or read timeout). This is the longest you will wait for the next chunk. A few seconds is typical once tokens are flowing.
- A deadline for the whole request. This is the cap from the timeouts chapter, and retries must still fit inside it.
The time before the first token is often longer than the gaps between later tokens, because the model may still be processing a long prompt. Some applications give the first chunk a larger limit than the rest. In httpx, the read timeout is a per-read idle limit, not a total limit, so httpx.Timeout(connect=5.0, read=10.0, write=10.0, pool=5.0) gives you idle behavior without extra code. Most SDKs expose a similar setting.
Choosing a recovery strategy
When a stream breaks after you have received some text, you have three options.
- Retry from scratch. Discard the partial output and send the same request again. It is simple and works with every provider. The cost is that you pay for the discarded tokens, and the new answer will differ from the first one because sampling is not deterministic.
- Continue from the partial output. Send the partial text back and ask the model to carry on. Some APIs let you end the message list with a partial assistant message that the model continues. Others do not, and then you must ask in a user message, which tends to produce repeated or oddly joined text. Use this only for long outputs where restarting is costly, and test the seams.
- Surface the partial result. Show or return what you have, clearly marked as incomplete. This suits chat interfaces and cases where partial text is still useful.
The default is to retry from scratch for short responses. Switch strategy only when responses are long enough that wasted tokens or latency hurt.
Retrying a stream from scratch
The code below uses the same pieces as earlier chapters: a bounded loop, exponential backoff, and full jitter. It adds an idle timeout on each chunk. The stream is simulated with an async generator so the example runs without an API key. In a real application, open_stream would return your SDK's async stream, mapped to text chunks.
import asyncio
import random
class StreamInterrupted(Exception):
"""Raised when a stream breaks. Carries the text received so far."""
def __init__(self, partial: str):
super().__init__("stream interrupted")
self.partial = partial
# Extend this tuple with your client's transport errors,
# such as httpx.TransportError or the SDK's connection error.
TRANSIENT = (asyncio.TimeoutError, ConnectionError)
async def collect(stream, idle_timeout: float) -> str:
parts = []
iterator = stream.__aiter__()
while True:
try:
chunk = await asyncio.wait_for(iterator.__anext__(), timeout=idle_timeout)
except StopAsyncIteration:
return "".join(parts)
except TRANSIENT as exc:
raise StreamInterrupted("".join(parts)) from exc
parts.append(chunk)
async def stream_with_retries(open_stream, max_attempts=3, idle_timeout=2.0,
base=0.2, on_reset=None) -> str:
for attempt in range(1, max_attempts + 1):
try:
return await collect(open_stream(), idle_timeout)
except StreamInterrupted as exc:
if attempt == max_attempts:
raise
if on_reset is not None:
on_reset(attempt, exc.partial)
await asyncio.sleep(random.uniform(0, base * 2 ** (attempt - 1)))
calls = {"n": 0}
async def fake_tokens(fail: bool):
for word in ["The ", "quick ", "brown ", "fox."]:
await asyncio.sleep(0.05)
if fail and word == "brown ":
raise ConnectionError("connection reset by peer")
yield word
def open_stream():
calls["n"] += 1
return fake_tokens(fail=calls["n"] == 1)
async def main():
text = await stream_with_retries(
open_stream,
on_reset=lambda attempt, partial: print(f"attempt {attempt} failed after {partial!r}"),
)
print("final:", text)
asyncio.run(main())The first attempt fails after "The quick ". The on_reset callback is where a user interface would clear the partly drawn answer. The second attempt succeeds, and the function returns only the text from the successful attempt. Partial text from a failed attempt is never mixed into the result.
A few points about this design:
- The idle timeout cancels a stalled read with
wait_for, which counts as an interruption and consumes one attempt. - Errors that arrive before the first chunk can use the same path. A stream that fails to open is just a stream that was interrupted with an empty partial result.
- The attempt limit and deadline still apply. In production, also check the overall deadline before each new attempt, as in the timeouts chapter.
Check how the stream finished
A clean end of stream does not mean the answer is whole. Most APIs report why generation stopped, for example stop, length, or a content filter. Handle each one on purpose:
def finish_action(finish_reason):
if finish_reason in ("stop", "end_turn"):
return "accept"
if finish_reason == "length":
return "truncated: raise the output limit or continue"
if finish_reason in ("content_filter", "refusal"):
return "surface to the caller; retrying rarely helps"
return "interrupted: treat as a transport failure and retry" # None or unknown
for reason in ("stop", "length", "content_filter", None):
print(reason, "->", finish_action(reason))The exact reason strings differ by provider. Check your provider's documentation and map its values to these four outcomes.
Side effects and idempotency
Retrying a stream is safe when the request only generates text. It is not automatically safe when your application does something with the text while it streams. Examples include sending each sentence to a text-to-speech service, writing to a database, or forwarding chunks to another user. After a restart, the model may produce different words, so the new stream will not line up with what you already sent.
Two rules help:
- Buffer first, act later. Do anything irreversible only when the stream has finished with a normal reason.
- If you must forward chunks live, make the receiver able to discard them. Send a reset signal on retry, and have the client replace its display instead of appending.
Common errors
- Putting retries only around the call that opens the stream, so mid-stream failures bypass them.
- Appending the retried stream onto the partial text, which duplicates the beginning of the answer.
- Using one large total timeout and no idle timeout, so a dead connection hangs until the limit expires.
- Treating a truncated stream with no finish reason as a success.
- Retrying a content-filter finish, which wastes attempts and cost.
Exercise
A chat app streams answers to the browser as they are generated. The connection drops after 300 tokens have been shown, and your code retries from scratch. Name two things the app must do so the user does not see a corrupted answer, and one condition under which you would stop retrying.
Show answer
First, tell the browser to discard or clear the 300 tokens already shown (a reset event), so the new stream replaces the old text instead of being appended to it. Second, accumulate any tool-call arguments or other side-effect data in a buffer and act only after a normal finish reason, so a retry cannot cause duplicate actions. Stop retrying when the attempt limit is reached or the overall deadline would be exceeded, and then show the error or the partial text marked as incomplete. A finish reason of content filter is another stopping condition, because retrying will likely give the same result.