PubSub to Channel subscribers on other nodes

Hello!

I am working on an app where I have an Elixir cluster and have clients connected to Phoenix Channels on various nodes. I am using PubSub to send messages when a request comes into a controller on one node to a Channels client connected potentially on another node. So far I have been using MyAppWeb.Endpoint.broadcast/3 and this works great for clients connected to the channel on the same node. However, the clients connected to other nodes in the cluster aren’t receiving the messages. My question is what should I use to push PubSub messages to Channel subscribers on other nodes?

Any tips would be appreciated.

What you could do is subscribe to a topic in the channel join sequence, and then replace your broadcast with a broadcast on that topic.

Phoenix.PubSub.subscribe(MyApp.Pubsub, "topic")

And

Phoenix.PubSub.broadcast(MyApp.PubSub, "topic", payload)

The topic can be the same for all channel connections or individual by adding some identifier to it, "topic:#{id}".

As each channel is a process it will receive the broadcast to handle_info/2.

Another way would be to start a specific GenServer that listens to the broadcasts from PubSub and then handles them.

Though on reflection I must say that normally if all your nodes are listening to the same PubSub the distribution of the broadcasts to all channels on all nodes is a default.
If this is not the same app running on all your nodes, make sure the PubSub has the same name on all nodes. MyApp.PubSub in both MyApp and MyOtherApp, this will make that PubSub cluster-wide.

This would also be needed to make the above mentioned PubSub method working.

This could be error with your cluster configuration.
We are using libcluster_ec2.
You can check with log your broadcast:

Logger.info(
      "Message published to #{inspect(Node.list())} from #{inspect(Node.self())}"
    )

And this log message list all our cluster nodes.

2 Likes