العربية

Server-Sent Events arrive all at once behind Nginx: the buffering fix

A streaming AI chat that works locally but dumps the whole answer at the end in production usually has one cause: Nginx buffering. Here is the full fix for Nginx and Express.

· 6 min read
Server-Sent Events arrive all at once behind Nginx: the buffering fix

Your streaming AI chat works perfectly on your laptop. Words appear one by one, the way they should. Then you deploy it behind Nginx and the user stares at a spinner for twenty seconds before the whole answer lands at once. This is almost always an SSE Nginx buffering problem, and it takes a few lines to fix once you know where to look.

The symptom: streaming works locally, not in production

I hit this on an AI feature for a client platform. The backend was Node.js with Express, running under PM2, with Nginx in front as a reverse proxy. The same setup I describe in deploying a Node.js app with PM2 and Nginx.

Locally, the browser talked straight to Node on port 3000, and the tokens streamed in live. On the server, the browser talked to Nginx, Nginx talked to Node, and the stream turned into a single block of text at the end.

A few signs that point to buffering and not a bug in your code:

  • The full response is correct, it just arrives late.
  • The delay matches the time the model takes to finish generating.
  • Hitting Node directly on the server (bypassing Nginx) streams fine.
  • In the browser Network tab, the EventStream tab stays empty, then fills up all at once.

Why server-sent events and Nginx clash: proxy buffering

By default, Nginx buffers responses from upstream servers. It reads what your app sends into memory (or a temp file), and passes it to the client in larger chunks. For normal pages this is a good thing. It frees your Node process quickly and handles slow clients well.

For server-sent events it is exactly wrong. Each event is a small piece of text like data: hello\n\n. Nginx happily collects them in its buffer and waits for the buffer to fill or the response to end. With a short AI answer, the buffer never fills, so everything is released when the stream closes.

Three other things can make it worse:

  • Read timeouts. Nginx closes an upstream connection if it gets nothing for proxy_read_timeout, which defaults to 60 seconds. Long or quiet streams get cut.
  • Compression. If gzip is applied to text/event-stream, either in Nginx or in Express middleware, the compressor holds data until it has enough to compress.
  • Headers not sent early. If your app does not flush headers right away, some layers wait before treating the response as started.

Fix 1: turn off proxy_buffering for the stream route

Do not disable buffering for the whole site. Give the streaming endpoint its own location block. Nginx picks the longest matching prefix, so this block wins over your general location /.

server {
    server_name example.com;

    # Streaming endpoint (SSE)
    location /api/chat/stream {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Connection '';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_buffering off;
        proxy_cache off;
        gzip off;

        proxy_read_timeout 1h;
        proxy_send_timeout 1h;
    }

    # Everything else keeps normal buffering
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # ... your listen 443 ssl and certificate lines from Certbot stay here
}

What each line does:

  • proxy_buffering off sends each chunk to the client as soon as Nginx receives it. This is the main fix.
  • proxy_http_version 1.1 with an empty Connection header keeps the upstream connection open properly for a long response.
  • proxy_cache off makes sure nothing tries to cache the stream.
  • gzip off stops Nginx from compressing it.
  • The timeouts give long streams room. Pick a value that matches your longest realistic stream, and use heartbeats (below) so quiet periods do not trigger it.

Test and reload:

sudo nginx -t && sudo systemctl reload nginx

If you added HTTPS with Certbot, keep its lines in the server block as they are. My setup is in free HTTPS on a VPS with Let's Encrypt.

Fix 2: the X-Accel-Buffering header from your app

Nginx also reads a special response header from the upstream: X-Accel-Buffering: no. When your app sends it, Nginx disables buffering for that one response, even if proxy_buffering is on.

This is useful in two cases. First, when you do not control the Nginx config, for example on a managed platform that sits behind Nginx. Second, as a safety net, so the route still streams if someone later edits the config and forgets the special block.

I use both: the Nginx block and the header. Belt and braces. Note that if a config uses proxy_ignore_headers X-Accel-Buffering, the header is ignored, so check for that if it does not take effect.

Fix 3: flushHeaders and clean writes in Express

On the Node side, the endpoint needs the right headers, sent immediately, and each event written in the correct format.

app.get('/api/chat/stream', async (req, res) => {
  res.set({
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache, no-transform',
    'Connection': 'keep-alive',
    'X-Accel-Buffering': 'no',
  });
  res.flushHeaders(); // send headers now, before the first token

  let closed = false;
  const heartbeat = setInterval(() => {
    res.write(': ping\n\n'); // SSE comment, ignored by the browser
  }, 15000);

  res.on('close', () => {
    closed = true;
    clearInterval(heartbeat);
  });

  try {
    for await (const token of generateAnswer(req.query.q)) {
      if (closed) break;
      res.write(`data: ${JSON.stringify({ token })}\n\n`);
    }
    if (!closed) {
      res.write('event: done\ndata: {}\n\n');
    }
  } catch (err) {
    if (!closed) {
      res.write(`event: error\ndata: ${JSON.stringify({ message: 'Stream failed' })}\n\n`);
    }
  } finally {
    clearInterval(heartbeat);
    res.end();
  }
});

The details that matter:

  • res.flushHeaders() tells the client and Nginx the response has started, so the browser opens the stream right away.
  • no-transform in Cache-Control asks proxies not to modify (or compress) the body.
  • Each event ends with a blank line: \n\n. Miss it and the browser keeps waiting for the event to finish.
  • The heartbeat comment keeps the connection active, so read timeouts in Nginx or anything else on the path do not fire during a slow model response.
  • res.on('close') stops generating when the user leaves the page, which saves tokens and server work.

If you use the compression middleware, either skip it for this route or call res.flush() after each write. The simplest option is to mount the stream route before app.use(compression()), or use the middleware's filter option to exclude text/event-stream.

How to test the SSE stream from the terminal

Do not trust the browser alone. Use curl with -N, which turns off curl's own buffering:

curl -N "https://example.com/api/chat/stream?q=hello"

You should see data: lines appear one after another. Then compare with a request straight to Node on the server:

curl -N "http://127.0.0.1:3000/api/chat/stream?q=hello"

If the direct request streams and the public one does not, the problem is in the proxy layer. If neither streams, look at your Node code: missing \n\n, compression middleware, or a library that collects the whole AI response before returning.

One more layer to check: if a CDN or another proxy sits in front of Nginx, it can buffer too. Check its documentation for streaming or event-stream support.

FAQ

Should I set proxy_buffering off for the whole site?

No. Buffering helps normal pages and API responses. Turn it off only in the location that serves the stream, and send X-Accel-Buffering: no from that route as a backup.

Does X-Accel-Buffering work without changing the Nginx config?

Yes, in most setups. Nginx honors it per response unless the config tells it to ignore that header. You may still need longer read timeouts or heartbeats for long streams.

Why does my server-sent events connection drop after about a minute?

That is usually proxy_read_timeout, which defaults to 60 seconds. Raise it for the stream location and send a comment line like : ping every 15 seconds or so.

Can I use EventSource for a POST chat request?

The browser EventSource API only sends GET requests. For POST, use fetch and read response.body as a stream. The Nginx and Express fixes above apply the same way.


Building an AI feature or a live dashboard and want it to stream properly? Talk to the editor at ahmed-adil.com.

More from the Supplement