Supervisors
| Trees of processes | |
| Restart strategies | |
| Child specs | |
| Start a tree |
Trees of processes
A supervisor watches worker processes and restarts them when they crash, forming a tree with one boss and many leaves. Each crash stays local: the broken leaf restarts while siblings keep running. The children list declares the leaves as module and argument pairs.
children = [{Counter, 0}]
The pair says to start the Counter server with zero as its initial argument.
Restart strategies
The strategy option decides how far a restart spreads after one child fails. The one_for_one choice restarts only the crashed child and fits independent workers. The one_for_all choice restarts every child for tightly linked state, while rest_for_one restarts the crashed child plus everything started after it.
Supervisor.start_link(children, strategy: :one_for_one)
Child specs
Behind the scenes each pair expands into a child spec map with an id and a start instruction. The id names the child while start holds the module, function, and arguments to launch it. Write the map form when a child needs custom restart or shutdown settings.
child = %{id: Counter, start: {Counter, :start_link, [0]}}
Start a tree
Starting the supervisor with the children list and a strategy boots the whole tree at once. The call returns an ok tuple with the supervisor pid when every child launches cleanly. Checking the pid confirms that the tree is alive.
children = [{Counter, 0}]
{:ok, sup} = Supervisor.start_link(children, strategy: :one_for_one)
IO.inspect(is_pid(sup))
true
Next: Tasks and Agents
Article author: Arthur Isaev