Distribution in depth

The distributed lesson connects two nodes and makes one call across. A system that runs on several nodes needs four more things: a cookie and a name that every node agrees on, a call with a deadline, a monitor that reports a node going down, and a way to find a process without knowing which node it is on. Each of the programs below starts its own second node with peer, so a single machine runs the whole cluster.

A cluster of two

Distribution in Erlang is a name and a secret. The name says who the node is, and the cookie says which nodes may talk to it; -setcookie on the command line or erlang:set_cookie/2 at run time sets the secret, and a node whose cookie differs is refused at the connection. rpc:call/5 takes a timeout as its last argument, which is the difference between a slow node and a hung caller, and rpc:multicall/4 fans a call out and reports which nodes did not answer:

cluster.erl

-module(cluster). -export([run/0]). run() -> logger:set_primary_config(level, none), {ok, P1, N1} = peer:start_link(#{name => node_one}), {ok, P2, N2} = peer:start_link(#{name => node_two}), io:format("ping: ~p ~p~n", [net_adm:ping(N1), net_adm:ping(N2)]), io:format("visible nodes: ~p~n", [length(nodes())]), SameCookie = rpc:call(N1, erlang, get_cookie, []) =:= erlang:get_cookie(), io:format("same cookie: ~p~n", [SameCookie]), yes = global:register_name(course_name, self()), io:format("name here: ~p~n", [global:whereis_name(course_name) =:= self()]), NameThere = rpc:call(N1, global, whereis_name, [course_name]) =:= self(), io:format("name from a peer: ~p~n", [NameThere]), io:format("a slow call: ~p~n", [rpc:call(N2, timer, sleep, [2000], 100)]), {Ok, Bad} = rpc:multicall([N1, N2], erlang, node, []), io:format("multicall: ~p~n", [{length(Ok), length(Bad)}]), global:unregister_name(course_name), peer:stop(P2), peer:stop(P1).

erlc cluster.erl

erl -sname deep_one -noshell -eval 'cluster:run(), halt().'

ping: pong pong visible nodes: 2 same cookie: true name here: true name from a peer: true a slow call: {badrpc,timeout} multicall: {2,0}

The peers inherit the cookie of the node that started them, which is why the fourth line is true; a node started with another cookie would answer pang at the ping and never appear in nodes/0. The slow call shows the deadline: the two second sleep is cut at the hundredth millisecond and the caller gets {badrpc, timeout} without waiting for the answer. A name registered with global is visible on every connected node, which is how a program finds a service without knowing where it runs.

Watching a node

erlang:monitor_node(Node, true) asks the runtime to deliver a {nodedown, Node} message when the connection ends, which a supervisor uses to stop sending work to a node that is gone. The program starts a node, monitors it, stops it and waits for the message:

monitor.erl

-module(monitor). -export([run/0]). run() -> logger:set_primary_config(level, none), {ok, Peer, Node} = peer:start_link(#{name => node_three}), pong = net_adm:ping(Node), true = monitor_node(Node, true), peer:stop(Peer), receive {nodedown, Node} -> io:format("the down message: received~n") after 5000 -> io:format("the down message: missing~n") end.

erlc monitor.erl

erl -sname deep_two -noshell -eval 'monitor:run(), halt().'

the down message: received

The message arrives because the connection went away, not because a process ended: a node can be perfectly healthy and unable to reach the other one, and this is the only report the runtime gives. monitor_node/3 takes the extra option allow_passive_connect for a node that is not connected yet. A process monitor is the finer tool: monitor(process, Pid) works on a pid that lives on another node, as the next program shows.

A process on another node

spawn(Node, Fun) starts the fun on that node and answers a pid the caller can keep; a message to that pid travels over the connection, and monitor(process, Pid) watches it from the caller's node. The program spawns a process on a peer, receives its message and gets the DOWN when it stops:

remote_proc.erl

-module(remote_proc). -export([run/0]). run() -> logger:set_primary_config(level, none), {ok, Peer, Node} = peer:start_link(#{name => node_four}), Self = self(), Pid = spawn(Node, fun() -> Self ! {hello, node()}, receive stop -> ok end end), receive {hello, Where} -> io:format("the message came from the remote node: ~p~n", [Where =:= Node]) end, Ref = monitor(process, Pid), Pid ! stop, receive {'DOWN', Ref, process, Pid, Reason} -> io:format("the monitor saw it end: ~p~n", [Reason]) end, peer:stop(Peer).

erlc remote_proc.erl

erl -sname deep_three -noshell -eval 'remote_proc:run(), halt().'

the message came from the remote node: true the monitor saw it end: normal

The fun travels as a reference to its module, so the module must be loadable on the node that runs it: a release puts the same beams on every node, and a development shell needs the folder on the code path of both. A monitor is the portable report across nodes, because a link would need the two processes to be linked, and a link between nodes does not carry the same guarantees as one inside a node: a partition breaks it silently instead of failing fast.

Groups and names

Two OTP services answer "which processes are in this cluster". pg keeps named groups of pids and synchronises them across the connected nodes: a process joins with pg:join(Group, Pid) on its own node, and pg:get_members(Group) answers the pids of every node in the group. It is the tool for a broadcast: a worker joins the group, and a job goes to every member. pg must be started on each node with pg:start_link/0, and a restarted node rejoins nothing by itself, so the application that owns the worker joins again at start.

global registers one name for the whole cluster, which the program above used: the first node to register wins, every node resolves the name to the same pid, and a name whose node has gone is unregistered when the cluster notices. A program that needs the name to move to a standby node gives global a resolve function with global:register_name/4, and that function decides which of two claimants wins after a partition. The default keeps the first registration, which is fine for one process per cluster and wrong for a standby.

What a partition does

A cluster assumes the nodes can reach each other. When the network splits, each side keeps running, and the runtime cannot tell a broken cable from a dead machine: both look like nodedown. Two nodes that both believe they own a name, a table or a sequence of numbers diverge, and a merge must choose one side. That is why the defaults are conservative: global keeps the first name and does not fail over without a resolve function, and Mnesia stops a table that loses its copies instead of inventing rows.

The practical rules for a distributed program: give every remote call a timeout, monitor the nodes the work goes to, keep the authoritative copy of the data on one node or in a database that resolves conflicts, and design the protocol so that a repeated request is harmless. A message that may arrive twice is cheaper to handle than a cluster that must decide afterwards what happened. The Mnesia lesson shows the store that takes the second of those jobs on itself.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a node need before another node may connect?

    Answer

    The same cookie

    The cookie is the shared secret of the connection, and a mismatch is refused.

  2. What does the last argument of rpc:call/5 set?

    Answer

    A timeout in milliseconds

    The caller stops waiting at the deadline and gets {badrpc, timeout}.

  3. What message does monitor_node(Node, true) deliver when the node goes down?

    Answer

    {nodedown, Node}

    The runtime sends the tuple to the process that asked for node monitoring.

  4. What does spawn(Node, Fun) answer?

    Answer

    A pid on the remote node

    The fun starts on the node, and the caller keeps the pid it answered.

  5. What does pg:get_members(Group) answer?

    Answer

    The pids in the group across the connected nodes

    pg synchronises the group membership of every connected node.

  6. Why does the default global behaviour not fail a name over after a partition?

    Answer

    Two nodes could both claim the name

    A split leaves each side able to register the name, so a resolve function has to decide.

  7. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p~n", [global:whereis_name(nobody)]).

    Answer

    undefined

    A name nobody registered resolves to undefined, even on a node without distribution.

  8. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~p~n", [rpc:call('nobody@127.0.0.1', erlang, node, [], 100)]).

    Answer

    {badrpc,nodedown}

    The local node is not distributed, so the call fails at once with nodedown and never reaches a deadline.

  9. What does this module print? -module(q3). -export([main/0]). main() -> io:format("~p~n", [length(nodes())]).

    Answer

    0

    A node started without a name has no connected nodes, and the local node is not in the list.

  10. What does this module print? -module(q4). -export([main/0]). main() -> io:format("~p~n", [net_kernel:monitor_nodes(true)]).

    Answer

    ok

    The call subscribes the process to node events and answers ok; the events arrive only when distribution carries them.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container, with every peer node on the same machine.

Article author: Arthur Isaev