SSE Streaming Arrives All at Once? Nginx and CDN Buffering Checklist
When SSE streaming turns into a single response that arrives all at once, almost always some layer in the path is holding the response back. The most common culprit is Nginx's proxy_buffering, followed by gzip compression, your application framework's compression middleware, and only then the CDN. The model is still emitting tokens one by one; an intermediate layer is just waiting to collect a full chunk (or the entire response) before passing it on. The way to find it is to run curl -N starting at the origin and work outward, one layer at a time. The first layer where the response starts arriving "in one piece" is the one at fault.
This post covers one thing: streaming being buffered. If your problem is a stream that drops partway through, or how to configure caching and rate limiting on Cloudflare, see Troubleshooting SSE disconnects in LLM streaming and Using Cloudflare to accelerate AI apps.
First: is it buffered, or is the model just slow?
In a browser, both cases look the same: a long spinner, then a big block of text. The fixes are completely different. To tell them apart, look at two timings:
- Time to first byte: from sending the request to receiving the first byte.
- The gap between the first
data:event and the last event.
| Symptom | Time to first byte | How events arrive | Likely cause |
|---|---|---|---|
| Real streaming, slow model | Long | Then one by one, evenly spaced | Model queueing or slow prefill (long TTFT) |
| Buffered | Long, close to total duration | All events flood in at the same moment | A middle layer is batching |
| Partially buffered | Medium | In chunks, each containing many events | Buffer size limit (a single Nginx buffer defaults to 4k or 8k) or chunked compression |
| Healthy | Short | One by one | n/a |
What matters is reading the second and third columns together. A slow first byte does not mean buffering: for long-context requests, TTFT can legitimately be several seconds or more. But if hundreds of event timestamps are crammed into the same second, something is batching. For how to separate TTFT from connection time, see AI API latency breakdown: connection setup, gateway round trip and time to first token.
For the connection layer, you can use cdnping data as a reference. cdnping probes the official API endpoints of major providers every 5 minutes from Cloudflare's edge. In the 2026-10-17 snapshot (probe node DEN, 24 hours since collection began), the median probe latency was 73 ms for the Claude API, 96 ms for the OpenAI API and 69 ms for the Gemini API, with 100% availability over 24 hours for all three (source: /en/status; methodology in /en/methodology). cdnping only started collecting on that day, so this is a single-window example, and it reflects only the "connect to gateway" segment. If the connection layer is tens to hundreds of milliseconds, yet your first byte takes ten-plus seconds and the events arrive together, the delay is not in the network. It is in model generation or in your own middle layers.
How do you locate the buffering layer by layer?
Prepare a request that reliably produces many events. The example below uses an OpenAI-compatible endpoint; substitute your own address and key:
# Prefix each line with its arrival time, to see whether events arrive one by one or all at once
stamp() { while IFS= read -r line; do printf '%s %s\n' "$(date +%H:%M:%S.%3N)" "$line"; done; }
BODY='{"model":"<your-model-name>","stream":true,"messages":[{"role":"user","content":"Count from 1 to 40, one number per line"}]}'
curl -sN https://your-endpoint/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-d "$BODY" | stamp
-N (--no-buffer) stops curl from buffering its own output, which would otherwise mislead you. The date that ships with macOS does not support %N; install coreutils and use gdate.
Then run the same command against each layer, from the inside out:
- Hit the app process directly: on the server, request
http://127.0.0.1:<port>to bypass every proxy. - Through the local Nginx: request
http://127.0.0.1:80orhttps://localhost, with the correctHostheader. - Bypass the CDN and hit the origin: use
--resolve your-domain:443:origin-IPso the domain resolves straight to the origin. - Through the CDN, using the production domain.
- In the browser: in DevTools' Network panel, check whether the request's EventStream or response preview shows events appearing one by one.
# Step 3: same domain, skip the CDN and hit the origin directly
curl -sN --resolve api.example.com:443:203.0.113.10 \
https://api.example.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \
-d "$BODY" | stamp
(203.0.113.10 is a reserved documentation address; replace it with your origin IP.)
The first layer where the timestamps bunch up is the one to fix. If step 1 already returns everything at once, the problem is in your application code, and you do not need to touch Nginx or the CDN.
Also take a look at the response headers, since many clues are there:
curl -sN -D - -o /dev/null https://your-endpoint/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \
-d "$BODY" | head -30
Check whether Content-Type is text/event-stream, whether there is a Content-Encoding: gzip/br, whether there is a Content-Length (a streaming response should not have one), what Cache-Control says, and any cache status headers added by the CDN.
Which Nginx settings need to change?
Nginx enables proxy_buffering by default: it reads the upstream response into a buffer before sending it to the client, which is the most common reason SSE gets batched. Give the streaming endpoint its own location:
location /v1/ {
proxy_pass http://upstream_app;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
# Core: turn off response buffering and caching
proxy_buffering off;
proxy_cache off;
# Compression batches data into blocks; turn it off for streaming endpoints
gzip off;
# Long answers and long thinking time: relax the read timeout
proxy_read_timeout 600s;
proxy_send_timeout 600s;
}
A few notes:
proxy_buffering offwritten here only affects this location. Turning it off globally is not recommended: for ordinary endpoints and static files, leaving buffering on actually saves upstream connections.- Alternatively, have the application return an
X-Accel-Buffering: noresponse header. When Nginx sees it, it disables buffering for that response. The advantage is that you do not need to change the Nginx config, which suits setups where several services share one gateway. This requires thatproxy_ignore_headers X-Accel-Bufferingis not configured. - If you ever added
text/event-streamtogzip_types, remove it. Writinggzip offdirectly in that location is the safest option. proxy_read_timeoutdefaults to 60 seconds. If the gap between two outputs exceeds that, Nginx drops the connection. That is a disconnect problem, but it often shows up together with buffering, so fix it while you are there.- With multiple Nginx layers, change every one of them. For example, a host Nginx forwarding to an Nginx inside a container, or ingress-nginx on Kubernetes (the matching annotation is
nginx.ingress.kubernetes.io/proxy-buffering: "off"). Miss any one layer and the stream still gets held up.
After the change, run nginx -t && nginx -s reload, then retest starting from step 2.
What are the pitfalls in application code and frameworks?
If step 1, hitting the app directly, already returns everything at once, check these:
- Response headers: at minimum send
Content-Type: text/event-streamandCache-Control: no-cache, no-transform.no-transformtells intermediaries not to rewrite the response body (including compressing it). - Compression middleware: in many web frameworks, the compression middleware accumulates output up to a certain size before compressing and sending it. Skip compression for streaming routes, or explicitly flush after every write (check your framework's docs for the exact API).
- Not actually writing as it generates: for example, the backend does not set
stream: truewhen calling the upstream, gets the complete result, and then "simulates" SSE; or it reads the whole upstream stream into an array and returns it in one go. Look for any collect-then-return logic in the code. - Event format: each event must end with a blank line (
\n\n). Without it, the browser'sEventSourcekeeps waiting, which also looks like a hang. - How the frontend reads: with
fetch, read chunk by chunk viaresponse.body.getReader()and decode withTextDecoderusing{ stream: true }. If you useawait response.text()orresponse.json(), the frontend itself waits until the end, no matter how well the backend streams.
What should you check at the CDN layer?
Claims online about whether Cloudflare buffers SSE contradict each other. More reliable than secondhand conclusions is to compare steps 3 and 4 above directly: if the same request streams event by event when it bypasses the CDN but arrives all at once through the CDN, the problem is in the CDN; if the behavior is identical, keep looking further inward. According to Cloudflare's official documentation, proxied traffic is forwarded as it is received by default, and "Response Buffering" is a setting you have to enable separately (available only on some plans). Refer to the official documentation and the settings in your own account for specifics.
Whichever CDN you use, verify the following:
| Check | What to do | How to verify |
|---|---|---|
| Cache rules | Set the streaming endpoint's path to bypass cache, and make sure it is not matched by rules like "cache everything" | The cache status header should show not cached or bypass |
| Compression and content rewriting | Disable features that rewrite the response body on that path (compression, HTML optimization, script injection, etc.) | No unexpected Content-Encoding in the response headers |
| Response buffering option | If your account has a response-buffering switch, confirm it is off for that path | Compare steps 3 and 4 |
| Origin response headers | Send Cache-Control: no-cache, no-transform | Inspect with curl -D - |
| Wait timeout | The origin must start returning data before the timeout | Long-thinking requests do not fail with a timeout error |
For what each cache header directive means and how a CDN interprets it, see How to configure Cache-Control headers.
Why does it drop after a long silence, and how do you write a heartbeat?
This is a separate problem from buffering, but in AI workloads the two often appear together (for a full walkthrough of disconnects, see Troubleshooting SSE disconnects). A model with long reasoning time may take a long while to emit its first token, and during that time no bytes flow through the path. Cloudflare's wait for an origin response has an upper limit, 100 seconds on most plans (check the official docs), after which it returns a 524; Nginx's proxy_read_timeout defaults to 60 seconds. For what the various error codes mean, see the LLM API error code cheat sheet.
The approach is to return 200 and the response headers immediately after receiving the request, then send SSE comment lines periodically. A line starting with a colon is a comment, which EventSource and most client SDKs simply ignore:
: keepalive
: keepalive
data: {"choices":[{"delta":{"content":"1"}}]}
A heartbeat interval of 15 to 30 seconds is common; it should be shorter than the shortest idle timeout on the path. Two things to note:
- The heartbeat must come from your own service. If you are relaying an upstream stream, your relay layer has to supply the heartbeat itself when the upstream is silent.
- If a middle layer is still buffering, the heartbeats get held back along with everything else and do nothing. So fix buffering first, then add the heartbeat.
How do you verify the fix?
Tick through this checklist:
- Running
curl -sN ... | stampagainst the production domain, the event timestamps increase one by one and no longer cluster in the same second. - Time to first byte is not much different from hitting the app directly; the extra is mostly the network round trip added by the CDN.
- Response headers:
Content-Type: text/event-stream, noContent-Length, no unexpectedContent-Encoding, andCache-Controlcontainsno-cache. - Send a request that needs a long time to think: it does not return a 524 past the CDN's wait limit (for example Cloudflare's 100 seconds), and Nginx does not drop it past 60 seconds.
- In browser DevTools, the frontend renders text progressively rather than all at once at the end.
- Add the commands above to your post-deploy smoke test, so a later config change does not turn buffering back on.
If events now arrive one by one but the whole thing still feels slow, go back to the model itself: check how many tokens per second it outputs (see How to read model output speed in tokens/s), and the network between your server and the upstream API. For the network part, you can start by using the cdnping online speed test to measure first-connection and round-trip times from your browser to each provider's API, then see Latency breakdown when accessing AI APIs from China to decide whether you need to change where you deploy.