---
title: "SSE Streaming Disconnects: Debugging Nginx, CDN and Load Balancers"
description: "SSE streaming that cuts off, stalls, or arrives all at once is usually a proxy buffering or timing out. Check five layers with curl -N and apply the config fixes."
url: https://cdnping.org/en/blog/llm-sse-streaming-disconnect-proxy
language: en
published: 2026-10-28
category: "Troubleshooting"
tags: ["SSE","LLM streaming","Nginx","CDN","load balancer","troubleshooting"]
source: cdnping.org
license: Free to quote and summarize with a link to the url above.
---
# SSE Streaming Disconnects: Debugging Nginx, CDN and Load Balancers

When SSE streaming breaks, the model is rarely the culprit. Usually some proxy layer on the request path is buffering data or cutting the connection after an idle timeout. Run `curl -N` against the upstream directly and again through your own proxy, and compare the arrival timestamp of each chunk. That tells you which layer is at fault. This article walks through the layers in order (upstream, Nginx, load balancer, CDN, browser) and gives a verification step and a fix for each.

## First, identify which symptom you have

"Streaming is broken" looks the same to a user, but it covers four different failures with different causes:

| Symptom | Common cause | Layer to check first |
|---|---|---|
| Long wait, then the whole response appears at once | A layer is buffering (Nginx `proxy_buffering`, gzip, compression middleware) | Nginx, app framework |
| Output stops halfway, then errors or disconnects after tens of seconds | Idle timeout (`proxy_read_timeout`, load balancer idle timeout) | Nginx, load balancer |
| No first byte at all, finally a 504 / 524 | Upstream first token is too slow and exceeds the proxy's or CDN's wait limit | Upstream, CDN |
| After a disconnect the request restarts automatically and the bill shows an extra call | Browser `EventSource` auto-reconnect | Frontend |

If you are using an off-the-shelf command-line tool rather than your own service, for example Codex reporting `stream disconnected before completion`, the cause is more likely a local proxy, certificate, or WSL problem. See [Codex stream disconnected before completion: telling proxy, certificate, and WSL causes apart](/en/blog/codex-stream-disconnected-before-completion). This article covers the architecture where your own service forwards an LLM's streaming response to users.

## How do you see when each chunk arrives with curl?

`-N` turns off curl's own output buffering. Then prefix each line with a local timestamp:

```bash
curl -N -sS https://your-domain/v1/chat/completions \
  -H "Authorization: Bearer $KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"your-model","stream":true,"messages":[{"role":"user","content":"Count from 1 to 50, one number per line"}]}' \
| while IFS= read -r line; do printf '%s  %s\n' "$(date +%H:%M:%S.%3N)" "${line:0:80}"; done
```

(The `date` that ships with macOS does not support `%3N`. Install coreutils and use `gdate`.)

Look at two things in the output:

- Whether the timestamps increase evenly. In healthy streaming, `data:` lines arrive at intervals of tens to hundreds of milliseconds. If nothing appears for a long time and then dozens of lines share the same timestamp, something in between is buffering.
- What the last line is. A normal finish ends with `data: [DONE]` or the equivalent end event. If the stream stops after an ordinary chunk and curl returns an error such as `curl: (18)` or `(92)`, the connection was closed midway.

Run the same command three times: directly against the upstream API, through your Nginx (you can request `127.0.0.1` on the server), and through the public domain (which goes through the load balancer and CDN). The run where chunks start bunching up or the stream breaks tells you the problem lies in that layer or the one just before it.

For a breakdown of total time, add a `-w` line:

```bash
curl -N -sS -o /dev/null -w 'connect=%{time_connect}s tls=%{time_appconnect}s ttfb=%{time_starttransfer}s total=%{time_total}s\n' ...
```

When `ttfb` is close to `total`, the response was almost certainly buffered into a single delivery. For how connection setup, first byte, and output time relate, see [AI API latency breakdown: connection setup, gateway round trip, and time to first token (TTFT)](/en/blog/api-latency-connect-rtt-ttft).

