Sub topic 12
Keeping Proxies from Buffering the Stream
This chapter assumes you can write a FastAPI route, you know what an async generator is, and you have seen the /chat endpoint that returns StreamingResponse with Server-Sent Events (SSE). Your code can be correct and still look broken in production. The cause is often a proxy between the client and your app that holds the response until it is complete.
Why buffering breaks streaming
A proxy is a server that sits between the client and your app and forwards traffic. Nginx, a load balancer, a CDN, and an API gateway are all proxies. Many of them buffer responses by default. Buffering means the proxy collects the bytes your app sends and forwards them in larger pieces, or only after the response ends.
For a normal JSON response this is a good optimization. For a token stream it removes the benefit. Your app yields tokens one by one, but the user sees nothing for several seconds and then gets all the text at once.
The symptom is easy to recognize. The stream works when you call the app directly on port 8000. It fails when you call it through the public URL.
Response headers that help
The endpoint from the previous chapters already sets two headers.
from fastapi.responses import StreamingResponse
def stream_response(events):
return StreamingResponse(
events,
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)| Header | What it does |
|---|---|
| `Content-Type: text/event-stream` | Tells clients and many proxies that this is an event stream, not a finished document. |
| `Cache-Control: no-cache` | Tells caches not to store the response or replay it. |
| `X-Accel-Buffering: no` | Tells Nginx to turn off response buffering for this response. |
X-Accel-Buffering is specific to Nginx. Other proxies ignore it. Check the documentation of the proxy you use, because each one has its own setting.
Proxy configuration
Headers from the app are a hint. If you control the proxy, configure it directly. For Nginx, turn off buffering for the streaming route and allow a long read time.
location /chat {
proxy_pass http://app:8000;
proxy_http_version 1.1;
proxy_buffering off;
proxy_read_timeout 300s;
proxy_set_header Connection "";
}proxy_buffering offsends data to the client as it arrives.proxy_read_timeoutis how long Nginx waits for the next bytes from the app. The default is 60 seconds. A slow model can exceed it.proxy_http_version 1.1with an emptyConnectionheader keeps the upstream connection open.
Two other layers also cause trouble. Compression middleware such as gzip may collect output before compressing, so exclude text/event-stream from compression. Managed gateways often have their own idle timeout and response buffering settings, so look for a streaming or response-passthrough option.
Check it with curl
The -N flag turns off curl's own buffering. Run it against the public URL.
curl -N -X POST https://example.com/chat \
-H "Content-Type: application/json" \
-d '{"prompt": "Say hello"}'If tokens appear one at a time, the path is clean. If everything appears at once at the end, a layer is buffering. Run the same command against the app directly. Compare the two results to find which layer is responsible.
Keep long streams alive
Some proxies close a connection that is silent for too long. While the model is still thinking, your generator may send nothing for many seconds. An SSE comment line is ignored by clients but keeps the connection active.
def keepalive() -> str:
return ": keep-alive\n\n"You would yield this from the generator at an interval when no tokens are ready. A later chapter on timeouts covers how to schedule it.
Exercise
A streaming endpoint prints tokens one at a time when called at http://localhost:8000, but through the company's Nginx the full answer appears at once after several seconds. Name two changes that would likely fix this.
Show answer
Turn off buffering in Nginx for that route with proxy_buffering off, or have the app send X-Accel-Buffering: no. Also check that compression is not applied to text/event-stream and that proxy_read_timeout is long enough. Confirm the fix by running curl -N against the public URL.