Supervisors and Supervision Trees

Article · 5:00

The behaviour whose only job is restarting things, the three restart strategies, and designing a tree that recovers rather than thrashing.

A supervisor is a process that starts child processes, links itself to them, traps exits, and restarts them according to a declared strategy. It contains no business logic at all - that separation is the entire idea. Working code does the work and crashes when it cannot; supervisors do the recovery.

Children are declared in init/1, which returns a SupFlags map and a list of child specifications. A child spec names the start function, a restart policy (permanent - always restart, temporary - never, transient - only on an abnormal exit), a shutdown policy (a timeout in milliseconds for a graceful stop, or brutal_kill), and a type (worker or supervisor).

The three strategies.

one_for_one restarts only the child that died. Right when children are independent.

one_for_all kills and restarts every child when any one dies. Right when they depend on each other and a survivor would be left holding a stale reference to something that no longer exists.

rest_for_one restarts the one that died and everything started after it. Right for a start-order dependency chain: a connection pool, then a cache that uses it, then a server that uses the cache.

Restart intensity is the safety valve, and it is the part people misconfigure. #{intensity => 3, period => 60} means that if more than three restarts happen within sixty seconds, the supervisor gives up and terminates itself - which escalates to its supervisor. Without it, a child that crashes immediately on start would be restarted forever in a tight loop. With it, the failure propagates up the tree until something restarts a large enough subsystem to clear the condition, or the whole application stops. That escalation is the feature.

Designing the tree is where fault tolerance is actually decided. Put things that must fail together under one supervisor with one_for_all. Keep independent subsystems in separate branches so a failure in one cannot reach the other. Keep state that is expensive to rebuild as far from frequently-crashing code as possible - a restarted process starts from init/1, and anything it held is gone unless it was in ETS owned elsewhere, or on disk, or passed in.

simple_one_for_one is the older name for a supervisor with one child template and many dynamic instances - a process per connection, say. In modern OTP it is #{strategy => simple_one_for_one} still, with children added by supervisor:start_child/2.

-module(bank_sup).
-behaviour(supervisor).
-export([start_link/0, init/1]).

start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

init([]) ->
    SupFlags = #{
        strategy  => one_for_one,
        intensity => 3,        % more than 3 restarts...
        period    => 60        % ...within 60 seconds, and this
    },                         % supervisor gives up and escalates.

    Children = [
        #{id       => account_store,
          start    => {account_store, start_link, []},
          restart  => permanent,   % always bring it back
          shutdown => 5000,        % 5s to stop politely, then kill
          type     => worker,
          modules  => [account_store]},

        #{id       => transaction_log,
          start    => {transaction_log, start_link, []},
          restart  => permanent,
          shutdown => 10000,       % longer: it flushes to disk
          type     => worker,
          modules  => [transaction_log]}
    ],

    {ok, {SupFlags, Children}}.

%% ---------------- The three strategies ----------------
%%
%%   one_for_one    only the dead child restarts.
%%                  Children are independent.
%%
%%   one_for_all    ALL children are killed and restarted.
%%                  They depend on each other, and a survivor would
%%                  hold a stale reference to something now gone.
%%
%%   rest_for_one   the dead child, and everything started AFTER it.
%%                  A start-order chain: pool -> cache -> server.
%%
%% ---------------- Restart policies ----------------
%%
%%   permanent   always restarted. The default for a service.
%%   temporary   never restarted, whatever the reason. A one-off job.
%%   transient   restarted only on an ABNORMAL exit. A job that should
%%               finish, and whose failure matters.
%%
%% ---------------- Shutdown ----------------
%%
%%   5000          send a shutdown exit, wait 5s, then brutal_kill
%%   brutal_kill   kill immediately. terminate/2 does NOT run.
%%   infinity      wait for ever. Only for a child that is itself a
%%                 supervisor, so the subtree stops bottom-up.

%% ---------------- Why intensity matters ----------------
%%
%% A child whose init/1 fails on a bad config file crashes instantly,
%% every time. Without an intensity limit the supervisor restarts it in
%% a tight loop for ever, burning a core and filling the log.
%%
%% With one, the supervisor gives up after 3 tries and terminates -
%% which is an abnormal exit, so ITS supervisor sees it and may restart
%% a bigger subtree, perhaps including whatever reads the config. If
%% nothing in the tree can clear the condition, the application stops,
%% loudly, which is correct: a node that cannot start is better than a
%% node pretending to run.

%% ---------------- A tree ----------------
%%
%%                     bank_app_sup            one_for_all
%%                     /          \
%%           storage_sup          api_sup      one_for_one
%%            /       \             |
%%     account_store  tx_log    connection_sup simple_one_for_one
%%                                   |
%%                            one worker per connection
%%
%% A connection dying takes nothing with it. account_store dying
%% restarts the storage branch. storage_sup giving up restarts
%% everything, because the API is useless without storage.
%%
%% The shape of this tree IS the fault tolerance design. It is worth
%% drawing before writing the modules.

%% ---------------- Dynamic children ----------------
%%
%%   {ok, Pid} = supervisor:start_child(connection_sup, [Socket]),
%%   supervisor:terminate_child(Sup, Id),
%%   supervisor:which_children(Sup),
%%   supervisor:count_children(Sup).

Discussion

No questions on this topic yet. Sign in to ask the first one.