Run it with
elixir --name global@127.0.0.1 global.exs
Download source
:global gives a process one name across the whole
cluster. Every node agrees on who owns the name, so
it suits singletons: one leader, one scheduler, one
coordinator. We start two peer nodes as on the Nodes
page and connect them to each other explicitly, so
the cluster is fully meshed before we rely on it.
A GenServer registered with name: {:global, ...}.
The module has to exist on every node that runs it.
It uses GenServer.start/3, not start_link:
:erpc.call/4 runs in a short-lived process on the
remote node, and a process linked to it would die
with it as soon as the call returns.
leader runs on: :"global_a@127.0.0.1"
b asks, answer: :"global_a@127.0.0.1"
The name is unique cluster-wide: a second leader on
node b is refused, and we learn where the real one is.
5
26
27
{:error,{:already_started,existing}}=:erpc.call(b,Leader,:start,[:leader])IO.inspect(node(existing),label:"already started on")
already started on: :"global_a@127.0.0.1"
When the owner's node dies, the name is released, so
another node can take over. That happens when the
cluster notices the node is gone, a moment later, and
each node notices on its own. So we wait until both
this node and b, which will register next, see the
name free, instead of assuming it is instant.
6
28
29
30
31
32
33
34
35
36
37
38
39
40
:peer.stop(peer_a)wait_until_free=fnagain->ifEnum.all?([node(),b],&(:erpc.call(&1,:global,:whereis_name,[:leader])==:undefined))do:freeelseProcess.sleep(10)&&again.(again)endendIO.inspect(wait_until_free.(wait_until_free),label:"after a died, :leader is"){:ok,_}=:erpc.call(b,Leader,:start,[:leader])IO.inspect(GenServer.call({:global,:leader},:where),label:"new leader runs on")
07:51:10.994 [warning] 'global' at node :"global@127.0.0.1" requested disconnect from node :"global_a@127.0.0.1" in order to prevent overlapping partitions
after a died, :leader is: :free
new leader runs on: :"global_b@127.0.0.1"
Pitfall: registering a name right after nodes
connect, before :global has synced, can leave the
name visible on one node only for a while. Startup
code that registers singletons should call
:global.sync/0 first.
Pitfall: every registration takes a lock on all
nodes, so it gets slower as the cluster grows. Use
:global for a few long-lived singletons, not for
thousands of short-lived processes: use Registry
per node, or :pg for groups.
Pitfall: after a network partition heals, two
nodes may each hold the same name. :global then
keeps one and, by default, kills the other process.
A "singleton" can briefly run twice, so its work
must tolerate that (idempotent writes, fencing).
Partitions and Split Brain
shows it happen, and
Leases and Fencing Tokens
how to guard against it.