Skip to content
Erlang

Supervisor Tree

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

By EZ4Code Team
supervisorotpfault-tolerance

Code

-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}}.

Explanation

A supervisor doesn't run business logic — it starts, monitors, and restarts children. The strategy controls restart behaviour: one_for_one restarts only the dead child, one_for_all restarts all siblings (use when children depend on each other), rest_for_one restarts the dead child and those started after it. intensity/period caps the restart rate to avoid infinite restart loops crashing the whole node.

More Erlang Snippets