Sub topic 12
Keeping proxies from buffering the stream
This chapter assumes you have the /chat endpoint from the previous chapters: a StreamingResponse that yields Server-Sent Events (SSE). You should know the basics of HTTP headers and have seen a reverse proxy such as nginx. The endpoint can be correct and still look broken in production. Tokens arrive in one lump after the model finishes, because something between your app and the browser held the bytes back.
Where buffering happens
Your code yields a chunk, and Uvicorn writes it to the socket. In production the chunk then passes through more layers before it reaches the user. Any of them may collect bytes until a buffer fills or the response ends.
| Layer | Typical cause | Fix |
|---|---|---|
| Reverse proxy (nginx) | `proxy_buffering on` is the default | `X-Accel-Buffering: no` header or `proxy_buffering off` |
| Compression | gzip waits for enough data to compress | Exclude `text/event-stream` from compression |
| CDN or API gateway | Response buffering or caching | Disable buffering for the route, send `Cache-Control: no-cache` |
| Load balancer | Idle timeout closes quiet connections | Send periodic keep-alive comments, raise the idle timeout |
| Client library | Reads the whole body before returning | Use a streaming API, as in the previous chapter |
The first two rows cause most of the problems.
Headers the endpoint should send
The endpoint from the earlier chapter already sets the important ones:
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}Each header does a different job:
Content-Type: text/event-streamcomes frommedia_type. Many proxies and browsers treat this type as a stream, andEventSourcerequires it.Cache-Control: no-cachetells shared caches not to store the response or serve it to another user.X-Accel-Buffering: nois read by nginx. It turns offproxy_bufferingfor this one response, so you do not need to change the nginx config for the route. Other proxies ignore it.
You may see Connection: keep-alive in older examples. It is a hop-by-hop header for HTTP/1.1. Do not set it yourself. It is not valid on HTTP/2, and Uvicorn and the proxy manage the connection.
Configuring nginx
If you control nginx, set the behavior explicitly for the streaming route. This does not depend on the app sending the header.
location /chat {
proxy_pass http://127.0.0.1:8000;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
gzip off;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}What each directive does:
proxy_http_version 1.1and an emptyConnectionheader let nginx keep a persistent connection to Uvicorn. nginx talks HTTP/1.0 to upstreams by default, and that mode does not support chunked streaming well.proxy_buffering offmakes nginx forward each chunk as it arrives instead of filling its buffers first.proxy_cache offstops nginx from caching the response body.gzip offavoids compression that waits for more data. Compressing small text tokens gains little anyway.proxy_read_timeoutis the longest nginx waits between two reads from the upstream. The default is 60 seconds. If the model pauses longer than that, for example during a slow first token, nginx closes the connection and the client sees a truncated stream.
Without proxy_buffering off, nginx first writes the upstream response into memory buffers, then to a temporary file if the response is larger. It sends data to the client only when a buffer is full or the response ends. For short LLM answers that means the whole answer arrives at once, which defeats streaming.
Compression middleware in the app
If your app adds GZipMiddleware, check that it does not delay SSE. Compressors hold data back to find patterns, so small token events can sit in the compressor. Recent Starlette versions skip compression for text/event-stream, but this depends on the version. Do not assume it. You can avoid the question by not compressing the streaming route, or by doing compression only at the proxy where you can turn it off per location.
Keeping idle connections alive
Even without buffering, a quiet stream can be cut. A model may take many seconds before the first token, and a load balancer or proxy may close connections that send no bytes for 30 to 60 seconds. SSE has a standard answer: a line that starts with a colon is a comment. Clients ignore it, and it still counts as traffic.
import asyncio
from collections.abc import AsyncIterator
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
STREAM_HEADERS = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}
async def with_heartbeat(
source: AsyncIterator[str], interval: float = 15.0
) -> AsyncIterator[str]:
"""Yield items from source, plus an SSE comment after each quiet interval."""
iterator = source.__aiter__()
pending = asyncio.ensure_future(iterator.__anext__())
try:
while True:
done, _ = await asyncio.wait({pending}, timeout=interval)
if not done:
yield ": keep-alive\n\n"
continue
try:
item = pending.result()
except StopAsyncIteration:
return
yield item
pending = asyncio.ensure_future(iterator.__anext__())
finally:
pending.cancel()
async def slow_events():
for i in range(3):
await asyncio.sleep(2.5)
yield f"event: token\ndata: {{\"text\": \"part {i} \"}}\n\n"
yield "event: done\ndata: {}\n\n"
@app.get("/slow")
async def slow():
return StreamingResponse(
with_heartbeat(slow_events(), interval=1.0),
media_type="text/event-stream",
headers=STREAM_HEADERS,
)The wrapper does not use asyncio.wait_for on the next item. A timeout in wait_for cancels the awaited call. Cancelling __anext__ of an async generator ends that generator, so the stream would die at the first heartbeat. asyncio.wait with a timeout only stops waiting. The pending task keeps running, and the loop checks it again after the next interval.
The finally block cancels the pending task if the client disconnects. This ties into the previous chapter on cancellation: the wrapper must not keep the model call alive after the stream is gone.
In production, set the interval below the shortest idle timeout in your path. A value of 15 seconds is common. Wrapping token_events from the main endpoint is a one-line change: pass with_heartbeat(token_events(client, body.prompt)) to StreamingResponse.
Verifying that the stream is not buffered
Test through the same path your users take, not only against Uvicorn on localhost. curl with -N turns off its own output buffering, so you see exactly when bytes arrive.
curl -N -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"prompt": "Count to ten slowly"}'Run it twice: once against the app port (8000) and once against the proxy or public URL. If events appear gradually on the first and all at once on the second, a layer between them is buffering. Add -i to inspect the response headers. Check that Content-Type is text/event-stream, that Content-Length is absent, and that Transfer-Encoding: chunked appears on HTTP/1.1. A Content-Length header means something collected the full body before sending it.
You can also add a timestamp to the Python client from the previous chapter, printing time.monotonic() beside each token. Gaps of a few tens of milliseconds are normal. A single large gap followed by a burst is buffering.
Common mistakes
- Testing only on localhost. Direct access skips the proxy, so everything looks fine until deployment.
- Setting
proxy_buffering offon the wronglocation, so the request matches a different block. Check which block handles the path. - Forgetting
proxy_read_timeout. Short answers work and long ones are cut at exactly 60 seconds. - Compressing the stream at several layers. Disable it on the streaming route at each layer.
- Relying on
X-Accel-Bufferingbehind a proxy that is not nginx. - Adding padding bytes to force a flush. It is a workaround for old proxies. Prefer configuring the proxy.
Exercise
A streaming endpoint works with curl -N against Uvicorn on port 8000. Behind nginx with default settings, the browser shows the whole answer at once after the model finishes. Name two ways to fix this, and name one more nginx setting to check if long answers are cut off after exactly 60 seconds.
Show answer
Either send the X-Accel-Buffering: no response header from the endpoint, or set proxy_buffering off in the nginx location for the route (also use proxy_http_version 1.1 and an empty Connection header so the upstream connection works well). For answers cut off at 60 seconds, raise proxy_read_timeout, whose default is 60 seconds, and send heartbeat comments so the connection is never idle that long.
Exercise
Why does with_heartbeat use asyncio.wait with a timeout instead of asyncio.wait_for(iterator.__anext__(), interval)?
Show answer
wait_for cancels the awaited __anext__ call when the timeout expires. Cancelling an async generator's __anext__ ends that generator, so the underlying stream would be lost after the first heartbeat. asyncio.wait with a timeout only stops waiting and leaves the pending task running, so the generator continues and its next item is picked up on a later loop.