skip to content

With turbo-rails, how does broadcasts_refreshes_to keep every open chores page current, and how are the resulting refreshes debounced and de-duplicated?

level: middleimportance: should knowfreq 30%

answer

  1. after_commit sends a refresh stream
  2. turbo_stream_from subscribes the page
  3. request-id skips the sender's own tab
  4. 0.5 s server debounce per thread
  5. 150 ms client debounce

basics

~20 s

broadcasts_refreshes_to adds an after_commit callback that broadcasts a refresh stream to a named stream; pages subscribed with turbo_stream_from re-fetch and morph. A 0.5 s server debounce and a 150 ms client debounce coalesce bursts, and a request-id skips the sender's tab.

solid answer

~40 s

`broadcasts_refreshes_to :household` in the `Chore` model adds an `after_commit` that calls `broadcast_refresh_later_to(household)`. Pages that render `turbo_stream_from @household` hold an Action Cable subscription to that stream. The broadcast carries no HTML, just `<turbo-stream action="refresh" request-id="...">`; each receiving tab re-fetches its current URL with a `replace` visit, which morphs if the page asks for it. Bursts are coalesced twice. On the server, `broadcast_refresh_later_to` goes through a per-thread debouncer keyed by stream and request id with a 0.5 s delay, so a request that touches twenty chores enqueues one job. In the browser, `Turbo.session.refresh` is debounced by 150 ms. The `request-id` is the `X-Turbo-Request-Id` the originating tab sent; that tab remembers its last 20 ids and ignores its own refresh, since its redirect already updated it. A refresh is also ignored while a visit is in flight.

code

ruby · 9 lines
ruby
class Chore < ApplicationRecord
  belongs_to :household
  broadcasts_refreshes_to :household
end

# A bulk import without a refresh per row
Chore.suppressing_turbo_broadcasts do
  rows.each { |row| household.chores.create!(row) }
end

go deeper

for a junior

Know that broadcasts_refreshes_to plus turbo_stream_from makes other open pages reload themselves when a record changes.

for a middle

Trace the after_commit callback, the refresh stream with its request-id, the 0.5 s server and 150 ms client debounces, and the stream each macro broadcasts to.

for a senior

Size the fan-out (one page render per subscribed tab), pick the stream that list pages actually subscribe to, and suppress broadcasts for bulk jobs.

for a principal

Decide where a refresh signal is cheaper to own than hand-written stream updates, given page render cost and the number of concurrent viewers.

