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([])
endExplanation
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
Pattern Matching
Pattern matching is core to Elixir — used everywhere.
Pipe Operator
Chain function calls with the |> pipe operator.
Processes and Messages
Spawn lightweight processes and send messages.
GenServer
Build stateful server processes with GenServer behaviour.
Protocols and Enums
Polymorphism via protocols and the Enum module.
Enum and Stream Operations
Functional collection operations in Elixir.