Skip to content
Erlang

Supervisor Tree

Define a supervisor that starts workers and restarts them on crash.

#supervisor#otp#fault-tolerance

Code

erlang
-module(my_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).

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

init(_Args) ->
    %% {ok, {SupFlags, [ChildSpec]}}
    SupFlags = #{
        strategy  => one_for_one,  % restart only the dead child
        intensity => 10,           % max 10 restarts
        period    => 60            % ...per 60s, else supervisor dies
    },
    Children = [
        #{
            id       => counter,                 % internal id
            start    => {counter, start_link, []},
            restart  => permanent,               % always restart
            shutdown => 5000,                    % 5s graceful timeout
            type     => worker,
            modules  => [counter]
        },
        #{
            id       => cache,
            start    => {cache, start_link, []},
            restart  => transient,               % restart only on abnormal exit
            shutdown => brutal_kill,
            type     => worker,
            modules  => [cache]
        }
    ],
    {ok, {SupFlags, Children}}.