skip to content

In a Rails ActionController::Live action, what is ActionController::Live::ClientDisconnected, when is it raised, and how should the action handle it?

level: seniorimportance: should knowfreq 20%

answer

  1. raised on the next write
  2. a RuntimeError, not an IOError
  3. Live::Buffer#abort after the Rack body closes
  4. ignore_disconnect discards silently
  5. errors after commit skip rescue_from

basics

~20 s

ActionController::Live::ClientDisconnected is the RuntimeError that response.stream.write raises once the viewer has gone. It surfaces only on a write after the server noticed, so the action should rescue it as a normal end, send periodic heartbeats and close the stream in ensure.

solid answer

~40 s

The action writes into a `Live::Buffer`, not the socket. When the server finds the client gone it closes the Rack body, which Rails maps to `Live::Buffer#abort`; the next `response.stream.write` then raises `ActionController::Live::ClientDisconnected`, a `RuntimeError` (an `IOError` means you wrote after your own `close`). A loop that sleeps notices only when it writes, so I send a heartbeat on a timer, rescue `ClientDisconnected` as a normal end and close in `ensure`. `response.stream.ignore_disconnect = true` swaps the exception for silent discards, and `connected?` lets me check first. Any other exception after commit is handled by Live itself, which logs it, runs the `on_error` callback and closes the stream; `rescue_from` never sees it.

code

ruby · 19 lines
ruby
before_action -> { @build = Current.user.visible_builds.find(params[:build_id]) }

def show
  response.headers["Content-Type"] = "text/event-stream"
  sse = ActionController::Live::SSE.new(response.stream, event: "log")
  last = 0

  until @build.reload.finished?
    lines = @build.log_lines.where("number > ?", last).order(:number).to_a
    lines.each { |l| sse.write({ text: l.body }, id: l.number) }
    last = lines.last.number if lines.any?
    sse.write("", event: "heartbeat") if lines.empty?
    sleep 2
  end
rescue ActionController::Live::ClientDisconnected
  logger.info "build #{@build.id} viewer left"
ensure
  response.stream.close
end

go deeper

for a junior

Recall that a Live write raises ActionController::Live::ClientDisconnected once the viewer is gone, and that the stream is always closed in ensure.

for a middle

Explain the chain from the server closing the Rack body to Live::Buffer#abort, and why the action only notices on its next write.

for a senior

Design the loop: authorize in a before_action so nothing is committed yet, heartbeat to detect leavers, rescue ClientDisconnected quietly, and know that post-commit errors bypass rescue_from.

for a principal

Set the policy for abandoned streams, such as heartbeat interval against wasted polling and how failures are reported once a 200 has already gone out.

## How a disconnect reaches the action An `ActionController::Live` action never touches the socket. It writes into a buffer (`Live::Buffer`); the web server thread drains that buffer to the client. A closed browser tab therefore reaches the action indirectly: 1. The server thread fails to send to the gone client and **closes the Rack body**. 2. Rails maps that Rack `close` to `Response#abort`, which calls **`Live::Buffer#abort`**: the buffer marks itself aborted and drops anything queued. 3. The action's **next** `response.stream.write` sees that the buffer is no longer connected and raises **`ActionController::Live::ClientDisconnected`**. The important consequence: the disconnect surfaces only **after the action writes**. The server notices a dead client only when it tries to send something, and the exception (or a `false` from `connected?`) appears after that. A build-log loop that sleeps for a minute between lines can go on polling the database for a viewer who left long ago. Writing a small heartbeat event on a timer bounds how long that can last. ## ClientDisconnected is not an IOError | exception | raised when | |---|---| | `ActionController::Live::ClientDisconnected` | writing after the **client** went away (default behaviour) | | `IOError` ("closed stream") | writing after **your own code** called `close` on the stream | `ClientDisconnected` deliberately subclasses **`RuntimeError`**; the source comments that a disconnect is beyond the developer's control, not an I/O bug. So `rescue IOError` does **not** catch it, while a bare `rescue => e` does. ## ignore_disconnect and connected? - **`response.stream.ignore_disconnect = true`** makes writes after a disconnect succeed silently and discard their data. The action keeps running, which is only right when it has work to finish regardless of the viewer. - **`response.stream.connected?`** returns `false` once the buffer was aborted, which lets a loop check before doing expensive work. ## Errors that happen after commit The response is committed by the first write **or by a close**. Once it is, the status and headers are already on the wire. So `ActionController::Live` handles an exception raised **after** commit itself: 1. For an HTML request it writes `ActionView::Base.streaming_completion_on_exception` (a snippet that sends the browser to `/500.html`). 2. It calls the callback registered with `response.stream.on_error { ... }`. 3. It logs the exception at FATAL level and closes the stream. `rescue_from` handlers and the error pages never see it, and the client already received a 200. An exception raised **before** commit is different: it is re-raised in the request thread and handled the ordinary way. There is a trap between the two. An action whose `ensure` calls `response.stream.close` commits the response on its way out, even when the exception came from a `find` at the top of the same method. Live then sees a committed response and treats the `RecordNotFound` as a mid-stream failure: the viewer gets a 200 with no events instead of a 404. Do lookups and authorization in a `before_action`, which runs and fails before the action's `ensure` exists. ## What the browser sees From the browser's side, a stream ended by `close` simply finishes. An `EventSource` then reconnects after the `retry:` delay and sends the last `id:` it received as `Last-Event-ID`, so an action that finishes normally should send a final event the page treats as "stop listening". A stream ended by an exception after commit looks the same on the wire: a 200 that stopped, which is another reason to send an explicit final event and to log failures in `on_error`. ## A pattern for the build-log loop - Do lookups and authorization in a `before_action`, so failures still produce a proper status. - Rescue `ActionController::Live::ClientDisconnected` around the loop and treat it as a normal end, logged at info level rather than as an error. - Send a heartbeat on a fixed interval when there is nothing new, so a departed viewer is noticed within that interval. - Close the stream in `ensure`; after a disconnect the close simply ends the buffer. - Do not reach for `ignore_disconnect` unless the work must finish anyway, because then nothing stops the loop.

  • Why does rescue IOError not catch a viewer disconnect in a Live action?
    `ActionController::Live::ClientDisconnected` inherits from `RuntimeError`, by design, since a disconnect is outside the developer's control. `IOError` ("closed stream") is what a write raises after the action itself closed the stream. Rescue `ClientDisconnected` by name.
  • The database raises halfway through a streaming action. What does the browser receive, and why does rescue_from not help?
    The status, a 200, and the headers left at the first write. Live rescues the exception in the live thread: for HTML it writes `streaming_completion_on_exception`, calls the stream's `on_error` callback, logs it at FATAL and closes the stream. `rescue_from` cannot change a committed response, so checks that may fail belong before the first write.
  • Why can Build.find at the top of a Live action, with response.stream.close in its ensure, answer a 200 with no events instead of a 404?
    The `ensure` runs while `RecordNotFound` propagates, and closing the stream commits the response with status 200. Live then finds a committed response, so it treats the error as mid-stream: it logs it and closes, and the error-page handling never runs. Loading the record in a `before_action` raises before the action method, so nothing is committed and the 404 survives.

  • A sleeping Live action is interrupted the moment the viewer closes the tab.
  • ClientDisconnected subclasses IOError, so rescue IOError handles it.
  • rescue_from in ApplicationController turns a mid-stream error into a 500 page.
  • ignore_disconnect = true stops the action as soon as the client leaves.
  • Errno::EPIPE from the socket is what a Live action rescues on disconnect.