Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 Supervisor is OTP’s supervisor behaviour, and DynamicSupervisor is what replaced simple_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 from use 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:

  1. look up which spec owned that pid;
  2. decide from the exit reason and the spec’s restart policy whether this death warrants a restart;
  3. if yes, run the child’s {m, f, args} again — there is no magic state transfer, the new process starts from scratch;
  4. 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:

KeyMeaningDefault
:idunique identity within this supervisorrequired
:start{module, function, args} to spawn itrequired
:restartwhen to restart — :permanent, :transient, :temporary:permanent
:shutdowngrace period on tree shutdown — :brutal_kill, ms, :infinity5_000
:type:worker or :supervisor:worker
:significantparticipates in auto-shutdown (OTP 24+)false
:modulesfor 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 to supervisor: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?

StrategyOn a child restartUse when
:one_for_oneonly the dead childchildren are independent
:one_for_allevery other child too (dead ones restarted, live ones stopped then restarted)children share coupled state
:rest_for_onethe dead child and everything started after itordered dependencies
DynamicSupervisorn/a — children started at runtimefleets, 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/period pair 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:

PolicyRestarted onTypical for
:permanentany exitservers holding critical state
:transientabnormal exits only — anything except :normal, :shutdown, {:shutdown, _}workers whose clean finish means done
:temporaryneverone-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/2 during shutdown if the worker traps exits; otherwise the :shutdown signal 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/2 returns {:ok, pid} or {:error, {:already_started, pid}} — but the already_started comes from the child’s own start_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 :id in the spec does not deduplicate: DynamicSupervisor permits duplicate ids, so “one process per session” is enforced by the Registry, 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.Supervisor is this exact pattern prepackaged for tasks.

From Erlang you know: this is simple_one_for_one with the rough edges sanded off — per-child specs instead of one frozen MFA, and no more positional start_child argument 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: 5 over a child that crashes in init/1, catch the supervisor’s own exit, and confirm reason is :shutdown

Checkpoint

  1. What does a supervisor actually do when it “restarts” a child?
  2. Your registry crashed while workers were running. Which strategy would you pick to avoid stale registrations, and why not the others?
  3. A :transient child exits with {:shutdown, :done}. Restarted?
  4. Why does exceeding the restart budget terminate the supervisor rather than just logging?
  5. During shutdown, when does a worker’s terminate/2 run — and who decides how long it may take?
Answers
  1. Re-runs the child’s {module, function, args} from scratch — fresh process, fresh state via init. Nothing is transferred; recoverability comes from rebuilding, not snapshotting.
  2. :rest_for_one with the registry first in start order. Workers registered under names die with the registry, so they must be rebuilt after it; plain :one_for_one leaves 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_one and put the dependency first.
  3. No — {:shutdown, term} counts as clean, like :shutdown and :normal; :transient restarts abnormal deaths only.
  4. 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.
  5. Only if the worker traps exits (then it receives the :shutdown signal as a message); the child’s own :shutdown spec 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.

Back to table of contents