Handle disconnects and slow streams
Keep streams responsive through proxies and stop upstream work when the client goes away.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 11 minutes to read.
In short
Streams fail in ways normal requests do not: proxies buffer them, idle connections are closed, and users leave mid-answer. A healthy stream disables buffering, sends heartbeats during long pauses and measures time to first token. When the client goes away, the server should stop the model call too, and once the 200 status is sent, errors must travel as events.
Explained simply
Streaming works nicely on your laptop. In production, the response passes through load balancers, reverse proxies and sometimes a CDN. Some of them collect the whole response before passing it on. That is called buffering, and it turns your live stream back into one late blob.
Long silences cause a second problem. A model may think for many seconds before the first word. Many proxies close connections that stay quiet for too long. A heartbeat, a tiny message sent every few seconds, keeps the line busy without showing anything to the user.
Users also leave. They press Stop, close the tab or lose signal on a train. If your server keeps asking the model for tokens after that, you pay for text nobody reads. The server should notice the disconnect and stop the model call too.
Finally, errors behave differently mid-stream. The status code 200 goes out with the first bytes. If the model fails after that, you cannot switch to 500. Instead you send an error event, and the UI keeps the partial answer and offers a retry.
Press Play on a diagram to walk through it one step at a time.
- 1Browser aborts
AbortController.abort() closes the fetch
- 2Server sees disconnect
Generator is cancelled or next write fails
- 3Cleanup runs
finally block closes the upstream stream
- 4Model call stops
No more tokens billed
- 5Partial answer kept
Saved and marked as stopped
- Status can be 401, 404, 422, 503
- Body is a normal JSON error
- Client checks response.ok
- Nothing to show yet
- Status is already 200
- Send event: error, then close
- Client keeps partial text
- No done or error means interrupted
In depth
Finding and disabling buffering
Any hop between the generator and the screen can buffer. NGINX buffers proxied responses by default; turn this off for the streaming location with proxy_buffering off, or send the response header X-Accel-Buffering: no, which NGINX honours per response. Compression middleware such as GZipMiddleware can hold data until it has enough to compress, so exclude text/event-stream from compression. CDNs and some managed load balancers have their own streaming settings; check their documentation.
Test from the outside in. Run curl -N directly against Uvicorn, then against the proxy, then against the public URL. The first hop where events stop arriving one by one is the one buffering.
- 1Browser
Reads chunks as they arrive
- 2CDN or edge
May buffer or cut long responses
- 3Load balancer
Idle timeout closes quiet connections
- 4Reverse proxy
NGINX buffers by default
- 5App middleware
Compression can hold small chunks
- 6Generator
Yields each event straight away
Time to first token and heartbeats
Time to first token (TTFT) is the gap between receiving the request and sending the first delta. It covers authentication, retrieval, prompt building and the model's own start-up, and it is the number users feel most. Record it as a separate metric with the total duration and token count, and look at the 95th percentile, not just the average.
While waiting, send heartbeats. An SSE comment such as : ping followed by a blank line every 10 to 15 seconds stays well under typical idle timeouts (NGINX proxy_read_timeout defaults to 60 seconds). Sending an early comment as soon as the response starts also pushes the headers out, so the client knows the request was accepted.
- TTFT = first delta sent minus request received
- Track p50 and p95 TTFT, total time and tokens
- Heartbeat every 10 to 15 seconds
- Comments start with a colon and never reach the UI
Propagating cancellation upstream
In the browser, pass an AbortController's signal to fetch and call abort() when the user presses Stop or the component unmounts. On the server, what happens next depends on your Starlette and server versions: either the streaming task is cancelled at its current await, raising CancelledError inside the generator, or the next write fails because the socket is closed. Checking await request.is_disconnected() between tokens catches the case early.
In every case, wrap the model stream in try/finally or async with, so the upstream HTTP stream is closed and the provider stops generating. Do not swallow CancelledError; let it propagate after cleanup. Log the cancellation with tokens produced so far, and save the partial answer marked as stopped if your chat history needs it.
- FastAPI to Browser: delta, delta, delta1delta, delta, delta
- Browser to FastAPI: abort() closes the connection2abort() closes the connection
- FastAPI to Model provider: finally: close upstream stream3finally: close upstream stream
- Model provider to FastAPI: Generation stops, usage so far4Generation stops, usage so far
Errors after the headers are sent
HTTP sends the status line and headers before the body. The moment the first event leaves, the client has a 200. If the model provider fails 40 tokens later, raising HTTPException does nothing useful; the server can only close the connection, which looks like a network drop.
So plan two error paths. Before streaming, return normal error statuses. During streaming, catch failures, send an error event with a safe code and a retryable flag, then end the stream. The client treats a stream that closes without done or error as an interrupted connection, keeps the partial text visible, and offers Retry or Continue.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Disable proxy buffering~35m
- 2Measure time to first token~35m
- 3Send heartbeats~35m
- 4Propagate cancellation upstream~35m
- 5Report errors after headers are sent~35m
Key points
- Turn off proxy buffering for streams, for example X-Accel-Buffering: no or proxy_buffering off in NGINX.
- Send an SSE comment line such as : ping every 15 seconds so idle timeouts do not close the stream.
- Measure time to first token separately from total duration; it is what users feel.
- Close the upstream model stream when the client disconnects, using try/finally.
- After headers are sent the status cannot change, so report late failures as an error event.
Key terms
Tap a card to flip it. 0/5 known
Examples
async def events(request: Request, question: str):
stream = await model.open_stream(question)
try:
async for token in stream:
if await request.is_disconnected():
break
yield sse('delta', {'text': token})
yield sse('done', {})
except ProviderError as e:
yield sse('error', {'code': e.code, 'retryable': e.retryable})
finally:
await stream.aclose() # stop the upstream call either wayCleanup runs whether the stream ends, fails or is cancelled.
A stream that works locally but not in production
Step 1: curl -N against Uvicorn on port 8000 shows deltas every 100 ms. Step 2: the same call through NGINX shows nothing for six seconds, then the full answer. Step 3: the NGINX location has default buffering. Step 4: add proxy_buffering off for /chat/stream, or have FastAPI send X-Accel-Buffering: no, and reload. Step 5: repeat the curl through NGINX; deltas arrive live. Rollback: remove the directive and reload NGINX.
location /chat/stream {
proxy_pass http://api:8000;
proxy_http_version 1.1;
proxy_set_header Connection '';
proxy_buffering off;
proxy_read_timeout 300s;
}Heartbeats while waiting for the first token
This generator races the next token against a 15-second timer. If the timer wins, it sends a comment and keeps waiting on the same pending task. The client sees nothing new, but proxies see traffic, and the connection stays open through a slow start.
async def with_heartbeat(tokens, every: float = 15.0):
it = tokens.__aiter__()
nxt = asyncio.ensure_future(it.__anext__())
try:
while True:
done, _ = await asyncio.wait({nxt}, timeout=every)
if not done:
yield ': ping\n\n'
continue
if isinstance(nxt.exception(), StopAsyncIteration):
return
yield sse('delta', {'text': nxt.result()})
nxt = asyncio.ensure_future(it.__anext__())
finally:
nxt.cancel()Quick reference
- NGINX: proxy_buffering off for stream routes, or send X-Accel-Buffering: no.
- Exclude text/event-stream from gzip or other compression middleware.
- Heartbeat: ': ping' plus a blank line every 10 to 15 seconds.
- TTFT = time to first delta; track p95, not only the average.
- Browser stop: AbortController.abort(); server: try/finally closes upstream.
- Check await request.is_disconnected() between tokens.
- After the first byte the status is fixed; send event: error instead.
- No done or error event received = treat as interrupted, keep partial text.
Common mistakes
- Testing only on localhost, then finding that the production proxy delivers the whole answer at once.
- Letting the model call run to the end after the user left, paying for tokens nobody reads.
- Raising HTTPException in the middle of a stream and expecting the client to see a 500.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add a Stop button to your chat UI that aborts the fetch, and confirm in the server logs that the stream ended early.
- Exercise 2medium
Measure TTFT and total duration for the streaming route and log them with the token count for each request.
- Exercise 3hard
Prove that cancellation reaches the model provider: use a fake provider that counts tokens generated, abort the client after one second, and show the count stops growing.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I know if the client disconnected in FastAPI?
- Call await request.is_disconnected() in your loop, and put cleanup in a finally block, because the server may also cancel the generator or fail the next write when the client goes away.
- Can I change the status code if streaming fails?
- No. The status is sent with the first bytes. Send an error event inside the stream and let the client handle it.
- How often should I send heartbeats?
- Every 10 to 15 seconds is common. It only needs to be shorter than the smallest idle timeout on the path, such as a 60-second proxy read timeout.
- Should the client reconnect automatically after a drop?
- For chat answers, usually not blindly, because it would start a new generation and cost again. Show the partial answer and let the user choose to retry or continue.