In Rails Action Cable, how do stream_from and stream_for differ, and how does a server-side broadcast reach a channel's subscribers?
answer
- a broadcasting is a named pub/sub queue
- stream_from takes the literal name
- stream_for derives it from a record
- channel_name plus to_gid_param
- broadcast vs broadcast_to
basics
~10 sstream_from subscribes a channel to a broadcasting by its literal string name; stream_for builds that name from a record (channel name plus GlobalID). ActionCable.server.broadcast(name, data) or SomeChannel.broadcast_to(record, data) publishes it to every current subscriber.
solid answer
~30 sA **broadcasting** is a named pub/sub queue. Inside `subscribed`, `stream_from "ticket_chat_42"` attaches the channel instance to a literal name, and you publish with `ActionCable.server.broadcast("ticket_chat_42", { body: "Hi" })`. `stream_for ticket` computes the name with `broadcasting_for`: the channel's `channel_name` (`ticket_chat` for `TicketChatChannel`) joined by a colon to the record's `to_gid_param`. Its matching publisher is `TicketChatChannel.broadcast_to(ticket, body: "Hi")`, so the two sides cannot drift apart. The hash is JSON-encoded, passed through the adapter in `config/cable.yml`, decoded and transmitted to each subscriber, where the JavaScript `received(data)` callback fires. Streams are online only: a browser that subscribes later never sees earlier broadcasts.
code
ruby · 11 linesclass TicketChatChannel < ApplicationCable::Channel
def subscribed
ticket = current_user.support_tickets.find_by(id: params[:ticket_id])
stream_or_reject_for ticket
end
end
TicketChatChannel.broadcasting_for(SupportTicket.find(42))
# => "ticket_chat:Z2lkOi8vZGVzay9TdXBwb3J0VGlja2V0LzQy"
TicketChatChannel.broadcast_to(SupportTicket.find(42), author: 7, body: "On it")go deeper
Recall that stream_from takes a string name and stream_for takes a record, and pair them with ActionCable.server.broadcast and Channel.broadcast_to respectively.
Explain broadcasting_for: channel_name plus the record's GlobalID, why that keeps channels apart, and that a stream is online only, with no replay for late subscribers.
Show you route broadcasts through record-derived names so publishers cannot drift, and know that delivery fans out through the pub/sub adapter to every process holding the stream.
Weigh record-scoped streams against shared feeds for chat-heavy pages: how many broadcastings each page holds, what each costs on the adapter, and where message history must come from instead.
## What a broadcasting is Action Cable separates **who publishes** from **who listens**. The meeting point is a **broadcasting**: a plain string that names a pub/sub queue held by the subscription adapter configured in `config/cable.yml`. A **channel** instance (one per browser subscription) attaches itself to one or more broadcastings with a **stream**; any code in the app, such as a controller, a model or a job, publishes to a broadcasting by name. The source comment on `ActionCable::Channel::Streams` calls it "purely an online queue": if a subscriber is not streaming at the moment a message is sent, it never receives that message. In a customer-service desk where each support ticket has a live chat, the broadcasting is "the chat for ticket 42", and every agent and customer viewing that ticket holds a stream on it. ## stream_from: you choose the name `stream_from(broadcasting, callback = nil, coder: nil, &block)` converts its argument with `String(...)` and subscribes to exactly that name: ```ruby class TicketChatChannel < ApplicationCable::Channel def subscribed ticket = current_user.support_tickets.find_by(id: params[:ticket_id]) stream_or_reject_for ticket end end # elsewhere, after a message is saved TicketChatChannel.broadcast_to(ticket, author: current_user.id, body: message.body) ``` With `stream_from` the publisher must build the identical string, for example `ActionCable.server.broadcast("ticket_chat_#{ticket.id}", ...)`. That suits names that are not tied to a record (`"desk_announcements"`), but every publisher has to repeat the naming rule. ## stream_for: Rails derives the name from a record `stream_for(broadcastables, ...)` simply calls `stream_from(broadcasting_for(broadcastables), ...)`. The class method `broadcasting_for` joins the channel's `channel_name` with each object's serialised form: | Input | Serialised as | Example broadcasting | |---|---|---| | A record (responds to `to_gid_param`) | URL-safe Base64 of its GlobalID | `ticket_chat:Z2lkOi8v...` | | A string or number | `to_param` | `ticket_chat:all` | | An array | each element, joined with `:` | `ticket_chat:<gid>:<gid>` | `channel_name` is the class name underscored without the `Channel` suffix, with namespaces turned into colons, so `Desk::TicketChatChannel` gives `desk:ticket_chat`. Because the channel name is part of the string, two channels that stream the same ticket never share a broadcasting. Rails 8.1.0's changelog lists `stream_for` accepting an array, as in `stream_for [ticket, ticket.customer]`. ## Publishing: broadcast and broadcast_to - `ActionCable.server.broadcast(broadcasting, message, coder: ActiveSupport::JSON)` publishes to a literal name; the message is JSON-encoded by default. - `TicketChatChannel.broadcast_to(record, message)` is shorthand for `ActionCable.server.broadcast(TicketChatChannel.broadcasting_for(record), message)`. - `ActionCable.server.broadcaster_for(name)` returns a reusable object whose `broadcast(message)` sends to that name. - A channel instance also has `broadcast_to`, delegating to its class. ## What happens to one message 1. The publisher encodes the hash and hands it to the pub/sub adapter (`solid_cable`, `redis`, `postgresql` or, in one process only, `async`). 2. Every server process with a stream on that broadcasting receives it from the adapter. 3. Each matching stream handler runs on the Action Cable worker pool, decodes the JSON and calls `transmit`, which writes a frame tagged with that subscription's identifier. 4. In the browser, `@rails/actioncable` routes the frame to the subscription and calls its `received(data)` callback. ## Variations worth knowing - A channel may hold **several streams**; `stop_stream_from(name)`, `stop_stream_for(record)` and `stop_all_streams` remove them, and Rails stops them all on unsubscribe. - Passing a block or callback to `stream_from` / `stream_for` replaces the default re-transmit, so the block must call `transmit` itself. `coder: ActiveSupport::JSON` decodes the message before the block sees it; the default `coder: nil` hands it the raw string. - Turbo's `broadcasts_to` and `turbo_stream_from` are built on these primitives but are a separate API with their own channel. ## Mistakes interviewers listen for - **Expecting history.** A stream starts empty. Render the ticket's last messages from the database with the page, and let the stream carry only what arrives afterwards. - **Mismatched names.** If the channel calls `stream_for ticket` but a controller broadcasts to `"ticket_#{ticket.id}"`, nothing is delivered and nothing raises: the adapter simply has no subscriber for that string. The server log line `TicketChatChannel is streaming from ticket_chat:...` shows the name the channel actually used. - **Broadcasting whole records.** The message is encoded with `ActiveSupport::JSON`, so an Active Record object becomes its `as_json` hash with every attribute. Build the payload explicitly (author, body, timestamp) so internal fields never reach a customer's browser. - **One stream per message type.** A single ticket stream can carry several kinds of payload; add a `type` key rather than opening a broadcasting for each event. ## Choosing between them Prefer `stream_for` with `broadcast_to` whenever the stream belongs to a record: the name is derived in one place, it includes the channel, and the record itself is easy to authorise in `subscribed`. Use `stream_from` for names that are not records, such as a desk-wide announcements feed.
- What broadcasting name does TicketChatChannel's stream_for build for a SupportTicket, and why does it matter that the channel name is included?`broadcasting_for(ticket)` returns `"ticket_chat:"` followed by `ticket.to_gid_param`, the URL-safe Base64 form of `gid://<app>/SupportTicket/42`. Because the channel's `channel_name` is the prefix, `OtherChannel.broadcast_to(ticket, ...)` publishes to a different string and never reaches `TicketChatChannel` subscribers, even for the same record.
- How can a channel change a message before it reaches the browser?Pass a block or callback to `stream_from` or `stream_for`. Rails then calls it instead of re-transmitting, so the block must call `transmit` itself. With `coder: ActiveSupport::JSON` the block receives the decoded hash; with the default `coder: nil` it receives the raw JSON string.
- Can one channel instance stream more than one broadcasting?Yes. Each `stream_from` or `stream_for` call adds a stream to the subscription. `stop_stream_from`, `stop_stream_for` and `stop_all_streams` remove them, and Rails runs `stop_all_streams` automatically when the subscription is unsubscribed.
A broadcasting is a radio frequency: stream_from tunes a receiver to a named frequency, stream_for tunes it to the frequency printed on a record's label, and broadcast transmits on it. Only receivers tuned in at that moment hear the message; turning one on later gives silence, not a recording.
- stream_for "ticket_42" and stream_from "ticket_42" listen to the same broadcasting.
- A browser that subscribes later still receives the messages broadcast before it joined.
- broadcast_to on one channel class reaches stream_for subscribers of every channel for that record.
- Calling stream_from a second time replaces the channel's first stream.
- A broadcast goes straight to the browser without passing through the cable.yml adapter.
Assumes Rails 8.1; the 8.1.0 Action Cable changelog adds stream_for with an array of objects, such as stream_for [ticket, ticket.customer].