Chapter 24 — Supervisors Deep Dive: Restart Trees That Hold the System Up
A supervisor has exactly one job: start children, watch them, and restart them according to policy — forever, without holding state anyone needs. It is the component that turns let it crash from a slogan into an operating mode. Chapters 22–23 built the raw material; this chapter arranges it into trees that survive production.
From Erlang you know: Elixir’s
Supervisoris OTP’ssupervisorbehaviour, andDynamicSupervisoris what replacedsimple_one_for_one(which you should no longer write by hand). Child specs are the same maps/tuples you configured in Erlang — Elixir just gives them first-class syntax and generates them fromuse GenServer.
24.1 A Supervisor Is Just a Process With One Loop
Strip away the DSL and a supervisor is: a process with trap_exit = true,
holding a list of child specs, running a receive loop over {:EXIT, pid, reason} messages. When a linked child dies:
- look up which spec owned that pid;
- decide from the exit reason and the spec’s restart policy whether this death warrants a restart;
- if yes, run the child’s
{m, f, args}again — there is no magic state transfer, the new process starts from scratch; - check the restart budget (24.4) — if the policy is being violated too fast, give up and terminate yourself, escalating upward.
That last step is what makes trees honest: a supervisor that cannot keep a child alive does not hide the fact; it dies loudly and lets its supervisor try a larger-scale fix. Restarts propagate as a last resort, not a first.
flowchart TD
C["child dies<br/>exit reason attached"] --> P{"restart policy<br/>says restart?"}
P -->|"no"| DONE["leave it dead"]
P -->|"yes"| B{"within budget?<br/>max_restarts per max_seconds"}
B -->|"yes"| R["start child again<br/>fresh init, fresh state"] --> W["keep watching"]
B -->|"no"| UP["supervisor terminates<br/>reason escalates to its parent"]
24.2 The Child Spec, Dissected
Every supervised process is described by one map:
| Key | Meaning | Default |
|---|---|---|
:id | unique identity within this supervisor | required |
:start | {module, function, args} to spawn it | required |
:restart | when to restart — :permanent, :transient, :temporary | :permanent |
:shutdown | grace period on tree shutdown — :brutal_kill, ms, :infinity | 5_000 |
:type | :worker or :supervisor | :worker |
:significant | participates in auto-shutdown (OTP 24+) | false |
:modules | for hot-code upgrade analysis | [module] |
You rarely write maps by hand. use GenServer defines Stack.child_spec/1,
and Elixir offers shorthand forms in the children list:
children = [
Stack, # {Stack, []} — default argument []
{Stack, [:a]}, # Stack.start_link([:a]) — ONE arg, a list
{Stack, [:b], restart: :temporary} # 3-tuples are NOT specs — this raises
]
{Stack, []} passes the empty list as a single argument (start_link([]));
it is not splatted. And a 3-tuple {Module, Args, Opts} raises
ArgumentError at supervisor start: the accepted forms are a module, a
{module, arg} tuple, a map, or the 6-element Erlang tuple — a 3-tuple is
none of them. For overrides, use Supervisor.child_spec/2:
children = [
Stack,
{Stack, [:a]},
Supervisor.child_spec({Stack, []}, id: :stack_a, restart: :transient)
]
From Erlang you know: these fields map one-to-one onto the tuple
{ChildId, MFA, RestartType, Shutdown, ChildType, Modules}you passed tosupervisor:start_child/2. Same semantics; the map keys are just kinder.
24.3 Strategies — Deciding Who Else Restarts
The strategy answers one question: when this child restarts, who else does?
| Strategy | On a child restart | Use when |
|---|---|---|
:one_for_one | only the dead child | children are independent |
:one_for_all | every other child too (dead ones restarted, live ones stopped then restarted) | children share coupled state |
:rest_for_one | the dead child and everything started after it | ordered dependencies |
DynamicSupervisor | n/a — children started at runtime | fleets, sessions, tasks |
flowchart TD
subgraph OFO["strategy: one_for_one"]
direction LR
A1[cache] ~~~ B1[pool] ~~~ C1[metrics]
KILL1X["pool crashes"] -.->|"only pool restarts"| B1R["pool v2"]
end
subgraph RF1["strategy: rest_for_one"]
direction LR
A2["registry"] --> B2["dynamic sup"] --> C2["workers"]
KILL2X["registry crashes"] -.->|"registry AND dynamic sup<br/>AND workers all restart"| RF1R["whole tail rebuilt"]
end
Choosing wrongly shows up later, not immediately: :one_for_one over
processes that actually depend on each other produces zombie pairs (a fresh
worker talking to a stale cache). The dependency rule from the architecture
chapters applies inside the tree: if B’s correctness depends on A’s
liveness, order them A→B and let the strategy say so.
24.4 Restart Intensity — the Budget That Prevents Storms
Restarting forever is not resilience; a child that dies instantly after
every start would burn a core spinning. The supervisor therefore budgets
restarts: by default 3 restarts per 5 seconds (max_restarts,
max_seconds). Exceeding the budget — a crash loop — makes the
supervisor terminate itself with reason :shutdown, escalating to its own
parent (24.1).
Supervisor.start_link(children,
strategy: :one_for_one,
max_restarts: 3,
max_seconds: 5,
name: MyApp.Supervisor
)
Tune the numbers after you know your restart latency, never before. A child legitimately taking 10 retries in its first seconds wants a bigger budget; a subsystem crash-looping every minute wants an alarm, and the escalation gives you exactly one.
From Erlang you know: same
intensity/periodpair under other names, same semantics — the budget counts restarts, and only deaths that trigger restarts count toward it.
24.5 Restart Policies — Deciding Whether This Death Matters
The per-child :restart value classifies exits:
| Policy | Restarted on | Typical for |
|---|---|---|
:permanent | any exit | servers holding critical state |
:transient | abnormal exits only — anything except :normal, :shutdown, {:shutdown, _} | workers whose clean finish means done |
:temporary | never | one-shot jobs; things that re-register themselves |
Task children are :temporary by default — a finished task must not be
resurrected. Note how this composes with exit reasons from Ch 22: a worker
that finishes cleanly returns → :normal; a worker killed mid-flight dies
abnormally → restarted under :transient.
24.6 Shutdown — Orderly Retreat
When the tree stops (deploy, System.stop/0, supervisor giving up), the
supervisor walks its children in reverse start order and terminates each
according to the child’s :shutdown value:
:brutal_kill—exit(pid, :kill), no ceremony;- integer ms — send exit signal
:shutdown, wait that long, then kill; :infinity— wait forever (correct for supervisors-as-children; abuse elsewhere hangs deploys).
Two facts connect directly to Chapter 23’s truth table:
- The supervisor itself traps exits — that is literally how it receives child deaths as messages.
- A worker only gets its graceful
terminate/2during shutdown if the worker traps exits; otherwise the:shutdownsignal kills it where it stands. Resources needing cleanup set the flag themselves (23.6).
24.7 Wiring Real Trees
The application callback is just the root of the tree:
defmodule MyApp.Application do
use Application
@impl true
def start(_type, _args) do
children = [
MyApp.Repo,
{Phoenix.PubSub, name: MyApp.PubSub},
MyAppWeb.Endpoint
]
Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)
end
end
Flat :one_for_one at the top is fine — genuinely independent subtrees.
Structure appears when children depend on each other: group them under a
sub-supervisor whose strategy encodes the dependency.
defmodule MyApp.WorkerPool do
use Supervisor # a module-based sub-supervisor
def start_link(arg), do: Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
@impl true
def init(_arg) do
children = [
{Registry, keys: :unique, name: MyApp.WorkerRegistry},
{DynamicSupervisor, name: MyApp.WorkerSupervisor}
]
Supervisor.init(children, strategy: :one_for_all)
end
end
If the Registry died alone, every worker’s registered name would dangle —
so :one_for_all rebuilds the pair together (this is the shape Postgrex and
Phoenix.PubSub ship internally). Use :rest_for_one instead when the
dependency is ordered but partial: everything downstream of the failure
rebuilt, upstream preserved.
OTP 24+ adds one more tool for trees with “optional” parts: mark children
:significant and set the parent’s auto_shutdown so the tree stops
cleanly when all significant children end — designed for session-style
trees that have a natural lifetime.
24.8 DynamicSupervisor — Children Born at Runtime
Static specs describe what exists at boot. Fleets — one process per session, per upload, per connection — need children started (and replaced) later:
defmodule MyApp.SessionSup do
use DynamicSupervisor
def start_link(init_arg), do: DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
def start_session(id) do
spec = Supervisor.child_spec({MyApp.Session, id}, restart: :transient)
DynamicSupervisor.start_child(__MODULE__, spec)
end
@impl true
def init(_init_arg), do: DynamicSupervisor.init(strategy: :one_for_one)
end
iex> MyApp.SessionSup.start_session("user-42")
#=> {:ok, #PID<0.180.0>}
iex> DynamicSupervisor.which_children(MyApp.SessionSup)
#=> [{:undefined, #PID<0.180.0>, :worker, [MyApp.Session]}]
iex> DynamicSupervisor.count_children(MyApp.SessionSup)
#=> %{active: 1, specs: 1, supervisors: 0, workers: 1}
Use the DynamicSupervisor functions, not Supervisor.which_children/1 —
the latter happens to work because DynamicSupervisor implements the same
:supervisor calls, but it teaches the wrong module and any child-spec-only
helper you reach for next will not exist.
Notes that matter:
-
The dynamic supervisor itself is a static child of something above it; only its children are dynamic.
-
start_child/2returns{:ok, pid}or{:error, {:already_started, pid}}— but thealready_startedcomes from the child’s ownstart_link/1, not from the spec. If your child registers via{:via, Registry, ...}and that key is taken, you get{:error, {:already_started, pid}}. A:idin the spec does not deduplicate:DynamicSupervisorpermits duplicate ids, so “one process per session” is enforced by theRegistry, not the supervisor.case DynamicSupervisor.start_child( MyApp.SessionSup, Supervisor.child_spec({MyApp.Session, session_id}, id: session_id) ) do {:ok, pid} -> {:ok, pid} {:error, {:already_started, pid}} -> {:ok, pid} # idempotent other -> other end -
Task.Supervisoris this exact pattern prepackaged for tasks.
From Erlang you know: this is
simple_one_for_onewith the rough edges sanded off — per-child specs instead of one frozen MFA, and no more positionalstart_childargument lists.
24.9 Watching Trees Fail — On Purpose
Production debugging starts with reading crash reports; they are already structured:
[error] GenServer MyApp.Session terminating
** (KeyError) key :token not found in: %{user_id: 42}
my_app/session.ex:23: MyApp.Session.handle_info/2
Last message: {:DOWN, ...}
State: %{user_id: 42}
Four lines tell you: which process, why, on what message, holding what state. For live views:
Supervisor.which_children(MyApp.Supervisor)
Supervisor.count_children(MyApp.WorkerPool)
#=> %{active: 12, specs: 12, supervisors: 1, workers: 11}
:observer.start() # GUI: trees, mailboxes, memory, scheduler usage
And the highest-value exercise in this chapter: kill things deliberately
in dev. Process.exit(pid, :kill) your cache under load, watch the tree
rebuild, and check what clients experienced. A supervision tree you have
never killed is an untested component wearing a production name.
Explore More
- Supervisor docs — child spec reference and strategy semantics
- DynamicSupervisor docs
Task.Supervisor— supervised ad-hoc processes without writing any supervisor yourself- OTP Design Principles: Supervision Behaviour
— the Erlang-side truth, including
supervisor_bridge - Exercise idea: build a three-child tree (
registry → pool → worker) with:rest_for_one; kill each child in turn and log exactly who restarted - Exercise idea: set
max_restarts: 2, max_seconds: 5over a child that crashes ininit/1, catch the supervisor’s own exit, and confirm reason is:shutdown
Checkpoint
- What does a supervisor actually do when it “restarts” a child?
- Your registry crashed while workers were running. Which strategy would you pick to avoid stale registrations, and why not the others?
- A
:transientchild exits with{:shutdown, :done}. Restarted? - Why does exceeding the restart budget terminate the supervisor rather than just logging?
- During shutdown, when does a worker’s
terminate/2run — and who decides how long it may take?
Answers
- Re-runs the child’s
{module, function, args}from scratch — fresh process, fresh state viainit. Nothing is transferred; recoverability comes from rebuilding, not snapshotting. :rest_for_onewith the registry first in start order. Workers registered under names die with the registry, so they must be rebuilt after it; plain:one_for_oneleaves them pointing at nothing. The §24.7 example uses:one_for_all, which also works but needlessly restarts anything started before the registry too — prefer:rest_for_oneand put the dependency first.- No —
{:shutdown, term}counts as clean, like:shutdownand:normal;:transientrestarts abnormal deaths only. - Because a crash loop means the local fix has failed; escalating gives a larger context (the parent restarts the whole subtree) a chance, and surfaces the failure upward until something can actually address it. Silently spinning would hide the outage.
- Only if the worker traps exits (then it receives the
:shutdownsignal as a message); the child’s own:shutdownspec value — integer ms,:infinity, or:brutal_kill— sets the grace period before the supervisor kills it. Order is reverse start.
Next: Chapter 25 — Pattern Matching Deep Dive — the last mechanics chapter. Ch 14 (High-Level Process Frameworks) packages these primitives into libraries if you want that detour.