Use Channels in a Cluster

Learn about using channels in a cluster.

Cluster

It’s critical to run multiple servers when deploying a production application. Doing so provides benefits for scalability and error tolerance. For example, the ability to double the number of servers in the event of a higher load is much more powerful than doubling the number of cores on a single server. It can take a few minutes to add more machines but could take much longer to move the application to a different machine with more cores. There may also be a time when a single machine is fully utilized, and we cannot add more CPU cores or memory.

Elixir makes connecting a cluster of BEAM nodes very easy. However, we have to ensure that we’re building our application to run across multiple nodes without error. Phoenix Channels handles a lot of this for us because PubSub is for all message broadcasts, which we’ll look at next.

Connecting a local cluster

Let’s jump right in by starting a local Elixir node (an instance of our application) with a name:

Press + to interact
iex --name server@127.0.0.1 -S mix phx.server
[info] Access HelloSocketsWeb.Endpoint at http://localhost:4000
iex(server@127.0.0.1)1>

We use the --name switch to specify a name for our node. We can see the name on the input entry line; ours is located at server@127.0.0.1. Open a new terminal and type the following command to start a second node:

Press + to interact
iex --name remote@127.0.0.1 -S mix
Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)
iex(remote@127.0.0.1)1> Node.list()
[]

We started a second node that doesn’t run a web server by starting mix instead of mix phx.server. We used a different name, remote@127.0.0.1, which gives us two nodes running on the same host domain. We can use Node.list/0 ...