Supervisors

“In a supervision hierarchy, keep important application state or functionality near the root while delegating risky operations towards the leaves.” - Error Kernel

If the child of a supervisor fails to restart max_restarts times in max_seconds, then the SUPERVISOR crashes. This means if a child of the application supervisor crashes, the ENTIRE APPLICATION will crash.

So yes fail if there are issues, but the known state should actually workarrow-up-right.

Dynamic Supervisors

Works well with Registry to limit to one per or something

Init

defmodule ReactPhoenix.Dynamic.Supervisor do
  use DynamicSupervisor

  def init(:ok) do
    DynamicSupervisor.init(strategy: :one_for_one)
  end

  #.....
end
  • :strategy - Currently only :one_for_one , where a child process terminates doesnt affect other children

  • :max_restarts - max restarts allowed in max_seconds. Default 3

  • :max_seconds - the time frame in which :max_restarts applies. Defaults 5.

  • :max_children - the maximum amount of children to be running under this supervisor at the same time. When :max_children is exceeded, start_child/2arrow-up-right returns {:error, :max_children}. Defaults to :infinity.

  • :extra_arguments - arguments prepended to the child spec given to start_child/2arrow-up-right

application.ex

Start Child

Start genservers/process dynamically

Supervisor won't restart if init fails, so use send self() for init

Way 1 Child Spec

use GenServer , agent, or supervisor all define default child_spec as below

Can modify child_spec options directly in the use

Way 2 Direct Spec

  • :id - any term to identify the child specification internally (Required)

  • :start - a tuple with the module-function-args to be invoked to start the child process (Required)

  • :restart

    • :permanent - always restarted(Default)

    • :temporary - never restarted

    • :transient - restarted only if terminates abnormally (anything besides :normal, :shutdown, or {:shutdown, term})

  • :shutdown - how to shutdown, defaults to 5_000 if the type is :worker or :infinity if the type is :supervisor.

  • :type - :worker (default) or a :supervisor

Example

worker.ex

supervisor.ex

application.ex

Usage, test in console:

Last updated