TExcelTAD
Home › Elixir › Elixir Supervisors

Elixir Supervisors

A supervisor is a process whose only job is to start other processes (its children), watch them through links, and restart them when they fail. Supervisors are how Elixir applications recover from crashes on their own: instead of every process defending itself against every error, a failing process is simply replaced with a fresh one in a known good state.

Starting a supervisor

You give Supervisor.start_link/2 a list of child specifications and a strategy. The simplest child spec is a module name or a {Module, argument} tuple; the module must define child_spec/1, which use GenServer and use Agent generate for you.

elixir · try it yourself
# Crash reports are logged with timestamps; silence them to keep the output stable.
Logger.configure(level: :none)

defmodule Counter do
  use Agent

  def start_link(initial), do: Agent.start_link(fn -> initial end, name: __MODULE__)
  def bump, do: Agent.update(__MODULE__, &(&1 + 1))
  def value, do: Agent.get(__MODULE__, & &1)
end

{:ok, _sup} = Supervisor.start_link([{Counter, 100}], strategy: :one_for_one)

Counter.bump()
Counter.bump()
IO.inspect(Counter.value())

# Simulate a crash by killing the process
old = Process.whereis(Counter)
Process.exit(old, :kill)
Process.sleep(20)

new = Process.whereis(Counter)
IO.inspect(new != nil and new != old)
IO.inspect(Counter.value())
102
true
100

After the crash the supervisor started a new Counter process with the original argument, so the value is back at 100. That's the point: the restarted process begins from a clean, known state. State that must survive crashes belongs somewhere more durable (a database, ETS owned by another process, or the restarting process's init reloading it).

Restart strategies

Strategy When one child dies… Use when
:one_for_one only that child is restarted children are independent (most common)
:one_for_all all children are stopped and restarted children can't work without each other
:rest_for_one the child and all children started after it are restarted later children depend on earlier ones
elixir · try it yourself
Logger.configure(level: :none)

defmodule Worker do
  use Agent
  def start_link(name), do: Agent.start_link(fn -> name end, name: name)
end

children = [
  Supervisor.child_spec({Worker, :db}, id: :db),
  Supervisor.child_spec({Worker, :cache}, id: :cache),
  Supervisor.child_spec({Worker, :web}, id: :web)
]

{:ok, _} = Supervisor.start_link(children, strategy: :rest_for_one)

before = Map.new([:db, :cache, :web], &{&1, Process.whereis(&1)})
Process.exit(Process.whereis(:cache), :kill)
Process.sleep(20)

for name <- [:db, :cache, :web] do
  restarted = Process.whereis(name) != before[name]
  IO.puts("#{name}: #{if restarted, do: "restarted", else: "kept"}")
end
db: kept
cache: restarted
web: restarted

With :rest_for_one, killing :cache restarted :cache and :web (started after it) but kept :db. Each child needs a unique :id inside one supervisor; Supervisor.child_spec/2 overrides it here because all three use the same module.

Restart intensity

A supervisor gives up if children crash too often: by default more than 3 restarts in 5 seconds (max_restarts: 3, max_seconds: 5). It then exits itself, and its supervisor decides what to do. This escalation stops an endlessly crashing child from burning CPU forever.

Each child can also declare its restart type in its child spec:

restart: Restarted when it exits…
:permanent (default) always
:transient only after an abnormal exit
:temporary never
elixir
use GenServer, restart: :transient

Inspecting a supervisor

elixir · try it yourself
Logger.configure(level: :none)

children = [
  %{id: :settings, start: {Agent, :start_link, [fn -> %{theme: "dark"} end]}},
  {Task, fn -> :ok end}
]

{:ok, sup} = Supervisor.start_link(children, strategy: :one_for_one)
Process.sleep(20)

IO.inspect(Supervisor.count_children(sup))

for {id, _pid, type, modules} <- Supervisor.which_children(sup) do
  IO.inspect({id, type, modules})
end
%{active: 1, workers: 1, supervisors: 0, specs: 1}
{:settings, :worker, [Agent]}

The first child uses the full map form of a child spec: id, and start as {module, function, args}. The Task child has restart: :temporary by default, so once it finished it was removed instead of restarted.

Supervision trees

Supervisors can supervise other supervisors, forming a supervision tree. A Mix application starts its root supervisor in application.ex:

elixir
defmodule Shop.Application do
  use Application

  @impl true
  def start(_type, _args) do
    children = [
      Shop.Repo,                                   # database pool
      {Phoenix.PubSub, name: Shop.PubSub},
      {Task.Supervisor, name: Shop.TaskSupervisor},
      Shop.Cart.Supervisor,                         # a DynamicSupervisor for carts
      ShopWeb.Endpoint                              # web server, started last
    ]

    Supervisor.start_link(children, strategy: :one_for_one, name: Shop.Supervisor)
  end
end

Children start in list order and stop in reverse order, so put dependencies (the database) before the things that use them (the web endpoint). For children created at runtime (one process per user, per game, per upload) use a DynamicSupervisor with DynamicSupervisor.start_child/2.

Test yourself

Which strategy restarts only the crashed child?

  1. :one_for_all
  2. :rest_for_one
  3. :one_for_one
  4. :simple

A restarted child's state is…

  1. Restored from just before the crash
  2. Rebuilt from its start arguments by init
  3. Copied from the supervisor
  4. Lost and the child stays down

What happens when children crash more than max_restarts times within max_seconds?

  1. The supervisor ignores them
  2. The supervisor itself exits, escalating to its parent
  3. The VM shuts down immediately
  4. The children are restarted slower