Skip to content
Supervision Trees
step 1/4

Reading — step 1 of 4

Learn

~1 min readOTP Behaviours

Supervisors restart crashed children automatically. The Erlang fault-tolerance story.

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

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

init([]) ->
    SupFlags = #{strategy => one_for_one,
                 intensity => 5,
                 period => 10},
    Children = [
        #{id => counter_worker,
          start => {counter, start_link, []},
          restart => permanent,
          shutdown => 5000,
          type => worker,
          modules => [counter]}
    ],
    {ok, {SupFlags, Children}}.

Supervisor flags:

  • strategyone_for_one (just the failed child), one_for_all (all children), rest_for_one (failed + later)
  • intensity — max restarts allowed
  • period — within how many seconds (intensity over period — exceed and the supervisor itself dies)

Child spec fields:

  • id — unique identifier within the supervisor
  • start{Module, Function, Args} to call
  • restartpermanent (always restart), temporary (never), transient (restart only on abnormal exit)
  • shutdown — ms to wait for graceful shutdown
  • typeworker or supervisor
  • modules — for code reload

Supervision trees:

App Supervisor (one_for_one)
├─ DB Sup (one_for_one)
│   ├─ DB Connection Pool (worker)
│   └─ Migration Worker (transient — runs once)
├─ Web Sup (one_for_one)
│   ├─ HTTP Server (worker)
│   └─ WebSocket Manager (worker)
└─ Background Sup (one_for_one)
    └─ Worker Pool (supervisor)
        ├─ Worker 1
        ├─ Worker 2
        └─ Worker 3

Failures contained at the right level. "Let it crash" works because the supervisor restarts from a known good state.

DynamicSupervisor — children added/removed at runtime:

  • One child per active user session
  • One child per ongoing job

The mantra: supervised processes don't need defensive code. Validate inputs at boundaries; let internal failures crash the worker. The supervisor handles restart.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Supervision Trees — Erlang Advanced