## Layer 1: Is the upstream provider itself stable?

Rule out the upstream first. If the curl run that goes straight to the upstream also breaks, there is no need to look at your own proxy.

- Open [API status](/en/status) and check whether the probe of the provider's official API endpoint is healthy and whether any incident is in progress.
- Use the [online speed test](/en) to measure "initial connection" and "round trip" from your own network. If both look normal but streaming still breaks, the problem is more likely in the proxy layer than in the network.
- Watch for incidents at the CDN and cloud platform itself. In the Cloudflare status page records that cdnping syncs, there is an "Increased HTTP 502 Errors" incident on October 15, 2026 at 10:47 (UTC) that lasted about 591 minutes (source: cdnping status page sync data, as of 2026-10-17). If your traffic goes through that platform, attribute any disconnects during such an incident to the platform first, instead of rushing to change your own configuration.

The probes on the status page are short requests. For example, cdnping started collecting data on 2026-10-17. In the window from 16:40 to 18:05 that day (Beijing time), probes from the Cloudflare Denver (DEN) node made 242 requests to the various API endpoints. The Claude API endpoint (api.anthropic.com) had a median latency of 73 ms and 100% availability. That only shows the endpoint is reachable. It does not prove that a streaming connection lasting several minutes won't be cut off midway.

## Layer 2: Which settings does a self-hosted Nginx need?

By default, Nginx reads the upstream response into a buffer first. That is fine for ordinary APIs and a problem for SSE. Give the streaming endpoint its own `location`:

```nginx
location /v1/ {
    proxy_pass https://upstream_llm;

    proxy_http_version 1.1;          # Defaults to 1.0, which does not support chunked long-lived connections
    proxy_set_header Connection "";  # Don't pass "close" to the upstream
    proxy_buffering off;             # Disable response buffering; forward as soon as data arrives
    proxy_cache off;
    gzip off;                        # gzip accumulates a block before compressing and sending

    proxy_read_timeout 600s;         # Maximum gap between two reads; default is 60s
    proxy_send_timeout 600s;
}
```

A few details that are easy to miss:

1. **`proxy_buffering off` and `X-Accel-Buffering`.** If changing the Nginx config is inconvenient, have the backend add `X-Accel-Buffering: no` to the response headers. Nginx will then disable buffering for that one response. Pick one of the two approaches.
2. **gzip.** If you turn off only `proxy_buffering` while `gzip on` is set globally and `gzip_types` includes `text/event-stream`, you may still see the response arrive all at once. The simplest fix is `gzip off` inside this location.
3. **`proxy_read_timeout`.** It is not a cap on total duration. It is the longest wait between two successful reads from the upstream. A model can go a long time without emitting a token while it thinks, and the 60-second default will trigger a disconnect in the middle.
4. **Verify after changing.** Run `nginx -t && nginx -s reload`, then use the curl command above against the local Nginx and confirm the timestamps now increase evenly.

Application frameworks can buffer too. Express's compression middleware and the default response wrapping in some Python frameworks both accumulate streamed output. Bypass Nginx and request the application port directly on the server to confirm the app itself emits chunks.

## Layer 3: Idle timeouts on cloud load balancers

Many cloud load balancers have an idle timeout setting: if no data crosses the connection for a set time, the connection is closed. Defaults differ by vendor, so check your cloud provider's official documentation.

How to tell: in the curl output, compare the time of the last chunk before the break with the time the request started. If the connection always drops a fixed number of seconds after the last chunk, it is almost certainly an idle timeout.

There are two fixes, usually used together:

- Raise the load balancer's idle timeout above the longest pause the model might take while thinking.
- Send SSE heartbeat comments from the server on a timer, for example a `: ping` line followed by a blank line every 15 seconds (an example value; it must be shorter than the idle timeout). Lines starting with a colon are comments that clients ignore, but they keep the connection looking active.

