LoginSignup
2
1

More than 3 years have passed since last update.

Nginx+FlaskでServer-Sent Events(SSE)が遅延するとき

Posted at

問題

  • FlaskのアプリケーションでServer-Sent Events(SSE)による更新を行っている
  • Nginxに接続しなければ正常に動作する
  • Nginxに接続すると,SSEの処理だけが絶望的に遅れる

原因

Nginxのリバースプロキシによってバッファリングが行われるため

解決

FlaskからJavascriptのEventSourceに渡すレスポンスに,ヘッダX-Accel-Buffering: no1を付与する.

X-Accel | NGINX

hoge.py
# Returns a response for the JS EventSource
@flask_app.route( "/stream" )
def stream():
    response = flask.Response( event_stream( "foo" ),
                               mimetype = "text/event-stream" )
    response.headers["X-Accel-Buffering"] = "no"
    return response

その他

Nginx側の設定に以下を追記すれば良いとの情報がみられる2が,Flask側でSSEの処理に絞って適用した方が綺麗だと考えられる.

ruby - EventSource / Server-Sent Events through Nginx - Stack Overflow

proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1