Handling client disconnect during ServerSentEvents using Plug with Bandit

This is the same underlying issue as Stopping the request handler · Issue #202 · mtrudel/bandit · GitHub; the tl;dr here is that the single-function nature of the Plug API makes it impossible for a single-process-per-connection model such as Bandit to close connections eagerly (at least for HTTP/1; HTTP/2 connections are fundamentally multi-process & should eagerly shut down requests on client disconnection).

All is not lost, however. You should be able to detect this with your code! As of 1.0.0-pre.14 (just released a few minutes ago), your application code will see any errors encountered (including {:error, :closed}) in the return value of Plug.Conn.chunk/2 calls. You should be able to case on the output of this value in your send_message/2 function in order to properly shut things down as needed.

2 Likes