Supervisors
The GenServer lesson starts a server with start_link/0, and the link is what makes a tree exist: the process that starts a server is its parent, and a crash in the child reaches the parent. A supervisor is that parent written by Erlang itself: it starts a list of children, watches them, and starts a child again when it dies. The program on this page is one supervisor and one child, and the child is a small receive loop so that the whole example is a single module; a real child is the gen_server of the previous lesson, and its specification has the same shape.
A child specification
The supervisor module answers one thing from init/1: the restart strategy with its budget, and a list of child specifications. A specification is a map in OTP 27; the older tuple form still compiles, and the map is the one to write today. id is the name the supervisor knows the child by in its own bookkeeping, not a registered name. start is the module, the function and the arguments that start the child, and that function must answer {ok, Pid}. restart says when the child is started again, shutdown how long it gets to stop, type is worker or supervisor, and modules names the code the child runs, which the release tools read:
supervised.erl
-module(supervised). -behaviour(supervisor). -export([main/0, init/1, start_counter/0]). main() -> logger:set_primary_config(level, none), process_flag(trap_exit, true), {ok, Sup} = supervisor:start_link({local, ?MODULE}, ?MODULE, []), add(2), io:format("count: ~p~n", [value()]), Old = whereis(counter), exit(Old, kill), io:format("restarted: ~p~n", [wait_new(Old, 100)]), io:format("count after restart: ~p~n", [value()]), io:format("children: ~p~n", [supervisor:count_children(Sup)]), exit(Sup, shutdown). init([]) -> Child = #{id => counter, start => {?MODULE, start_counter, []}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}, {ok, {{one_for_one, 5, 10}, [Child]}}. start_counter() -> Pid = spawn_link(fun() -> loop(0) end), true = register(counter, Pid), {ok, Pid}. add(Number) -> counter ! {add, Number}, ok. value() -> counter ! {get, self()}, receive {count, Number} -> Number after 1000 -> timeout end. loop(Count) -> receive {add, Number} -> loop(Count + Number); {get, From} -> From ! {count, Count}, loop(Count) end. wait_new(_Old, 0) -> timeout; wait_new(Old, Tries) -> case whereis(counter) of Pid when is_pid(Pid), Pid =/= Old -> new_pid; _ -> timer:sleep(10), wait_new(Old, Tries - 1) end.
erlc supervised.erl
erl -noshell -eval 'supervised:main(), halt().'
count: 2 restarted: new_pid count after restart: 0 children: [{specs,1},{active,1},{supervisors,0},{workers,1}]
The restart
The program moved the count to two, killed the child with an exit signal the child cannot
catch, waited for the supervisor to start a new one, and read the count again. The
counter came back at zero: a restart starts a new process, so nothing of the old state
survives. A supervisor restores the shape of the system, not its data. Data that must
outlive a crash belongs in an ETS table, in a
database or on disk, not in a process that may be restarted.
The logger is set to none because a killed child makes the
supervisor write a crash report, and that report carries a pid and a timestamp. In a real
system the report is the record of the incident; here it would only be noise around the
output the lesson compares. count_children/1 answers the four
numbers of the tree: the specifications, the children that are running, the children that
are supervisors and the children that are workers.
Restart strategies
The first element of the strategy tuple decides which children a death takes with it. one_for_one restarts only the dead child, and it is the right default for workers that do not depend on each other. one_for_all stops every child and starts them all again, for the set that only makes sense together, such as a cache and the reader that fills it. rest_for_one restarts the dead child and every child started after it, for a chain in which each worker depends on the ones before it. The next program has three children in a row and kills the middle one:
chain.erl
-module(chain). -behaviour(supervisor). -export([main/0, init/1, start_child/1]). main() -> logger:set_primary_config(level, none), process_flag(trap_exit, true), {ok, Sup} = supervisor:start_link({local, ?MODULE}, ?MODULE, []), A = whereis(a), B = whereis(b), C = whereis(c), exit(B, kill), io:format("b restarted: ~p~n", [wait_new(b, B, 100)]), io:format("c restarted: ~p~n", [wait_new(c, C, 100)]), io:format("a kept its process: ~p~n", [whereis(a) =:= A]), exit(Sup, shutdown). init([]) -> Children = [child(a), child(b), child(c)], {ok, {{rest_for_one, 5, 10}, Children}}. child(Name) -> #{id => Name, start => {?MODULE, start_child, [Name]}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}. start_child(Name) -> Pid = spawn_link(fun() -> receive stop -> ok end end), true = register(Name, Pid), {ok, Pid}. wait_new(_Name, _Old, 0) -> timeout; wait_new(Name, Old, Tries) -> case whereis(Name) of Pid when is_pid(Pid), Pid =/= Old -> new_pid; _ -> timer:sleep(10), wait_new(Name, Old, Tries - 1) end.
erlc chain.erl
erl -noshell -eval 'chain:main(), halt().'
b restarted: new_pid c restarted: new_pid a kept its process: true
a was started first and knows nothing of the two behind it, so it kept its process. c was started last and may depend on b, so it went down with it and came back after it. The restart key of a child decides what a death means: permanent always restarts, transient restarts only after an abnormal exit and treats a clean stop as the end, temporary never restarts. The shutdown value is a timeout in milliseconds, infinity for a child that must finish its work, or brutal_kill for a child with nothing to clean up.
A child that is not linked
The most expensive mistake in this lesson is a child whose start function does not link. The supervisor links to the process the start function answers, and that link is the only way it learns that the child died. The next program is the same tree with spawn/1 in place of spawn_link/1, and the child is never restarted:
unlinked.erl
-module(unlinked). -behaviour(supervisor). -export([main/0, init/1, start_worker/0]). main() -> logger:set_primary_config(level, none), process_flag(trap_exit, true), {ok, Sup} = supervisor:start_link({local, ?MODULE}, ?MODULE, []), Old = whereis(worker), exit(Old, kill), io:format("restarted: ~p~n", [wait_new(Old, 100)]), io:format("children: ~p~n", [supervisor:count_children(Sup)]), io:format("listed: ~p~n", [ids(Sup)]), exit(Sup, shutdown). init([]) -> Child = #{id => worker, start => {?MODULE, start_worker, []}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}, {ok, {{one_for_one, 5, 10}, [Child]}}. start_worker() -> Pid = spawn(fun() -> receive stop -> ok end end), true = register(worker, Pid), {ok, Pid}. ids(Sup) -> [Id || {Id, _Pid, _Type, _Modules} <- supervisor:which_children(Sup)]. wait_new(_Old, 0) -> timeout; wait_new(Old, Tries) -> case whereis(worker) of Pid when is_pid(Pid), Pid =/= Old -> new_pid; _ -> timer:sleep(10), wait_new(Old, Tries - 1) end.
erlc unlinked.erl
erl -noshell -eval 'unlinked:main(), halt().'
restarted: timeout children: [{specs,1},{active,0},{supervisors,0},{workers,1}] listed: [worker]
The supervisor still lists a child called worker and counts none of its children as active, and the name behind it is gone. No crash report, no restart, no exception: the tree is quietly one process short, and the next request to that name hits noproc. Every start function of a child is a *_link function for this reason, and gen_server:start_link/3 is the one the previous lesson uses.
The restart budget
The two numbers after the strategy are the budget: the supervisor stops the whole tree when it has restarted more than this many children within this many seconds. A child that crashes once is a bad request; a child that keeps crashing is a bug, and starting it a hundredth time would only hide the bug behind a busy loop. The last program allows one restart in five seconds and kills its child twice:
strict.erl
-module(strict). -behaviour(supervisor). -export([main/0, init/1, start_child/0]). main() -> logger:set_primary_config(level, none), process_flag(trap_exit, true), {ok, Sup} = supervisor:start_link({local, ?MODULE}, ?MODULE, []), First = whereis(worker), exit(First, kill), io:format("first restart: ~p~n", [wait_new(First, 100)]), Second = whereis(worker), exit(Second, kill), receive {'EXIT', Sup, Reason} -> io:format("supervisor: ~p~n", [Reason]) after 2000 -> io:format("supervisor: still running~n") end, io:format("registered: ~p~n", [whereis(?MODULE)]). init([]) -> Child = #{id => worker, start => {?MODULE, start_child, []}, restart => permanent, shutdown => 1000, type => worker, modules => [?MODULE]}, {ok, {{one_for_one, 1, 5}, [Child]}}. start_child() -> Pid = spawn_link(fun() -> receive stop -> ok end end), true = register(worker, Pid), {ok, Pid}. wait_new(_Old, 0) -> timeout; wait_new(Old, Tries) -> case whereis(worker) of Pid when is_pid(Pid), Pid =/= Old -> new_pid; _ -> timer:sleep(10), wait_new(Old, Tries - 1) end.
erlc strict.erl
erl -noshell -eval 'strict:main(), halt().'
first restart: new_pid supervisor: shutdown registered: undefined
The first restart used the budget. The second kill arrived within the same five seconds, so the supervisor gave up and terminated itself with shutdown, which is the signal its own parent understands as a normal stop. Its parent then decides what happens to the whole tree, which is why the budget is a design decision and not a number to raise until the crashes stop.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a supervisor?
Answer
A process that starts and watches children
It starts its children and restarts them according to the child specification.
-
What does
init/1of a supervisor answer?Answer
A restart strategy with a budget and a list of child specs
The answer is
{ok, {Strategy, Children}}, as in{ok, {{one_for_one, 5, 10}, Children}}. -
What does
one_for_onerestart?Answer
Only the child that died
Independent workers restart alone, so the rest of the tree keeps running.
-
What does
rest_for_onerestart?Answer
The dead child and the ones started after it
Later children may depend on the dead one, so they restart after it.
-
Why must a child start function link the process it starts?
Answer
The link is what tells the supervisor that the child died
A child that is not linked dies alone: no exit signal reaches the supervisor, so it never restarts it.
-
What do the numbers in
{one_for_one, 1, 5}mean?Answer
One restart in five seconds at most
The supervisor gives up when it has to restart more than once within five seconds.
-
What does this module print?
-module(q1). -behaviour(supervisor). -export([main/0, init/1]). main() -> {ok, Sup} = supervisor:start_link(?MODULE, []), io:format("~p~n", [supervisor:count_children(Sup)]). init([]) -> {ok, {{one_for_one, 5, 10}, []}}.Answer
[{specs,0},{active,0},{supervisors,0},{workers,0}]An empty child list has no specifications and no active children, and the four counters are reported in that order.
-
What does this module print?
-module(q2). -behaviour(supervisor). -export([main/0, init/1, start_child/1]). main() -> logger:set_primary_config(level, none), {ok, _Sup} = supervisor:start_link(?MODULE, []), A = whereis(a), B = whereis(b), exit(A, kill), timer:sleep(50), io:format("~p~n", [whereis(b) =:= B]). init([]) -> Child = fun(Id) -> #{id => Id, start => {?MODULE, start_child, [Id]}, restart => permanent} end, {ok, {{one_for_one, 5, 10}, [Child(a), Child(b)]}}. start_child(Name) -> Pid = spawn_link(fun() -> receive stop -> ok end end), true = register(Name, Pid), {ok, Pid}.Answer
trueone_for_onerestarts only the dead child, so the other keeps its process. -
What does this module print?
-module(q3). -behaviour(supervisor). -export([main/0, init/1, start_child/1]). main() -> logger:set_primary_config(level, none), {ok, _Sup} = supervisor:start_link(?MODULE, []), A = whereis(a), B = whereis(b), exit(A, kill), timer:sleep(50), io:format("~p~n", [whereis(b) =/= B]). init([]) -> Child = fun(Id) -> #{id => Id, start => {?MODULE, start_child, [Id]}, restart => permanent} end, {ok, {{rest_for_one, 5, 10}, [Child(a), Child(b)]}}. start_child(Name) -> Pid = spawn_link(fun() -> receive stop -> ok end end), true = register(Name, Pid), {ok, Pid}.Answer
truerest_for_onerestarts the dead child and every child started after it, sobis new too. -
What does this module print?
-module(q4). -behaviour(supervisor). -export([main/0, init/1, start_bad/0]). main() -> logger:set_primary_config(level, none), io:format("~p~n", [supervisor:start_link(?MODULE, [])]). init([]) -> Child = #{id => bad, start => {?MODULE, start_bad, []}, restart => permanent}, {ok, {{one_for_one, 5, 10}, [Child]}}. start_bad() -> {error, boom}.Answer
{error,{shutdown,{failed_to_start_child,bad,boom}}}A child that cannot start takes the supervisor down with it, and the reason names the child and its error.
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.
Article author: Arthur Isaev