Solve the problem that SSE stream is cached by Nginx

question

If your service uses the nginx gateway, there may be a problem with nginx buffering the sse stream. The resulting phenomenon is that when the client calls the sse interface, the stream data does not appear one by one, but in one go. The reason is nginx The gateway caches streaming data.

The case of a single Nginx

If there is only one layer of nginx gateway between your client and server, you can tell nginx not to cache the response data by adding a response header of X-Accel-Buffering=no to the interface.

The case of multiple Nginx

But many times the service environment we are in may have more than one nginx gateway. Take our service as an example. Due to some historical reasons, there are actually two nginx gateways from the client to the server, one is the gateway at the company level, and the other is the gateway for k8s reverse proxy. At this time, simply set X -Accel-Buffering=no is invalid.

The reason is that the response data first arrives at the first nginx. At this time, this nginx will consume the header, and then transparently transmit the data to the next nginx. At this time, the second nginx will cache the data by default, so the sse stream will be blocked again. cached.

The solution is to continue to add this header in the configuration of the first nginx, indicating that requests under this path need to carry this header, so that the second nginx can continue to receive this header and not cache data.

  location /path {
    
    
      ...
      add_header X-Accel-Buffering "no";
      ...
  }

If there are n nginxes between the client and the server, this header must be configured in at least n-1 nginxes.

Guess you like

Origin blog.csdn.net/u013534071/article/details/131500873