skip to content

Action Cable

Action Cable adds WebSockets to a Rails app: connections that identify the user, channels that stream broadcasts, and a pub/sub adapter that spans processes. Interviewers probe auth and scale.

part ofRuby on Railsread it →
on this pageshow

explore

questions

10

In Rails Action Cable, how do stream_from and stream_for differ, and how does a server-side broadcast reach a channel's subscribers?

level: juniorimportance: must knowfreq 58%

answer

  1. a broadcasting is a named pub/sub queue
  2. stream_from takes the literal name
  3. stream_for derives it from a record
  4. channel_name plus to_gid_param
  5. broadcast vs broadcast_to

basics

~10 s

stream_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 s

A **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 lines
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

TicketChatChannel.broadcasting_for(SupportTicket.find(42))
# => "ticket_chat:Z2lkOi8vZGVzay9TdXBwb3J0VGlja2V0LzQy"

TicketChatChannel.broadcast_to(SupportTicket.find(42), author: 7, body: "On it")

go deeper

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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].

open as a page

When a Rails app's Action Cable runs on four app servers, which cable.yml adapters deliver every broadcast, and how do solid_cable, redis and postgresql differ?

level: middleimportance: must knowfreq 45%

basics

~20 s

Across four servers any shared adapter works, never async: solid_cable writes each broadcast as a row that every process polls for, redis publishes through a Redis server, and postgresql uses NOTIFY on the app's own database, with payloads capped near 8000 bytes.

open as a page

In a Rails Action Cable connection class, how do identified_by, connect and reject_unauthorized_connection authenticate each WebSocket?

level: middleimportance: must knowfreq 52%

basics

~20 s

ApplicationCable::Connection declares identified_by :current_user; its connect method runs once when the socket opens and sets current_user from a signed cookie, or calls reject_unauthorized_connection, which raises UnauthorizedError so Rails closes the socket with reason unauthorized and no reconnect.

open as a page

In a new Rails 8.1 app, which Action Cable adapter does config/cable.yml set for development, test and production, and why?

level: juniorimportance: should knowfreq 40%

basics

~20 s

A new Rails 8.1 app's config/cable.yml uses async in development, test in test and solid_cable in production, connected to a separate cable database. rails new runs solid_cable:install, which overwrites Rails' own template whose production entry was redis.

open as a page

In a Rails app, how does a createConsumer subscription's perform call from @rails/actioncable reach a method on an Action Cable channel?

level: middleimportance: should knowfreq 42%

basics

~10 s

createConsumer() from @rails/actioncable opens one WebSocket (to the action-cable-url meta tag or /cable); consumer.subscriptions.create({channel: "TicketChatChannel", ticket_id: 42}, callbacks) subscribes; subscription.perform("speak", {body}) calls the channel's public speak(data) method.

open as a page

In Rails Action Cable, what do allowed_request_origins and disable_request_forgery_protection check, and why would production WebSocket upgrades fail with 'Request origin not allowed'?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Before accepting a WebSocket, Action Cable compares the Origin header with the request's own scheme and host, then with config.action_cable.allowed_request_origins (strings or regexes). A mismatch gets a 404 and a 'Request origin not allowed' log line; disable_request_forgery_protection skips the check entirely.

open as a page

In Rails Action Cable, what runs on the worker pool sized by config.action_cable.worker_pool_size, and how does that size affect database connections?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Each process's Action Cable worker pool (worker_pool_size, default 4) runs connect and disconnect, every subscribe and perform command, and each stream callback that transmits a broadcast. Each busy worker can hold an Active Record connection, so the database pool must cover them.

open as a page

In a Rails Action Cable channel, how do you stop a customer from streaming another customer's support-ticket chat, and what does reject actually do?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Treat params in subscribed as untrusted: load the ticket through current_user's own tickets and call stream_or_reject_for (or reject), never stream_from a name built from raw params. reject only marks the subscription; Rails then removes it and the browser's rejected() callback fires.

open as a page

In Rails, how do you test an Action Cable connection and a channel with ActionCable::Connection::TestCase and ActionCable::Channel::TestCase?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Connection tests set cookies, call connect and assert on connection.current_user, or wrap connect in assert_reject_connection. Channel tests call stub_connection(current_user:), subscribe(ticket_id:), then check subscription.confirmed? or rejected?, assert_has_stream_for, and perform with assert_broadcast_on.

open as a page

With Solid Cable as the Rails Action Cable adapter, how do polling_interval and message_retention trade broadcast latency against database load and table growth?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

Each process polls the messages table every polling_interval (0.1 seconds by default), so a shorter interval cuts latency but multiplies queries. message_retention (1 day) is how long rows survive before automatic trimming deletes them; it bounds table size, not what clients can replay.

open as a page