Clustering Your Application
Elixir and the BEAM have the incredible ability to be clustered together and processes can pass messages seamlessly to each other between nodes. Fly.io makes clustering easy! This extra (and totally optional) portion of the guide walks you through clustering your Elixir application.
There are 2 parts to getting clustering quickly setup on Fly.io.
- Installing and using
libcluster
- Scaling our application to multiple VMs
Adding libcluster
The widely adopted library libcluster helps here.
Libcluster supports multiple strategies for finding and connecting with other nodes. The strategy we’ll use is DNSPoll
which was added in version 3.2.2 of libcluster
, so make sure you’re using that version or newer.
After installing libcluster
, add it to the application like this:
defmodule HelloElixir.Application do
use Application
def start(_type, _args) do
topologies = Application.get_env(:libcluster, :topologies) || []
children = [
# ...
# setup for clustering
{Cluster.Supervisor, [topologies, [name: HelloElixir.ClusterSupervisor]]}
]
# ...
end
# ...
end
Our next step is to add the topologies
configuration to the file config/runtime.exs
.
app_name =
System.get_env("FLY_APP_NAME") ||
raise "FLY_APP_NAME not available"
config :libcluster,
debug: true,
topologies: [
fly6pn: [
strategy: Cluster.Strategy.DNSPoll,
config: [
polling_interval: 5_000,
query: "#{app_name}.internal",
node_basename: app_name
]
]
]
REMEMBER: Deploy your updated app so the clustering code is available, with fly deploy
.
This configures libcluster
to use the DNSPoll
strategy and look for other deployed apps using the same $FLY_APP_NAME
on the .internal
private network.
This assumes that your rel/env.sh.eex
file is configured to name your Elixir node using the $FLY_APP_NAME
. We did this earlier in the “Naming Your Elixir Node” section.
Before this app can be clustered, we need more than one VM. We’ll do that next!
Running multiple VMs
There are two ways to run multiple VMs.
- Scale our application to have multiple Fly Machines in one region.
- Add a Machine to another region (multiple regions).
Both approaches are valid and our Elixir application doesn’t change at all for the approach you choose!
Let’s first start with a baseline of our single deployment.
fly status
...
Machines
PROCESS ID VERSION REGION STATE CHECKS LAST UPDATED
app 6e82dd00f75687 20 sea started 1 total, 1 passing 2023-03-16T22:01:45Z
Scaling in a single region
Let’s scale up to 2 VMs in our current region.
fly scale count 2
Checking on the status we can see what happened.
fly status
...
Machines
PROCESS ID VERSION REGION STATE CHECKS LAST UPDATED
app 5683d474b4658e 20 sea started 1 total, 1 passing 2023-06-16T01:49:36Z
app 6e82dd00f75687 20 sea started 1 total, 1 passing 2023-03-16T22:01:45Z
We now have two VMs in the same region! That was easy.
Let’s make sure they are clustered together. We can check the logs:
fly logs
...
app[5683d474b4658e] sea [info] 21:50:21.924 [info] [libcluster:fly6pn] connected to :"fly-elixir@fdaa:0:1da8:a7b:ac2:f901:4bf7:2"
...
But that’s not as rewarding as seeing it from inside a node. From an IEx shell, we can ask the node we’re connected to, what other nodes it can see.
fly ssh console --pty -C "/app/bin/hello_elixir remote"
iex(fly-elixir@fdaa:0:1da8:a7b:ac2:f901:4bf7:2)1> Node.list
[:"fly-elixir@fdaa:0:1da8:a7b:ac4:eb41:19d3:2"]
I included the IEx prompt because it shows the IP address of the node I’m connected to. Then getting the Node.list
returns the other node. Our two VMs are connected and clustered!
Scaling to multiple regions
Fly.io makes it super easy to run VMs of your applications physically closer to your users. Through the magic of DNS, users are directed to the nearest region where your application is located.
Starting back from our baseline of a single VM running in sea
which is Seattle, Washington (US), I’ll add the region ewr
which is Parsippany, NJ (US). I can do this by cloning the existing Fly Machine into my desired region:
fly machine clone 6e82dd00f75687 --region ewr
Now our status shows we have two Machines spread across 2 regions! This puts a VM on both coasts of the US.
fly status
...
Machines
PROCESS ID VERSION REGION STATE CHECKS LAST UPDATED
app 0e2869ea63d486 20 ewr started 1 total, 1 passing 2023-06-16T01:56:19Z
app 6e82dd00f75687 20 sea started 1 total, 1 passing 2023-03-16T22:01:45Z
Let’s ensure they are clustered together.
fly ssh console --pty -C "/app/bin/hello_elixir remote"
iex(fly-elixir@fdaa:0:1da8:a7b:ac2:cdf6:c422:2)1> Node.list
[:"fly-elixir@fdaa:0:1da8:a7b:ab2:a8e:6666:2"]
We have two VMs of our application deployed to the West and East coasts of the North American continent and they are clustered together! Our users will automatically be directed to the server nearest them. That is so cool!
The cookie situation
Before two Elixir nodes can cluster together, they must share a secret cookie. The cookie itself isn’t meant to be a super secret encryption key or anything like that, it’s designed to let us create multiple sets of small clusters on the same network that don’t all just connect together. Different cookies means different clusters. For instance, only the nodes that all use the cookie “abc” will connect together.
For us, this means that in order for my_remote
node to connect to the cluster on Fly, we need to share the same cookie value used in production.
The cookie problem
When we build a mix release
, it generates a long random string for the cookie value. When we re-run the mix release
command, it keeps the same cookie value. That is, when we don’t run it in Docker. The Dockerfile we’re using is building a fresh release every time we run it. That’s kind of the point of a Docker container. So our cookie value is being randomly generated every time we deploy. This means after every deploy, we would have to figure out what the new cookie value is so our local node can use it.
The cookie solution
The easiest solution here is to specify the value to use for our cookie. One that we will know outside of the build and that won’t keep changing on us.
Making the cookie changes
If we read the Mix.Tasks.Release docs, in the :cookie
section we learn that if we provide an ENV named RELEASE_COOKIE
, it will be used. If that ENV is not found, it falls back to the randomly generated one.
To do this, we can create the cookie we want and store it in our fly.toml
file like this:
[env]
RELEASE_COOKIE = "my-app-cookie"
Also from the docs, we can generate the cookie string to use with this Elixir command:
Base.url_encode64(:crypto.strong_rand_bytes(40))
After deploying the application, we can verify that the cookie is being used by getting an IEx shell into our running server and issuing the following command:
Node.get_cookie()
This shows the cookie being used at runtime.
With a known and unchanging cookie deployed in our application, we are ready for the next step!