Scaling Out With Elixir Distribution: Add and Remove Nodes Without Downtime
| 11 minutes read
I wanted to understand what Elixir’s distribution feature actually buys me. Could I start the same application on another machine, have it share the workload, and remove a machine again without restarting the others?
Two everyday problems made this concrete. A scheduled task should run on one instance, even when the application has several. A state change that invalidates a cache should reach every instance. Both require coordination, but neither necessarily requires a message broker.
The BEAM, the runtime behind Erlang and Elixir, already lets processes communicate across machines. I used a small tick-processing script to explore how that becomes a useful scaling pattern, where it differs from JMS, and where its guarantees stop.
Start with two machines
A tick every second is deliberately boring work. It makes the interesting part visible: which machine handles it, and what changes when another machine joins.
Starting the cluster is the same command on every machine, only the name and one peer differ:
# first node
elixir --name tick@10.0.0.1 --cookie YOUR_SHARED_COOKIE tick_cluster_v2.exs
# scale out: start the same file on a new machine, point it at ANY existing node
TICK_PEERS="tick@10.0.0.1" elixir --name tick@10.0.0.2 --cookie YOUR_SHARED_COOKIE tick_cluster_v2.exs
Nothing on the first node is touched or restarted. Once both nodes are connected and their membership views agree, the intended output looks like this:
[tick@10.0.0.1] processed tick #1795969572
[tick@10.0.0.2] processed tick #1795969573
[tick@10.0.0.1] processed tick #1795969574
[tick@10.0.0.2] processed tick #1795969575
Start a third machine and the rotation includes it. Stop one and the remaining machines adjust their share. Distribution supplies the connections; the application supplies the rule for dividing work.
Connecting is the first building block
Each distributed BEAM instance has a node name. Nodes authenticate using a shared cookie and connect with Node.connect/1. With the default visible-node setup and :global synchronization, a connected cluster forms a full mesh: connecting C to A also brings C into contact with B. Every pair must be reachable.
That is what makes scaling out simple. A new node only needs to know one live member:
peers =
System.get_env("TICK_PEERS", "")
|> String.split(",", trim: true)
|> Enum.map(&String.to_atom(String.trim(&1)))
# on every tick:
Enum.each(state.peers, &Node.connect/1)
The script retries its configured peers on every tick. An existing connection returns true; an unsuccessful attempt returns false. For a real application, log failures and keep several seed peers so losing the first machine does not strand new or restarting nodes.
The current membership is always available:
Node.list() #=> [:"tick@10.0.0.1", :"tick@10.0.0.3"]
Node.list/0 is this node’s view of its current connections, not an instantaneous, authoritative membership list. Nodes disappear when disconnection is detected; a clean shutdown is generally faster to detect than an unresponsive machine.
Sharing work without a dispatcher
There is no central timer sending out jobs. Each node generates its own tick and computes which node should handle it.
First, all nodes need to agree which tick they’re talking about. The tick id is the current Unix second, and the timer is aligned to the second boundary:
now = System.system_time(:millisecond)
Process.send_after(self(), :tick, 1_000 - rem(now, 1_000))
id = System.system_time(:second)
Second, every node computes the owner of that tick with the same arithmetic:
nodes = Enum.sort([node() | Node.list()])
owner = Enum.at(nodes, rem(id, length(nodes)))
cond do
owner == node() -> if state.busy < state.max, do: try_claim(id)
true -> Process.send_after(self(), {:fallback, id}, @grace)
end
When membership views agree, sorting the list and taking id mod n gives everyone the same answer. Two nodes alternate; three rotate. No dispatch message is needed.
This is the application’s scaling rule, not something distribution does automatically. It divides ticks evenly, not CPU usage or execution time. The fallback handles some imbalance when a node is busy.
Claiming a tick, and the limits of that claim
Two nodes can temporarily disagree about ownership. The example therefore uses :global, OTP’s distributed name registry, to claim a tick before working on it.
In a connected, synchronized cluster, competing registrations of the same name produce one winner. The essential operation is:
case :global.register_name({:tick, id}, self()) do
:yes -> work(id)
:no -> :already_claimed
end
A separate process owns the registration, runs the work, and stays alive for another ten seconds. That briefly retains the claim after completion, preventing late contenders from immediately repeating the tick. Its exit releases the name.
This is not exactly-once execution. Isolated nodes can both claim a tick before connecting, and a network partition can allow both sides to work. Reconciliation may terminate a claimant, but it cannot undo an email already sent. A global: Name conflict terminating ... message is evidence of that conflict, not proof that it was harmless.
When the owner is busy
Non-owners do not simply ignore a tick. They wait a short grace period and check if anyone claimed it:
def handle_info({:fallback, id}, state) do
if state.busy < state.max and :global.whereis_name({:tick, id}) == :undefined,
do: try_claim(id)
{:noreply, state}
end
After 300 ms, a free non-owner attempts an unclaimed tick. This is one fallback attempt, not a retry queue: if everyone is busy, the tick is skipped. It also does not recover work that already started on a node that subsequently crashed.
The script tracks busy against TICK_MAX_CONCURRENCY. For the logging demo this is enough to illustrate load shedding. A production worker should reserve capacity before spawning claim attempts and monitor workers: the current asynchronous counter can lag, and a crashed worker never sends :done.
Adding capacity is easy; removing it needs care
Scaling out means starting the application with a unique node name and a reachable seed peer. Existing instances keep running, and their ownership calculations include the newcomer once membership converges.
Scaling in changes that list again. To avoid interrupting work, a real application must drain the departing worker: stop accepting new jobs, finish current ones, then disconnect. The demo does not implement draining.
The useful promise is that remaining instances need not restart. Lossless handover and uninterrupted service still depend on the application, available capacity, and how failures are handled.
How this compares to JMS
JMS is a Java messaging API, implemented by providers such as ActiveMQ Artemis and IBM MQ. Its familiar competing-consumer queue resembles the goal here: add workers and let them share the workload. The mechanism is different.
| Concern | JMS queue with a broker | This BEAM example |
|---|---|---|
| Work assignment | Broker delivers messages to consumers | Nodes compute ownership and claim ticks |
| Adding workers | Connect another consumer | Connect another node |
| Backlog | Broker holds queued messages | Busy ticks can be skipped |
| Failure recovery | Persistent messages and acknowledgements can support redelivery | No durable recovery; duplicates and missed ticks are possible |
| Communication | Through the messaging provider | Directly between BEAM processes |
Distribution is communication infrastructure; a queue is a work-management system. Connecting nodes does not give you persistence, acknowledgements, retries or dead-letter handling. Conversely, a queue is unnecessary just to notify other live instances of a cache change.
JMS transactions can coordinate messaging operations, but they do not automatically make external side effects, such as sending an email, exactly once. That problem exists on both sides of the comparison.
Real-world uses: schedulers and cache invalidation
Two situations come up again and again, and they use the same mesh in two different ways.
Scheduled jobs: one node does it
Typical case: every 5 minutes, send all emails that are due. The state lives in MongoDB, for example a mails collection where each document has a state and a send_at. The job is “find everything in state pending that is due, send it, mark it sent”.
MongoDB already stores what needs doing. The cluster’s role is narrower: choose which instance checks for due mail, without designating a permanent scheduler machine.
For a five-minute schedule, the shared identifier could be:
# one id per 5 minutes, same on every node
id = div(System.system_time(:second), 300)
Changing the id alone is not enough: the demo polls every second and retains claims for only ten seconds, so it would repeatedly reclaim the same five-minute bucket. A scheduler also needs bucket-level triggering and deduplication across the scheduling window. Use durable execution records if that must survive restarts.
Once triggered, the worker repeatedly claims a due document. Here is the MongoDB operation in mongosh syntax; the equivalent query belongs in the Elixir worker:
db.mails.findOneAndUpdate(
{ state: "pending", send_at: { $lte: new Date() } },
{ $set: { state: "sending", claimed_at: new Date() } },
{ sort: { send_at: 1 }, returnDocument: "after" }
)
The state transition is atomic for that document: two workers cannot both claim the same pending mail. Send the returned mail, mark it sent, and continue until no due document remains.
That still does not guarantee exactly-once delivery. A worker can send the email and crash before marking it sent. Recovering stale sending documents may then resend it. Use a provider idempotency key where supported, plus an explicit retry and stale-claim policy.
For this workflow, MongoDB can hold the pending work while Elixir coordinates the periodic check. A separate queue becomes useful when you need its delivery, retry or integration features, not merely because you have several application instances.
Invalidation: all nodes do it
Now reverse the requirement: a state change means every instance must drop its cached copy. There is no owner to elect. Broadcast instead.
With :pg (process groups, part of OTP), each node registers a process in a named group, and any node can message the whole group, wherever its members run:
defmodule CacheInvalidator do
use GenServer
def start_link(_), do: GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
def invalidate(key) do
for pid <- :pg.get_members(:cache_nodes) do
send(pid, {:invalidate, key})
end
end
@impl true
def init(:ok) do
:pg.join(:cache_nodes, self())
{:ok, %{}}
end
@impl true
def handle_info({:invalidate, key}, state) do
MyCache.delete(key)
{:noreply, state}
end
end
Start :pg before CacheInvalidator in each node’s supervision tree. Group membership propagates between connected nodes and tracks process exits. :pg maintains the group; the send/2 loop performs the broadcast, including local invalidation.
Call invalidate/1 after the database change commits. MyCache represents your application’s cache. In Phoenix, Phoenix.PubSub provides a convenient topic-based alternative.
This resembles a JMS topic, but without durable subscriptions or replay. Disconnected nodes can miss invalidations, so use cache TTLs, version checks or a cache flush when reconnecting. Sending a message is not an acknowledgement that every recipient processed it.
Practical notes
- Local testing: use
--sname tick1and--sname tick2. Long names (--name) rejectlocalhost. Don’t mix--nameand--snamenodes in one cluster. - Networking: nodes need to reach each other on epmd (port 4369) plus the distribution ports. Never expose these to the internet. I run them inside a Tailscale/Headscale network so the traffic stays private. You can pin the port range with
--erl "-kernel inet_dist_listen_min 9100 inet_dist_listen_max 9105". - Cookie: whoever has the cookie can run arbitrary code on every node. Use a long random value, and treat it like a root password.
- Clocks: keep them synchronized; even small differences affect the 300 ms fallback.
- Deployment: use compatible OTP versions and application code. A full mesh has quadratic connection growth, so benchmark rather than assuming unlimited scale.
The full script
defmodule TickCluster do
use GenServer
@interval 1_000
@claim_ttl 10_000
@grace 300
def start do
{:ok, _} = start_link([])
Process.sleep(:infinity)
end
def start_link(_), do: GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
@impl true
def init(:ok) do
max = System.get_env("TICK_MAX_CONCURRENCY", "1") |> String.to_integer()
peers =
System.get_env("TICK_PEERS", "")
|> String.split(",", trim: true)
|> Enum.map(&String.to_atom(String.trim(&1)))
IO.puts("[#{node()}] online, max concurrency #{max}")
send(self(), :tick)
{:ok, %{max: max, peers: peers, busy: 0}}
end
@impl true
def handle_info(:tick, state) do
# Align to wall-clock seconds so every node targets the same tick id.
Process.send_after(self(), :tick, @interval - rem(System.system_time(:millisecond), @interval))
Enum.each(state.peers, &Node.connect/1)
id = System.system_time(:second)
nodes = Enum.sort([node() | Node.list()])
owner = Enum.at(nodes, rem(id, length(nodes)))
cond do
owner == node() -> if state.busy < state.max, do: try_claim(id)
true -> Process.send_after(self(), {:fallback, id}, @grace)
end
{:noreply, state}
end
# The owner didn't take the tick (busy or down), so any free node may.
def handle_info({:fallback, id}, state) do
if state.busy < state.max and :global.whereis_name({:tick, id}) == :undefined,
do: try_claim(id)
{:noreply, state}
end
def handle_info({:claimed, true}, state), do: {:noreply, %{state | busy: state.busy + 1}}
def handle_info({:claimed, false}, state), do: {:noreply, state}
def handle_info(:done, state), do: {:noreply, %{state | busy: max(state.busy - 1, 0)}}
# A claim coordinates contenders within a connected, synchronized cluster.
defp try_claim(id) do
parent = self()
spawn(fn ->
case :global.register_name({:tick, id}, self()) do
:yes ->
send(parent, {:claimed, true})
work(id)
send(parent, :done)
# Hold the name briefly so a node with a late clock can't re-claim it.
Process.sleep(@claim_ttl)
:no ->
send(parent, {:claimed, false})
end
end)
end
defp work(id) do
IO.puts("[#{node()}] processed tick ##{id}")
end
end
TickCluster.start()
This is a learning example, not a durable scheduler. Before using it for consequential work, add supervision, worker monitoring, draining and application-level deduplication.
Takeaway
The interesting discovery was not that Elixir replaces a broker. It was that connecting application instances gives me a direct way to coordinate them: pick one worker for a scheduled check, or notify every worker of a state change.
Nodes can join and leave without restarting their peers. The application decides how work follows that changing membership, while the database or a durable queue handles anything that must survive failure. Those are separate responsibilities, and keeping them separate makes the design simpler.