Measured on localhost: a buffering relay and unflushed gzip held 20 SSE events for 2 s, then sent them at once. nginx settings, heartbeats and an end-to-end test.
A stream that is not streaming
Tanishka's team at Belgavi's Book Store built a help-desk assistant that streams its answer token by token over Server-Sent Events. On a laptop the words appear as they are generated. Behind the staging load balancer the page sits blank for six seconds and then the whole answer appears at once. Nothing in the application changed; something between the model server and the browser is holding the bytes.
This guide measures that effect on localhost, explains the two usual causes (a buffering reverse proxy and response compression), and shows the configuration and the test that keep a stream a stream. The measurements use a small relay written for the purpose, not nginx; the configuration advice comes from nginx's own documentation, which is cited at the end.
What Server-Sent Events need from every hop
An SSE response is a long HTTP response with Content-Type: text/event-stream. The server writes events separated by a blank line; the browser's EventSource dispatches each event when it sees that blank line. The HTML specification also defines comment lines that begin with a colon, which the client ignores and which servers use as heartbeats.
The protocol assumes every hop forwards bytes soon after it receives them. A proxy that collects the response before sending it on, or a compressor that waits for enough input to compress efficiently, does not break the protocol: the events still arrive, complete and in order. They just arrive late, all together, which for a token stream defeats the purpose.
A measurement on localhost
The companion probe starts an origin that sends 20 small events 100 ms apart, a relay in one of five modes, and a client that timestamps each complete event. One run on Windows 11 with CPython 3.13.5:
| Relay mode | First event after | Separate arrivals | Worst event late by |
|---|---|---|---|
| direct to origin | 2 ms | 20 | 12 ms |
| passthrough, forward each read | 3 ms | 20 | 14 ms |
| buffer until 4,096 bytes or end | 2,014 ms | 1 | 2,014 ms |
| gzip, no flush | 2,015 ms | 1 | 2,015 ms |
| gzip, sync flush per read | 4 ms | 20 | 13 ms |
The whole stream is about 1.2 KB, smaller than the 4 KB buffer, so the buffering relay never fills its buffer and sends everything when the origin finishes. The unflushed gzip case is not a quirk of the relay: Python's zlib.compressobj().compress() returns nothing for small inputs until it has enough data or is flushed, which is how deflate implementations generally behave. A sync flush at each event boundary costs a few bytes of compression ratio and restores the timing.
comp = zlib.compressobj(6, zlib.DEFLATED, 31) # gzip wrapper
...
if mode == 'gzip':
self.chunk(comp.compress(data)) # often b'' for small events
else: # gzip_flush
self.chunk(comp.compress(data) + comp.flush(zlib.Z_SYNC_FLUSH)) # emits a complete block nownginx: buffering on by default
nginx proxies responses with proxy_buffering on by default. The documentation says that with buffering enabled, nginx receives the response from the proxied server as soon as possible and saves it into buffers set by proxy_buffer_size and proxy_buffers; with buffering disabled, the response is passed to the client synchronously, immediately as it is received. For a token stream you want the second behaviour on the streaming location only.
location /assistant/stream {
proxy_pass http://assistant_upstream;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off; # forward each read as it arrives
proxy_cache off;
proxy_read_timeout 300s; # longer than the longest quiet gap in a stream
gzip off; # do not compress this location
}The upstream can also ask for this per response: nginx honours an X-Accel-Buffering: no response header (documented under proxy_buffering), unless proxy_ignore_headers removes it. Setting the header in the application is useful when the same location serves both streams and ordinary responses, but it only helps when nginx is the hop doing the buffering. Other proxies, load balancers and CDNs have their own settings and defaults; check each one in the chain.
Compression: leave event streams alone
nginx compresses only the MIME types listed in gzip_types, and the default list is text/html. A configuration that adds text/event-stream to the list, or a framework middleware that compresses every text response, reintroduces the gzip row from the table above. Either exclude event streams from compression or make sure the compressor flushes after each event. Excluding is simpler and costs little, because token events are small and the connection is long-lived.
Heartbeats and timeouts
The opposite failure appears when the model is slow to produce its first token, or pauses during tool calls. A proxy with a 60-second read timeout (nginx's default for proxy_read_timeout) closes an idle upstream connection, and the browser's EventSource reconnects, possibly starting a second generation. Send a comment line such as : keep-alive every 15 seconds while nothing else is being sent. It costs a dozen bytes and keeps every hop's idle timer from expiring.
If you send an id: field with each event, a reconnecting EventSource sends Last-Event-ID, and the server can resume rather than restart. That only works if the server can map an id back to a position in the generation, which most token streams cannot; in that case, treat a reconnect as a new request and make sure the old generation is cancelled.
What the application itself must do
Buffering is not only a proxy problem. Check each layer in the process that writes the response:
| Layer | What to check |
|---|---|
| Web framework | the response type is a streaming response, not a string built in full |
| Server or WSGI/ASGI adapter | it writes each chunk as it is yielded |
| Output buffering in the language runtime | flush after each event |
| Compression middleware | excluded for text/event-stream |
| Response headers | Cache-Control: no-cache; X-Accel-Buffering: no if nginx is in front |
Finding the hop that holds the bytes
When a stream arrives in one burst, test each hop from the inside out with the same client, and stop at the first hop where the first event is late. curl is enough for a quick look: its -N (--no-buffer) option turns off curl's own output buffering, so each event is printed as it arrives.
curl -sN -H 'Accept: text/event-stream' http://127.0.0.1:8080/assistant/stream # the application itself
curl -sN -H 'Accept: text/event-stream' http://ingress.internal/assistant/stream # through the ingress proxy
curl -sN -H 'Accept: text/event-stream' https://help.example.com/assistant/stream # through the CDN or load balancerWatch the response headers on each hop as well (curl -sNv). A Content-Encoding: gzip that the application did not send names the compressing hop. A Content-Length on what should be a stream means some hop read the whole body before forwarding it. And a response that starts only after the model has finished means the buffering is upstream of the hop you are testing, often inside the application server.
Testing the real chain
A unit test on the application cannot see a proxy that buffers. The test that catches this measures time to first event through the deployed path, from outside:
import http.client, time
def first_event_seconds(host, path):
conn = http.client.HTTPSConnection(host, timeout=30)
t0 = time.monotonic()
conn.request('GET', path, headers={'Accept': 'text/event-stream'})
resp = conn.getresponse()
buf = b''
while b'\n\n' not in buf:
chunk = resp.read1(4096)
if not chunk:
return None
buf += chunk
return time.monotonic() - t0Point it at an endpoint that emits a fixed test stream (for example, ten events one second apart from a canned response, with no model call), and assert that the first event arrives within two seconds and that events arrive separately. Run it after every change to the load balancer, the proxy or the CDN configuration. A synthetic stream keeps the test fast and cheap, and it separates transport problems from model latency.
Failure modes after the fix
- Turning off buffering everywhere. Ordinary responses benefit from proxy buffering, which frees upstream workers sooner for slow clients. Disable it only for streaming locations.
- A second proxy. The ingress controller is fixed, but a sidecar or service mesh proxy still buffers. Measure end to end, not hop by hop.
- Compression re-enabled by a platform default. A CDN setting can compress
text/*types; check the response headers the browser receives. - Long idle gaps. Without heartbeats, a tool call that takes longer than the read timeout closes the stream mid-answer.
Limits of this guide
The measurements come from a relay written to show the mechanism on one machine. Real proxies differ in buffer sizes and flush rules; the nginx behaviour above is taken from its documentation, not measured. The remedy is the same everywhere: find the hop that holds bytes, turn that behaviour off for event streams only, and keep an end-to-end time-to-first-event test in the deployment checks.