A common trap here is heartbeats swallowed by buffering. If Nginx or a compression middleware is still buffering, the heartbeats pile up in the buffer along with the body. The load balancer still sees a connection with no data and times out anyway. So fix Layer 2 buffering first, then add heartbeats. When you verify with curl, you should see `: ping` lines appear on their own at a fixed interval.

## Layer 4: Can the CDN buffer or cut a streaming response?

When you put an API behind a CDN, confirm three things:

| Check | How to look | Fix |
|---|---|---|
| Whether the streaming endpoint is cached | Look for cache-hit markers in the response headers | Set paths like `/v1/` to not cache, and return `Cache-Control: no-cache` |
| Whether the response is compressed or rewritten | Compare curl timestamps against the origin directly and through the CDN | Disable compression and content-rewriting features for `text/event-stream` |
| First-byte wait limit | A timeout code such as 524 after a long period with no first byte | Send the response headers and one heartbeat right away, then wait for the model's first token |

Taking Cloudflare as an example, its documentation says that in proxy mode there is a time limit on waiting for the origin response, and exceeding it returns 524. For LLM endpoints, the safer pattern is to return `200` and the `Content-Type: text/event-stream` headers immediately on receiving the request, then send a heartbeat line. The CDN has then received its first byte, and the rest can trickle out slowly. For cache rules and origin protection, see [Speeding up AI apps with Cloudflare: caching, API rate limiting, and origin protection](/en/blog/cloudflare-edge-for-ai-apps). To see which layer returns a 502, 504, or 524, check [LLM API error code cheat sheet](/en/blog/ai-api-error-codes-400-to-529-cheatsheet).

## Layer 5: Why does browser auto-reconnect cause duplicate billing?

The browser's native `EventSource` reconnects automatically after the connection drops. That is good for ordinary push notifications. For an LLM endpoint it means every drop sends a new request to your server, the model generates the answer again from the start, and the tokens are counted again. If your bill is higher than what the frontend actually displayed, check here first. For how to reconcile, see [AI API bill doesn't match: how token counting differs and how to check it](/en/blog/relay-billing-token-mismatch).

Recommended approach:

- For LLM endpoints, read the stream with `fetch` and `ReadableStream`, so that your code decides whether to retry after a disconnect instead of the browser restarting automatically. `EventSource` also supports only GET, which makes it a poor fit for requests carrying a long prompt anyway.
- If you must use `EventSource`, call `close()` as soon as you receive the end event. If the server returns 204 when the request has already completed, the browser will not reconnect.
- When you do need retries, add a request ID for deduplication and limit the retry count and interval. For the implementation, see [How to write LLM API retries: exponential backoff with jitter, retry budgets, and errors you must never retry](/en/blog/llm-api-retry-exponential-backoff-jitter).

## Checklist: work through it once

1. Use timestamped `curl -N` directly against the upstream and confirm it streams all the way to the end event. While you are at it, check [/en/status](/en/status) and [/en/down](/en/down) for any ongoing incident.
2. Request the application port on the server and confirm there is no compression middleware or framework buffering at the application layer.
3. Request the local Nginx and confirm `proxy_buffering off`, `proxy_http_version 1.1`, `gzip off`, and `proxy_read_timeout` are in effect.
4. Send a `: ping` heartbeat on a timer from the server (for example every 15 seconds) and confirm in the curl output that it appears on its own.
5. Check the load balancer's idle timeout and set it higher than the model's longest pause.
6. Test again through the public domain and confirm the CDN is not caching, compressing, or rewriting the streaming response, and that the first byte returns promptly.
7. Switch the frontend to reading the stream with `fetch`, drop `EventSource` auto-reconnect, and control retries in code.

Change only one thing per step, then compare timestamps with the same curl command. The step after which chunks go from bunched to even, or after which the disconnects stop, shows which layer was the problem.