## The model: one signal, many re-renders Targeted Turbo Streams send the HTML for each change. **Refresh broadcasts** send a single signal, "this page may be stale", and let each viewer fetch the page again. Combined with morphing, the user sees the changed rows update in place. turbo-rails wires this up from the model: ```ruby class Chore < ApplicationRecord belongs_to :household broadcasts_refreshes_to :household end ``` ```erb <%# app/views/chores/index.html.erb %> <%= turbo_stream_from @household %> <% turbo_refreshes_with method: :morph, scroll: :preserve %> ``` ## What each macro registers | Macro | Create | Update | Destroy | |---|---|---|---| | `broadcasts_refreshes_to :household` | `broadcast_refresh_later_to(household)` from one `after_commit` | same | same | | `broadcasts_refreshes` | `broadcast_refresh_later_to("chores")`, the plural model name | `broadcast_refresh_later` to the record's own stream | `broadcast_refresh`, synchronous, to the record's own stream | The table explains a common surprise: a list page subscribed to `"chores"` with plain `broadcasts_refreshes` hears about creates but not about updates or deletes, because those go to each record's own stream. For a list scoped to a parent, `broadcasts_refreshes_to` the parent is the usual choice. The callbacks run after commit, so a rolled-back change broadcasts nothing. ## The journey of one refresh 1. A member ticks a chore. Turbo's request carries `X-Turbo-Request-Id`, a UUID it also stores in a list of its 20 most recent request ids. 2. turbo-rails' `Turbo::RequestIdTracking` wraps the action and exposes the header as `Turbo.current_request_id`. 3. On commit, `broadcast_refresh_later_to` asks `Turbo::ThreadDebouncer` for a debouncer keyed by the stream name *and* the request id, in the current thread, with `Turbo::Debouncer::DEFAULT_DELAY` of 0.5 seconds. Every further call with the same key within the delay cancels the pending task and schedules a new one. 4. When the delay passes, one `Turbo::Streams::BroadcastStreamJob` is enqueued with `<turbo-stream action="refresh" request-id="...">`. 5. The job broadcasts it over Action Cable to every subscriber of the household stream. 6. Each tab's `refresh` action calls `Turbo.session.refresh`, itself debounced by 150 ms. It does nothing if the request id is one of this tab's recent requests, if a visit is already in flight, or if the URL is not the current one; otherwise it starts a `replace` visit to the current URL. 7. The visit is a page refresh, so with the morph meta tag the page morphs and, with `preserve`, keeps its scroll. The tab that made the change skips step 7 for its own broadcast: its form submission already redirected and refreshed it, and a second refresh would only cost a request. ## What the debouncing does and does not cover - The server debounce coalesces bursts **inside one thread** for the same stream and request id, typically all the commits of one request. Two different requests produce two refreshes. - The client debounce coalesces refresh streams that arrive within 150 ms of each other in a tab. - Neither reduces the fan-out: every subscribed tab still performs a full page GET per refresh it acts on. ## Matching the stream names The model and the page must name the same stream. `broadcasts_refreshes_to` accepts a symbol (a method on the record, such as `:household`) or a lambda returning an array, for example `->(chore) { [chore.household, :chores] }`; the page then subscribes with `turbo_stream_from @household, :chores`. A mismatch fails silently: the broadcast goes out and no page is listening. `turbo_stream_from` renders a `<turbo-cable-stream-source>` element whose `signed-stream-name` is signed by the server, so a browser cannot subscribe to a stream it was never given. Who may see a household's refreshes is therefore decided by who may render the page that contains the subscription. ## Costs and controls - **Render load scales with viewers.** One change to a household with eight open tabs means up to seven page renders. Cheap pages make this fine; expensive ones may call for targeted streams instead. - **Silencing.** `Chore.suppressing_turbo_broadcasts { ... }` suppresses broadcasts for bulk imports or seeds. - **Testing.** turbo-rails' `assert_turbo_stream_broadcasts` and `capture_turbo_stream_broadcasts` check that a refresh was broadcast to the expected stream. - **Delivery.** The broadcast travels through Action Cable, over whichever adapter `config/cable.yml` names, and the job through the app's Active Job backend, so both must be running for refreshes to arrive.

  • Why does a list subscribed to the model's plural stream miss updates when the model uses plain broadcasts_refreshes?
    `broadcasts_refreshes` sends creates to the plural stream ("chores") but sends updates and destroys to each record's own stream. A list page subscribed only to "chores" never hears about them. Broadcasting to a parent with `broadcasts_refreshes_to :household` sends every change to one stream.
  • Why does the tab that made the change ignore the refresh broadcast?
    Turbo sends an `X-Turbo-Request-Id` header with every request and remembers the last 20 ids. turbo-rails copies that id into the refresh stream's `request-id`, so the originating tab recognises its own change and skips a refresh its redirect has already performed.
  • Does the server debounce stop two users' simultaneous changes from causing two refreshes?
    No. The debouncer is keyed by stream and request id and lives in the current thread, so it coalesces the commits of one request. Two requests produce two broadcasts; the 150 ms client debounce may still merge them if they arrive close together.

  • The refresh broadcast carries the rendered HTML of the changed chore.
  • broadcasts_refreshes sends updates to the plural stream, so list pages see every change.
  • The server debounce merges refreshes from all users across every Puma process.
  • The tab that made the change refreshes twice, once from its redirect and once from the broadcast.
  • broadcasts_refreshes sends destroys through a background job, just like creates and updates.
  • Refresh broadcasts fire inside the transaction, before the commit.

Assumes turbo-rails 2.0.x (Turbo::Debouncer::DEFAULT_DELAY 0.5 s) with Turbo 8's client-side 150 ms refresh debounce, on Rails 8.1.