Video in progress

The SSE endpoint works in real time locally, but behind Nginx the events arrive late, several at once. What is the cause?

Almost always proxy buffering: by default Nginx collects the upstream response in a buffer and passes it on in chunks. The fix is proxy_buffering off in the SSE location, or returning the X-Accel-Buffering: no header from the app; also check compression.

📖 Answer

The symptom is clear: the EventStream tab in DevTools sits empty, then 10 to 20 events drop in at once. In the server log, though, the events were sent on time.

Nginx considers buffering a good thing for a normal HTTP response because it frees the backend sooner. For SSE it's a disaster, because the response never ends.

location /api/stream/ {
    proxy_pass http://app:8080;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 1h;
}

If you can't get at the configuration, the app itself can signal Nginx:

@GetMapping(value = "/api/stream/orders", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter stream(HttpServletResponse response) {
    response.setHeader("X-Accel-Buffering", "no");
    response.setHeader("Cache-Control", "no-cache");
    return registry.register(new SseEmitter(Duration.ofMinutes(30).toMillis()));
}

The second culprit is gzip. A compression algorithm also collects data and only then emits it. text/event-stream isn't in the default server.compression.mime-types list in Spring Boot, but someone may have added it with a "let's compress everything" mindset. Check gzip_types in Nginx the same way.

The third is a CDN or corporate proxy. You have no control over them, so with SSE I send a comment heartbeat (: ping) every 15 to 20 seconds: the buffer gets "pushed" out sooner anyway, and there are fewer drops too.

It's easy to verify: connect with curl -N https://host/api/stream/orders through the proxy and directly to the backend, and compare when the events arrive.