Channel.broadcast vs Endpoint.broadcast vs PubSub.broadcast

You generally shouldn’t need to care about the implementation details within phoenix pubsub. It currently publishes messages between multiple nodes by broadcasting through the configured inter-node communication adapter (pg or redis based) and locally directly to listeners using elixir’s Registry. That’s why there’s a broadcast and dispatch. But that may change at any time.

Publishing to sockets is not handeled by Phoenix PubSub, but only the channels layer on top.

There’s really two layers here.

  1. There’s the low level pubsub support provided by phoenix pubsub. That really (contrary to its name) is completely independant to phoenix itself. You can send any message through it and the receiving process will receive just that message as is.

  2. Channels however is an phoenix specific abstraction, which builds on pubsub, but brings some additional constraints. E.g. it can only send map data (or recently raw binary values) as messages as channels might communicate with external systems like phoenix.js in browsers. These messages are also wrapped in a phoenix specific struct to include additional metadata about the broadcast.

Endpoint.broadcast / Channel.broadcast are APIs to interact with the 2. layer, while PubSub.broadcast is about the 1. There’s Endpoint.broadcast and Channel.broadcast mostly because the latter is a bit more convenient to use, as a few parameters used to broadcast can be infered from the socket a channel has access to, but you need to use Endpoint.broadcast is you want to broadcast from outside the context of an active channel process.

9 Likes