Supervision trees
One supervisor with a list of workers is a flat system, and a real Erlang system is a tree: a supervisor of supervisors, each level with its own children and its own restart budget. The nesting is what makes a failure local. A worker that crashes inside a sub-tree is restarted by the supervisor of that sub-tree, the rest of the system never notices, and the number of restarts a level may spend is a property of that level, not of the whole node. The supervisors lesson has one supervisor and its child; this lesson puts supervisors inside supervisors.
A nested tree
The program below is a top supervisor with two children, and each child is a supervisor with one worker. The same module plays both parts: the arguments of init/1 say which level is being started, and a child of type supervisor is a child whose start function starts a supervisor rather than a worker. Its shutdown is infinity, because a supervisor stops its own children and the time that takes is not something the parent should cut short:
nested.erl
-module(nested). -behaviour(supervisor). -export([main/0, init/1, start_sub/1, start_worker/1]). main() -> {ok, Top} = supervisor:start_link({local, ?MODULE}, ?MODULE, top), io:format("top: ~p~n", [supervisor:count_children(Top)]), io:format("top children: ~p~n", [ids(Top)]), Left = whereis(left_sup), io:format("left: ~p~n", [supervisor:count_children(Left)]), io:format("left children: ~p~n", [ids(Left)]), unlink(Top), stop(Top). init(top) -> Children = [sub(left), sub(right)], {ok, {{one_for_one, 3, 10}, Children}}; init({sub, Name}) -> Child = #{id => Name, start => {?MODULE, start_worker, [Name]}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}, {ok, {{one_for_one, 3, 10}, [Child]}}. sub(Id) -> #{id => Id, start => {?MODULE, start_sub, [Id]}, restart => permanent, shutdown => infinity, type => supervisor, modules => [?MODULE]}. start_sub(Id) -> supervisor:start_link({local, sup_name(Id)}, ?MODULE, {sub, Id}). sup_name(Id) -> list_to_atom(atom_to_list(Id) ++ "_sup"). start_worker(Name) -> Pid = spawn_link(fun() -> receive stop -> ok end end), true = register(Name, Pid), {ok, Pid}. ids(Sup) -> lists:sort([Id || {Id, _Pid, _Type, _Modules} <- supervisor:which_children(Sup)]). stop(Sup) -> Ref = monitor(process, Sup), exit(Sup, shutdown), receive {'DOWN', Ref, process, Sup, _Reason} -> ok end.
erlc nested.erl
erl -noshell -eval 'nested:main(), halt().'
top: [{specs,2},{active,2},{supervisors,2},{workers,0}] top children: [left,right] left: [{specs,1},{active,1},{supervisors,0},{workers,1}] left children: [left]
The top has two children, and both of them are supervisors, so its workers count is zero and its supervisors count is two. One level down, the sub-supervisor has one child and that child is a worker. The counts are the quickest way to see whether a tree has the shape the source claims, and a release changes them at boot.
What a nested restart costs
A crash travels up the links until a process that traps exits and restarts the child handles it. In a nested tree that is usually the supervisor directly above the crashed worker, so the cost of the failure is the sub-tree and not the top. This program kills a worker inside the left sub-tree, then kills the sub-supervisor itself:
propagation.erl
-module(propagation). -behaviour(supervisor). -export([main/0, init/1, start_sub/0, start_worker/1]). main() -> logger:set_primary_config(level, none), process_flag(trap_exit, true), {ok, _Top} = supervisor:start_link({local, ?MODULE}, ?MODULE, top), A = whereis(a), B = whereis(b), Left = whereis(left_sup), exit(A, kill), io:format("a restarted: ~p~n", [wait_new(a, A, 100)]), io:format("b kept its process: ~p~n", [whereis(b) =:= B]), A2 = whereis(a), exit(Left, kill), io:format("sub supervisor restarted: ~p~n", [wait_new(left_sup, Left, 100)]), io:format("its worker came with it: ~p~n", [wait_new(a, A2, 100)]). init(top) -> Children = [#{id => left, start => {?MODULE, start_sub, []}, restart => permanent, shutdown => infinity, type => supervisor, modules => [?MODULE]}, #{id => b, start => {?MODULE, start_worker, [b]}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}], {ok, {{one_for_one, 3, 10}, Children}}; init(left) -> Child = #{id => a, start => {?MODULE, start_worker, [a]}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}, {ok, {{one_for_all, 3, 10}, [Child]}}. start_sub() -> supervisor:start_link({local, left_sup}, ?MODULE, left). start_worker(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 propagation.erl
erl -noshell -eval 'propagation:main(), halt().'
a restarted: new_pid b kept its process: true sub supervisor restarted: new_pid its worker came with it: new_pid
The first kill never reached the top: the sub-supervisor restarted its worker and b, a child of the top, kept the process it had. The second kill removed the sub-supervisor, the top started a new one, and the new supervisor started a new worker with it. That is the point of the nesting: the blast radius of a failure is the sub-tree under the supervisor that owns it.
Shutdown order
A tree stops in the opposite order of its start. The top asks its children to stop one by one, newest first, and a supervisor among them stops its own children before it answers. A child that wants to run code on the way out must trap exits, or the shutdown signal ends it before its terminate/2 or its own receive clause can run. This program prints one line per worker as the tree goes down:
shutdown.erl
-module(shutdown). -behaviour(supervisor). -export([main/0, init/1, start_worker/1]). main() -> logger:set_primary_config(level, none), process_flag(trap_exit, true), {ok, Top} = supervisor:start_link({local, ?MODULE}, ?MODULE, top), io:format("started~n", []), unlink(Top), Ref = monitor(process, Top), exit(Top, shutdown), receive {'DOWN', Ref, process, Top, Reason} -> io:format("top: ~p~n", [Reason]) end. init(top) -> Children = [child(a), child(b), child(c)], {ok, {{one_for_one, 3, 10}, Children}}. child(Name) -> #{id => Name, start => {?MODULE, start_worker, [Name]}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}. start_worker(Name) -> Parent = self(), Pid = spawn_link(fun() -> ready(Name, Parent) end), receive {ready, Pid} -> true end, true = register(Name, Pid), {ok, Pid}. ready(Name, Parent) -> process_flag(trap_exit, true), Parent ! {ready, self()}, receive {'EXIT', _From, shutdown} -> io:format("~p stopped~n", [Name]) end.
erlc shutdown.erl
erl -noshell -eval 'shutdown:main(), halt().'
started c stopped b stopped a stopped top: shutdown
The start function waits for the worker to report itself ready before it answers, so the worker is trapping exits before the tree is asked to stop. That handshake is what a start function owes its supervisor: a child that is not ready when the start function returns is a child the supervisor may already be shutting down.
Choosing the shape
A level exists because its children fail together or depend on each other. A cache and
the reader that fills it go in one sub-tree with one_for_all,
because a reader without its cache is useless. A worker pool and the acceptor in front of
it go in one sub-tree with rest_for_one, so a new acceptor is
started after the pool that failed. Unrelated workers stay at the top with
one_for_one, and the budget of each level counts the restarts of
that level only.
Two rules keep a tree honest. Every child is started by a
*_link function, or the supervisor never hears that it died. And
the budget of a level is set for the failure it can handle: a level that gives up takes
its parent with it, so the parent restarts the whole branch, which is correct only when
the branch is the unit that failed. The
OTP design principles lesson
turns this into a checklist, and the
releases lesson starts a whole tree from a
boot script.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What makes a child of a supervisor a sub-tree rather than a worker?
Answer
Its start function starts a supervisor and its type is
supervisorThe
typekey says what the child is, and a supervisor child is started by a function that returns a supervisor pid. -
Why is the shutdown of a supervisor child
infinity?Answer
It must be allowed to stop its own children first
The sub-tree stops itself, and the time that takes is not for the parent to cut short.
-
How far does the restart of a worker inside a sub-tree reach?
Answer
Only the supervisor directly above it restarts it
The nearest supervisor that traps exits handles the death, so the rest of the tree is untouched.
-
In which order does a supervisor stop its children?
Answer
In reverse start order
The newest child stops first, so a child never loses something a later child still uses.
-
Why does a worker have to trap exits to print on shutdown?
Answer
A link signal ends it before its own code can run
Without
process_flag(trap_exit, true)the shutdown signal terminates the process at once. -
What does a level that exceeds its restart budget do?
Answer
Stops itself and lets its parent decide
The supervisor terminates with
shutdown, and the parent restarts the branch or gives up in turn. -
What does this module print?
-module(q1). -behaviour(supervisor). -export([main/0, init/1, start_sub/0, start_worker/0]). main() -> {ok, Top} = supervisor:start_link(?MODULE, top), io:format("~p~n", [supervisor:count_children(Top)]). init(top) -> Children = [#{id => left, start => {?MODULE, start_sub, []}, restart => permanent, type => supervisor}, #{id => right, start => {?MODULE, start_sub, []}, restart => permanent, type => supervisor}], {ok, {{one_for_one, 3, 10}, Children}}; init(sub) -> Child = #{id => w, start => {?MODULE, start_worker, []}, restart => permanent, type => worker}, {ok, {{one_for_one, 3, 10}, [Child]}}. start_sub() -> supervisor:start_link(?MODULE, sub). start_worker() -> {ok, spawn(fun() -> receive stop -> ok end end)}.Answer
[{specs,2},{active,2},{supervisors,2},{workers,0}]The top has two children and both are supervisors, so no direct child of the top is a worker.
-
What does this module print?
-module(q2). -behaviour(supervisor). -export([main/0, init/1, start_sub/0, start_worker/1]). main() -> logger:set_primary_config(level, none), {ok, _Top} = supervisor:start_link(?MODULE, top), A = whereis(a), B = whereis(b), exit(A, kill), timer:sleep(50), io:format("~p~n", [whereis(b) =:= B]). init(top) -> Children = [#{id => left, start => {?MODULE, start_sub, []}, restart => permanent, type => supervisor}, #{id => b, start => {?MODULE, start_worker, [b]}, restart => permanent, type => worker}], {ok, {{one_for_one, 3, 10}, Children}}; init(left) -> Child = #{id => a, start => {?MODULE, start_worker, [a]}, restart => permanent, type => worker}, {ok, {{one_for_one, 3, 10}, [Child]}}. start_sub() -> supervisor:start_link(?MODULE, left). start_worker(Name) -> Pid = spawn_link(fun() -> receive stop -> ok end end), true = register(Name, Pid), {ok, Pid}.Answer
trueThe worker is restarted inside its own sub-tree, so the worker beside it keeps its process.
-
What does this module print?
-module(q3). -behaviour(supervisor). -export([main/0, init/1, start_worker/1]). main() -> logger:set_primary_config(level, none), process_flag(trap_exit, true), {ok, Top} = supervisor:start_link(?MODULE, top), unlink(Top), exit(Top, shutdown), timer:sleep(100), io:format("~p~n", [is_process_alive(Top)]). init(top) -> Children = [child(a), child(b)], {ok, {{one_for_one, 3, 10}, Children}}. child(Name) -> #{id => Name, start => {?MODULE, start_worker, [Name]}, restart => permanent, type => worker}. start_worker(Name) -> Pid = spawn_link(fun() -> receive stop -> ok end end), true = register(Name, Pid), {ok, Pid}.Answer
falseThe shutdown stopped the tree, so the supervisor process is no longer alive.
-
What does this module print?
-module(q4). -behaviour(supervisor). -export([main/0, init/1, start_worker/0]). main() -> logger:set_primary_config(level, none), process_flag(trap_exit, true), {ok, Top} = supervisor:start_link(?MODULE, top), io:format("~p~n", [supervisor:count_children(Top)]). init(top) -> Child = #{id => w, start => {?MODULE, start_worker, []}, restart => permanent, type => worker}, {ok, {{one_for_one, 3, 10}, [Child]}}. start_worker() -> {ok, spawn_link(fun() -> receive stop -> ok end end)}.Answer
[{specs,1},{active,1},{supervisors,0},{workers,1}]One specification, one running child, no supervisor child, and that child is a worker.
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