Elixir Supervisors

Bicycle Thief
2 min readJun 8, 2021

Elixir applications that use supervision trees can use one of two kinds of supervisors — a “regular” Supervisor or a DynamicSupervisor. The DynamicSupervisor is a relatively new addition to the language (added in v1.10) and deprecates the :simple_one_for_one strategy in the regular Supervisor module.

The primary difference between the two Supervisors is that you specify the children and the restart strategy when creating a regular supervisor but only the restart strategy when creating the DynamicSupervisor. That is, the DynamicSupervisor always starts with an empty list of children. The Dynamic Supervisor, as of v 1.12, also supports only one restart strategy: :one_for_one. You use the start_child() function to start a child and add it to the supervision tree.

One often misunderstood capability of start_child() is that it can be used to add children not just to Dynamic Supervision trees but also to the traditional Supervisor. This is often straightforward for a Dynamic Supervisor but requires you to produce a unique id if you are looking to create child processes based on the same module (say, a GenServer or another supervisor).

To create a child of a Dynamic Supervisor (dsup, in the example below), you would do something like this.

DynamicSupervisor.start_child(dsup, {MyApp.Child, optional_params})

Calling the function above multiple times will create a separate child each time. This, however, wouldn’t work with a regular Supervisor unless you produce a new id for each child. For a regular Supervisor sup, you would write code as follows:

Supervisor.start_child(sup, %{id: uuid, start: {MyApp.Child, :start_link, [param list]}})

I have used uuid in the above example, but it can be anything that is unique in your application context.

So what is the difference between the two Supervisors other than the restart strategies and the initial list of children? As José Valim articulated on Elixir Forum, the difference is in how they manage the children. As there is no intrinsic ordering, the DynamicSupervisor will shutdown all the children concurrently but the regular Supervisor will do it in an orderly fashion.

--

--

Bicycle Thief
0 Followers

Notes on what I am reading, watching, and thinking about.