Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 48 ยท Concurrency and OTP

Supervisors and Supervision Trees

Learn how Elixir supervisors restart crashed processes: child specs, one_for_one, one_for_all, rest_for_one, max restarts and DynamicSupervisor.

"Let it crash" only works if something picks the pieces up afterwards. That something is a supervisor: a process whose only job is to start other processes (its children), watch them, and restart them when they die. Supervisors can supervise other supervisors, which gives you a supervision tree, and a well-designed tree is what lets Elixir systems run for years while individual parts fail and recover.

Under the hood a supervisor uses what you learned in Links, Monitors and Let It Crash: it traps exits, links to every child and reacts to {:EXIT, ...} messages. This lesson shows the real Elixir API as read-only code, and the editors model supervisor decisions in JavaScript. The model captures the rules; real supervisors also handle shutdown timeouts, start-up ordering and many details we skip.

What a supervisor does

Starts Children start in the listed order.
Watches It links to every child.
Restarts A dead child gets a fresh start.

Supervisors contain no business logic.

1 / 2

Starting a supervisor

The simplest supervisor takes a list of children and a strategy:

ELIXIR
children = [
  Stack,
  {Counter, 0},
  {Cache, name: :cache}
]

{:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)

Each entry is a child specification (child spec) that says how to start and manage one child. A bare module name or {Module, arg} tuple means "call Module.child_spec(arg)", and use GenServer (or use Agent, use Task) defines child_spec/1 for you, from the start_link function in the module. The spec is a map:

ELIXIR
%{
  id: Stack,
  start: {Stack, :start_link, [[]]},
  restart: :permanent,
  shutdown: 5_000,
  type: :worker
}
  • id identifies the child inside this supervisor.
  • start is a {module, function, args} tuple that must start the child and link it to the caller; start_link functions do exactly that.
  • restart decides when a dead child is restarted:
    • :permanent (default): always restarted.
    • :transient: restarted only if it exits abnormally (not :normal, :shutdown or {:shutdown, _}).
    • :temporary: never restarted.
  • shutdown is how long the child gets to terminate before it is killed.
  • type is :worker or :supervisor.

Children start in order, and stop in the reverse order, so a child can depend on the ones listed before it.

You can also define a supervisor as a module, which is how applications usually do it:

ELIXIR
defmodule Shop.Supervisor do
  use Supervisor

  def start_link(arg) do
    Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
  end

  @impl true
  def init(_arg) do
    children = [Shop.Cache, Shop.Inventory, Shop.Orders]
    Supervisor.init(children, strategy: :rest_for_one)
  end
end

Restart strategies

:one_for_one restarts only the child that terminated. Use it when children are independent, for instance one worker per user session. It is the most common strategy.

:one_for_all restarts every child when one dies, because the children cannot work without each other. If two processes hold coupled state, restarting only one would leave them inconsistent.

:rest_for_one restarts the failed child and all children started after it in the list. Use it when later children depend on earlier ones: if the cache dies, the inventory and orders that use it restart too, but a child listed before the cache keeps running.

flowchart TD
    Root["Shop.Supervisor<br/>(rest_for_one)"] --> A["Cache"]
    Root --> B["Inventory"]
    Root --> C["Orders"]
    A -. "if Cache dies" .-> R["Cache, Inventory, Orders restart"]

With rest_for_one, a crash of the first child restarts all three; a crash of Orders restarts only Orders.

Restart intensity

What if a child crashes again and again because it fails during startup? Endless restarts would burn CPU and hide the problem. Supervisors therefore have a restart intensity: max_restarts (default 3) within max_seconds (default 5). If the children cause more restarts than that in the window, the supervisor gives up, terminates its children and exits itself. The failure then travels up the tree to the parent supervisor, which applies its own strategy.

ELIXIR
Supervisor.start_link(children,
  strategy: :one_for_one,
  max_restarts: 5,
  max_seconds: 10
)

This escalation is the core design: a small, local problem is fixed by restarting the worker; a persistent one restarts a larger subtree; and if the whole thing is hopeless, the application stops and your deployment tooling takes over.

Designing a tree

A good tree puts the most stable processes at the top and the riskiest at the leaves, and keeps state that is expensive to rebuild out of crashy processes. Some principles:

  • Group processes that must live and die together under one supervisor with :one_for_all or :rest_for_one.
  • Separate unrelated features under different supervisors so one feature's crash loop does not take down the others.
  • Make init/1 of workers fast and reliable, since a restart repeats it. A worker that cannot start because a database is down will exhaust the intensity; consider connecting lazily or with retries.
  • Remember that a restart loses the process's state. Rebuild it from a durable source (a database, a file) or accept the loss.

A new project created with mix new shop --sup has an Application module whose start/2 callback launches the top supervisor. Your application's tree starts from there; see Mix: Creating and Managing Projects.

DynamicSupervisor

A normal supervisor lists its children up front. When you need children created while the program runs (one process per chat room, one per uploaded file), use DynamicSupervisor:

ELIXIR
{:ok, sup} = DynamicSupervisor.start_link(strategy: :one_for_one, name: Rooms)

{:ok, pid} = DynamicSupervisor.start_child(Rooms, {Room, "elixir-chat"})
DynamicSupervisor.terminate_child(Rooms, pid)
DynamicSupervisor.count_children(Rooms)

A DynamicSupervisor starts empty and supports only :one_for_one. Its children are usually :temporary or :transient, so that a room that stopped on purpose is not resurrected. Combine it with a Registry to find the processes by name, which later lessons show.

A JavaScript supervisor model

The first editor shows which children are restarted under each strategy when one crashes. Each "child" has a start counter, and the "supervisor" applies the rule. Real supervisors terminate and start processes asynchronously and honor shutdown timeouts; this model only records the decisions.

JS Which children restart? (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Compare the rows: one_for_all always restarts all three, while rest_for_one restarts everything from the crashed child to the end of the list.

The second editor models restart intensity with a virtual clock, using the defaults of 3 restarts per 5 seconds. A worker that keeps crashing makes the supervisor give up.

JS Restart intensity (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the first run the fourth restart inside five seconds is one too many, so the supervisor stops. In the second, old restarts leave the window before new ones arrive, so the supervisor copes indefinitely.

The precise boundaries of the time window in OTP are an implementation detail. Rely on the idea (more than N restarts in M seconds escalates), not on exact edge cases.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which restart strategy restarts the crashed child and every child listed after it?

    rest_for_one is for chains of dependencies: later children depend on earlier ones, so they restart together.
  2. 2. What does restart: :transient mean?

    Transient children are restarted only when they crash. A :normal or :shutdown exit leaves them stopped.
  3. 3. What happens when children cause more than max_restarts restarts within max_seconds?

    The supervisor gives up, which is itself a crash that the parent supervisor handles with its strategy.
  4. 4. When should you use a DynamicSupervisor?

    DynamicSupervisor starts empty and adds children on demand with start_child/2.

Summary

  • A supervisor starts, links to and restarts child processes; supervisors can be nested into trees.
  • A child spec has id, start, restart (:permanent, :transient, :temporary), shutdown and type.
  • Strategies: :one_for_one, :one_for_all, :rest_for_one.
  • Too many restarts in a window (3 in 5 seconds by default) make the supervisor exit and escalate.
  • Put stable processes high in the tree, group dependent ones together and keep workers' start-up reliable.
  • DynamicSupervisor adds children at run time.
  • The JavaScript editors model the decisions, not the real OTP implementation.

Next up: Tasks and Parallel Work.