Skip to content
Elixir

Supervisors and OTP

Build fault-tolerant supervision trees.

By EZ4Code Team
supervisorotpfault-tolerance

Code

defmodule MyApp.Supervisor do
  use Supervisor

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

  @impl true
  def init(_init_arg) do
    children = [
      {Counter, 0},          # GenServer from previous example
      {MyApp.Cache, []},     # Another worker
      {Task.Supervisor, name: MyApp.TaskSup}
    ]

    # Strategies:
    # :one_for_one - restart only the failed child
    # :one_for_all  - restart all children
    # :rest_for_one - restart failed + all started after it
    Supervisor.init(children, strategy: :one_for_one)
  end
end

# Restart strategies per child
children = [
  %{id: Counter, start: {Counter, :start_link, [0]}, restart: :permanent},
  %{id: Worker, start: {Worker, :start_link, []}, restart: :temporary}
]

# Application
defmodule MyApp.Application do
  use Application
  def start(_type, _args), do: MyApp.Supervisor.start_link([])
end

Explanation

Supervisors monitor children and restart them on failure — the core of let-it-crash philosophy. Strategies: one_for_one (isolated), one_for_all (all restart), rest_for_one (cascade). restart: :permanent (always), :temporary (never), :transient (only on abnormal exit). Supervision trees make Elixir systems self-healing.

More Elixir Snippets