Sub topic 15
Why proxies and platforms break streaming
This chapter assumes you can read Python and JavaScript, know basic HTTP, and have a working SSE endpoint like the one built in the relay chapter. Your stream works on localhost. After deployment, the browser shows nothing for several seconds and then the whole answer appears at once. This chapter explains why that happens and how to fix it.
The symptom: streaming that works locally and fails in production
Streaming only helps if every hop between the model and the browser forwards bytes as soon as it receives them. A hop is any program that handles the response: your app server, a reverse proxy, a CDN, a load balancer, a corporate gateway. Any one of them can hold bytes back. When that happens, the stream is still correct. It just arrives late and in large pieces.
The typical symptoms are:
- No text for a long time, then everything at once.
- Text arrives in large bursts every few seconds instead of token by token.
- The connection drops after a fixed time, such as 30 or 60 seconds.
- It works in
curlbut not in the browser, or the reverse.
Why intermediaries buffer
Buffering is a sensible default for ordinary web traffic. A proxy that collects a whole response can compress it better, free the app server sooner, and send it to a slow client without tying up the backend. Streaming works against all three goals. The usual buffering layers are:
- Your app server or framework. Some servers collect output into a buffer, such as a WSGI server that waits for the response iterable, or middleware that compresses the whole body.
- Reverse proxies. nginx, by default, reads the upstream response into memory buffers before sending it on.
- Compression. gzip needs a block of data to compress. A compressor that waits to fill a block holds tokens back.
- CDNs and load balancers. Some cache or buffer responses, and most enforce idle and total timeouts.
- Serverless platforms. Some function platforms return the response only after the handler finishes, unless you use a mode that supports streaming responses.
- Corporate or antivirus proxies. These may scan the full body before releasing it, which you often cannot configure.
Fixing buffering at each layer
Signal the intent in response headers
Send headers that tell intermediaries this response should not be stored or held. The FastAPI example from earlier already does this:
import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def tokens():
for token in ["Streaming", " is", " incremental", "."]:
await asyncio.sleep(0.2)
yield f"data: {token}\n\n"
yield "data: [DONE]\n\n"
@app.get("/stream")
async def stream():
return StreamingResponse(
tokens(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
},
)Each header has a job:
| Header | Purpose |
|---|---|
| `Content-Type: text/event-stream` | Tells clients and many proxies this is an event stream. |
| `Cache-Control: no-cache` | Stops caches from storing or replaying the response. |
| `no-transform` (in `Cache-Control`) | Asks intermediaries not to modify the body, which discourages compression and rewriting. |
| `X-Accel-Buffering: no` | Tells nginx to disable response buffering for this response only. |
Configure nginx explicitly
The X-Accel-Buffering header works only if nginx honors it. You can also set the behavior in the location block, which is more reliable and easier to audit:
location /api/chat {
proxy_pass http://app:8000;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
gzip off;
proxy_read_timeout 300s;
}proxy_http_version 1.1 and the empty Connection header allow a persistent connection to the upstream. proxy_read_timeout is the longest nginx waits between two reads from the upstream. It is not a limit on the whole response, but a slow model that pauses longer than this value will be cut off.
Avoid compressing the stream
Compression middleware is a frequent hidden cause. If your framework compresses responses, exclude text/event-stream or flush after each event. Check this first when streaming works only with the middleware removed.
Keep the connection alive during silences
A stream can go quiet while the model thinks or waits for a tool. Idle timeouts in proxies and load balancers then close the connection. SSE allows comment lines, which clients ignore, so you can send them as a heartbeat:
import asyncio
async def with_heartbeat(source, interval=15.0):
"""Yield items from an async iterator, adding SSE comments during silences."""
iterator = source.__aiter__()
pending = asyncio.ensure_future(iterator.__anext__())
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__())The loop waits for the next item with a timeout. If none arrives within interval seconds, it emits a comment and keeps waiting on the same pending read, so no item is lost. Pick an interval shorter than the smallest idle timeout in your path. Note that the heartbeat does not help against a fixed total-duration limit.
Check the platform's streaming support
Hosting platforms differ. Before choosing one, check three points in its documentation:
- Whether handlers may return a streamed body, and in which runtime or mode.
- The maximum response duration and the idle timeout.
- Whether a CDN or edge layer in front of the platform buffers responses by default.
If a platform cannot stream or has short limits, you may need a different runtime for the chat endpoint, or a different transport.
Diagnosing where the buffer is
Test from the inside out. Compare the timing of the first byte at each hop, starting with the app server directly and moving outward.
curl --no-buffer -N -s -o /dev/null \
-w "first byte: %{time_starttransfer}s, total: %{time_total}s\n" \
http://localhost:8000/streamFor the example endpoint, the first byte should arrive after about 0.2 seconds and the total time should be about 0.8 seconds. Now run the same command against the public URL. If the first-byte time is close to the total time, something between the two points is buffering. Repeat against each intermediate address you can reach until the delay disappears.
The -N flag turns off curl's own output buffering. Without it, curl can make a healthy stream look broken.
Also look at the response headers with curl -i. A missing text/event-stream content type, an added Content-Encoding: gzip, or a Content-Length header all suggest the body is being collected and rewritten.
Edge cases and gotchas
- Buffer size thresholds. Some proxies flush only after a minimum number of bytes. Short tokens may then appear in bursts. Padding the start of the stream with a large comment line is a known workaround for some clients, but fixing the proxy is better.
- HTTP/2 and HTTP/3. These protocols multiplex streams over one connection. Streaming works, but a proxy that translates between versions can still buffer.
- Per-origin connection limits. Browsers using HTTP/1.1 allow only a few connections per host, so several open streams in many tabs can block other requests. HTTP/2 largely removes this.
- Retries by the client.
EventSourcereconnects automatically when a connection drops. A forced timeout can therefore look like an endless restart loop and may trigger repeated model calls and repeated cost. - Local testing hides the problem. A development server has no proxy in front of it. Always test through the same path that production uses.
Exercises
Exercise
Your streaming endpoint shows tokens one by one when you call it with curl -N on the app server, but the browser receives the whole answer at once through nginx. Name two nginx settings or response headers you would check, and say why.
Show answer
Check proxy_buffering (set it to off for the location, or send X-Accel-Buffering: no from the app), because nginx otherwise reads the upstream response into buffers before forwarding it. Also check gzip (turn it off for the location) because compression waits to fill blocks. Setting proxy_http_version 1.1 with an empty Connection header is another valid answer, since it allows persistent upstream connections.
Exercise
The stream is delivered in real time, but it always ends after exactly 60 seconds on long answers. A heartbeat comment every 15 seconds did not help. What is the likely cause, and what are your options?
Show answer
The 60-second limit is probably a total-duration limit on the platform, load balancer, or proxy, not an idle timeout. Heartbeats only reset idle timers. Options are raising the limit if the platform allows it, moving the endpoint to a runtime with longer limits, or splitting the work so the client can resume or continue with a new request.