Supervisor Tree
Define a supervisor that starts workers and restarts them on crash.
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
Ping-Pong Processes
Two processes pass messages back and forth using spawn and receive.
gen_server Counter
Build a stateful server with the gen_server behaviour.
Selective Receive with References
Match a specific reply out of many messages using a unique reference.
Links, Exit Trapping & 'Let It Crash'
Use link and trap_exit to detect process death and recover.
Stateful Server via Tail Recursion
Hold mutable state in a process by threading it through recursive calls.
Parallel Map with rpc:pmap
Apply a function to each list element in parallel across processes.