Using Supervisors to Organize Your Elixir Application

Ilya Averyanov

Ilya Averyanov on

Using Supervisors to Organize Your Elixir Application

In the previous chapter of this series, we looked at hot code reloading in Elixir and why we should use GenServer to implement long-running processes.

But to organize a whole application, we need one more building block — supervisors. Let's take a look at supervisors in detail.

Defining an OTP Application

According to the documentation:

In OTP, application denotes a component implementing some specific functionality, that can be started and stopped as a unit, and that can be reused in other systems. This module interacts with application controller, a process started at every Erlang runtime system.

This module contains functions for controlling applications (for example, starting and stopping applications), and functions to access information about applications (for example, configuration parameters).

In other words, an application is a kind of package that contains reusable modules, has name, version, specific dependencies, etc.

Mix creates a new application when we run:

1mix new our_new_app

But there is one crucial difference that distinguishes OTP applications from packages in other languages. OTP applications can be started and stopped and have their own running entities.

You can usually create such applications in Elixir with the command:

1mix new our_new_app --sup
2cd our_new_app

This creates an additional file for us: lib/our_new_app/application.ex. It implements the so-called application behavior. Its primary purpose is to implement start/2 function, which should start a supervision tree.

What Are Supervision Trees in Elixir?

So what is a supervision tree? I use the following analogy: a running OTP system is like a whole OS with its own lightweight processes. They start, work, and terminate. As in a real OS, we need a tool that helps us:

  • Start the system in the correct order
  • Handle abnormal situations when a process dies due to some errors
  • Stop the system correctly.

In a real OS, we have Systemd (on some Linux OSes) or launchd on MacOS. In OTP, there are supervisors and Supervisor module.

We can organize our processes in the following way using supervisors:

Supervision Tree

Leaf processes in this scheme are generally GenServer or similar processes.

As in Systemd, if a process fails, we can choose to do nothing. Another option is to restart the process over and over again until it completes normally, or together with sibling processes.

Earlier, in Erlang, it was tricky to build supervision trees, but Elixir helps us a lot with this.

It's also worth noting that there is some good documentation available about supervisors.

Connecting GenServers to a Supervision Tree

Let's again look at what mix created for us in lib/our_new_app/application.ex:

1  def start(_type, _args) do
2    children = [
3      # Starts a worker by calling: OurNewApp.Worker.start_link(arg)
4      # {OurNewApp.Worker, arg}
5    ]
7    # See https://hexdocs.pm/elixir/Supervisor.html
8    # for other strategies and supported options
9    opts = [strategy: :one_for_one, name: OurNewApp.Supervisor]
10    Supervisor.start_link(children, opts)
11  end

It starts a supervisor and clearly shows how to run our worker as a child.

Let's do that. We will be able to increment a given number periodically and report its state on demand in our sample process.

First, create a GenServer in lib/our_new_app/counter.ex:

1defmodule OurNewApp.Counter do
2  use GenServer
3  require Logger
5  @interval 100
7  def start_link(start_from, opts \\ []) do
8    GenServer.start_link(__MODULE__, start_from, opts)
9  end
11  def get(pid) do
12    GenServer.call(pid, :get)
13  end
15  def init(start_from) do
16    st = %{
17      current: start_from,
18      timer: :erlang.start_timer(@interval, self(), :tick)
19    }
21    {:ok, st}
22  end
24  def handle_call(:get, _from, st) do
25    {:reply, st.current, st}
26  end
28  def handle_info({:timeout, _timer_ref, :tick}, st) do
29    new_timer = :erlang.start_timer(@interval, self(), :tick)
30    :erlang.cancel_timer(st.timer)
32    {:noreply, %{st | current: st.current + 1, timer: new_timer}}
33  end

This server increments a given number every 100ms and can report its state via OurNewApp.Counter.get/1:

1iex -S mix
3iex(1)> {:ok, pid} = OurNewApp.Counter.start_link(10000)
4{:ok, #PID<0.182.0>}
5iex(2)> OurNewApp.Counter.get(pid)
7iex(3)> OurNewApp.Counter.get(pid)

Now let's integrate our server as a child. Update start/2 function in lib/our_new_app/application.ex to the following:

1  def start(_type, _args) do
2    children = [
3      {OurNewApp.Counter, 10000}
4    ]
6    opts = [strategy: :one_for_one, name: OurNewApp.Supervisor]
7    Supervisor.start_link(children, opts)
8  end

We see that our process starts automatically:

1iex -S mix
3iex(1)> [{_, pid, _, _}] = Supervisor.which_children(OurNewApp.Supervisor)
4[{OurNewApp.Counter, #PID<0.141.0>, :worker, [OurNewApp.Counter]}]
5iex(2)> OurNewApp.Counter.get(pid)
7iex(3)> Process.exit(pid, :shutdown)
9iex(4)> Supervisor.which_children(OurNewApp.Supervisor)
10[{OurNewApp.Counter, #PID<0.146.0>, :worker, [OurNewApp.Counter]}]

We queried the supervisor's children with Supervisor.which_children/1. We also see that our counter process restarted after we stopped it.

Our process tree now looks like this:

Supervision Tree with Counter

Adding GenServers to Custom Supervisors

Now let's make a special supervisor for our counter processes. Later, we'll see why we may want to do that. Our supervision tree will look like this:

Supervision Tree with Counters and their own supervisor

First, we should make a callback module for our new special supervisor. Let's add lib/our_new_app/counter_sup.ex with the following content:

1defmodule OurNewApp.CounterSup do
2  use Supervisor
4  def start_link(start_numbers) do
5    Supervisor.start_link(__MODULE__, start_numbers, name: __MODULE__)
6  end
8  @impl true
9  def init(start_numbers) do
10    children =
11      for start_number <- start_numbers do
12        # We can't just use `{OurNewApp.Counter, start_number}`
13        # because we need different ids for children
15        Supervisor.child_spec({OurNewApp.Counter, start_number}, id: start_number)
16      end
18    Supervisor.init(children, strategy: :one_for_one)
19  end

We must also update children for the main application supervisor in lib/our_new_app/application.ex:

1  def start(_type, _args) do
2    children = [
3      {OurNewApp.CounterSup, [10000, 20000]}
4    ]
6    opts = [strategy: :one_for_one, name: OurNewApp.Supervisor]
7    Supervisor.start_link(children, opts)
8  end

Let's see what we get:

1iex -S mix
3iex(1)> Supervisor.which_children(OurNewApp.Supervisor)
4[{OurNewApp.CounterSup, #PID<0.161.0>, :supervisor, [OurNewApp.CounterSup]}]
5iex(2)> Supervisor.which_children(OurNewApp.CounterSup)
7  {20000, #PID<0.163.0>, :worker, [OurNewApp.Counter]},
8  {10000, #PID<0.162.0>, :worker, [OurNewApp.Counter]}

That's just what we need: OurNewApp.Supervisor has OurNewApp.CounterSup as its child and OurNewApp.CounterSup has two OurNewApp.Counter children.

Many developers consider custom supervisors tricky and avoid using them. So let's do some simple exercises to get more acquainted with them.

First, we'll add a third counter to our counter supervisor at runtime:

2iex(3)> new_child_spec = Supervisor.child_spec({OurNewApp.Counter, 30000}, id: 30000)
3%{id: 30000, start: {OurNewApp.Counter, :start_link, [30000]}}
4iex(4)> Supervisor.start_child(OurNewApp.CounterSup, new_child_spec)
5{:ok, #PID<0.169.0>}
6iex(5)> Supervisor.which_children(OurNewApp.CounterSup)
8  {30000, #PID<0.169.0>, :worker, [OurNewApp.Counter]},
9  {20000, #PID<0.163.0>, :worker, [OurNewApp.Counter]},
10  {10000, #PID<0.162.0>, :worker, [OurNewApp.Counter]}

That was easy! With Supervisor.delete_child/2, Supervisor.restart_child/2, etc., we can easily manipulate the supervisor's children.

Secondly, instead of adding one worker to the existing tree, let's try adding a subtree with its own children (without a special module for the subtree supervisor):

1iex(6)> children_specs = for n <- [10000, 20000, 30000], do: Supervisor.child_spec({OurNewApp.Counter, n}, id: n)
3  %{id: 10000, start: {OurNewApp.Counter, :start_link, [10000]}},
4  %{id: 20000, start: {OurNewApp.Counter, :start_link, [20000]}},
5  %{id: 30000, start: {OurNewApp.Counter, :start_link, [30000]}}
7iex(7)> hand_crafted_sup_spec = %{
8...(7)>     id: :hand_crafted_sup,
9...(7)>     start: {Supervisor, :start_link, [children_specs, [strategy: :one_for_one]]},
10...(7)>     type: :supervisor,
11...(7)>     restart: :permanent,
12...(7)>     shutdown: 5000
13...(7)> }
15iex(8)> Supervisor.start_child(OurNewApp.Supervisor, hand_crafted_sup_spec)
16{:ok, #PID<0.204.0>}
17iex(9)> Supervisor.which_children(OurNewApp.Supervisor)
19  {:hand_crafted_sup, #PID<0.204.0>, :supervisor, [Supervisor]},
20  {OurNewApp.CounterSup, #PID<0.161.0>, :supervisor, [OurNewApp.CounterSup]}

The following took place:

  • hand_crafted_sup_spec was constructed, which started Supervisor.start_link
  • We told our main supervisor to start a child with this spec
  • The main supervisor started with children_specs parameters
  • It started counters from children_specs.

We could do this in another way: tell our main supervisor to launch an empty child supervisor, then add counters one by one to this child supervisor.

The process tree at the end of the experiment should look like this:

Supervision Tree with handcrafted supervisor

Examples of Custom Supervisor Usage

Let's see what happens if we terminate our app.

First, add some logging to lib/our_new_app/counter.ex:

1  def terminate(reason, st) do
2    Logger.info("terminating with #{inspect(reason)}, counter is #{st.current}")
3  end

Also enable the :trap_exit flag for our counters, so that we can handle process termination — see terminate callback documentation:

1  def init(start_from) do
2    Process.flag(:trap_exit, true)
4    st = %{
5    ...
6  end

Now, if we stop our application in the iex session, we see:

1iex -S mix
3iex(1)> Application.stop(:our_new_app)
419:35:43.544 [info]  terminating with :shutdown, counter is 20049
519:35:43.548 [info]  terminating with :shutdown, counter is 10050
619:35:43.548 [info]  Application our_new_app exited: :stopped

Imagine that we have to implement a graceful shutdown. The condition of gracefulness is to count up until we reach numbers divisible by 10 (10, 20, 30, etc) before shutdown.

Of course, in our simple example, we may just send ticks to count to the nearest number divisible by 10 in terminate.

Instead, imagine that these events are external end emulate some metrics that we would prefer to aggregate consistently.

First, let's add the possibility of a graceful restart to the OurNewApp.Counter module:

1defmodule OurNewApp.Counter do
2  use GenServer
3  require Logger
5  @interval 100
7  def start_link(start_from) do
8    GenServer.start_link(__MODULE__, start_from)
9  end
11  def get(pid) do
12    GenServer.call(pid, :get)
13  end
15  def stop_gracefully(pid) do
16    GenServer.call(pid, :stop_gracefully)
17  end
19  def init(start_from) do
20    Process.flag(:trap_exit, true)
22    st = %{
23      current: start_from,
24      timer: :erlang.start_timer(@interval, self(), :tick),
25      terminator: nil
26    }
28    {:ok, st}
29  end
31  def handle_call(:get, _from, st) do
32    {:reply, st.current, st}
33  end
35  def handle_call(:stop_gracefully, from, st) do
36    if st.terminator do
37      {:reply, :already_stopping, st}
38    else
39      {:noreply, %{st | terminator: from}}
40    end
41  end
43  def handle_info({:timeout, _timer_ref, :tick}, st) do
44    :erlang.cancel_timer(st.timer)
46    new_current = st.current + 1
48    if st.terminator && rem(new_current, 10) == 0 do
49      # we are terminating
50      GenServer.reply(st.terminator, :ok)
51      {:stop, :normal, %{st | current: new_current, timer: nil}}
52    else
53      new_timer = :erlang.start_timer(@interval, self(), :tick)
54      {:noreply, %{st | current: new_current, timer: new_timer}}
55    end
56  end
58  def terminate(reason, st) do
59    Logger.info("terminating with #{inspect(reason)}, counter is #{st.current}")
60  end

Here we:

  • Add a terminator field to the state that keeps the address of the party that wants to stop the server
  • Set this field in the stop_gracefully handler
  • Continue counting until we get to a number divisible by 10
  • Respond to the terminating party and stop the server upon obtaining this number.

Let's see how that works for a single process:

1iex -S mix
2Erlang/OTP 23 [erts-11.0.4] [source] [64-bit] [smp:16:16] [ds:16:16:10] [async-threads:1] [hipe]
4iex(1)> {:ok, pid} = OurNewApp.Counter.start_link(10000)
5{:ok, #PID<0.167.0>}
6iex(2)> OurNewApp.Counter.stop_gracefully(pid)
920:03:13.061 [info]  terminating with :normal, counter is 10120

Everything works fine. But what stops all counters gracefully? As we see in the OTP docs, OurNewApp.Application.prep_stop is called (if it exists) before the application stops.

Let's add the desired functionality:

1  @impl true
2  def prep_stop(st) do
3    stop_tasks =
4      for {_, pid, _, _} <- Supervisor.which_children(OurNewApp.CounterSup) do
5        Task.async(fn ->
6          :ok = OurNewApp.Counter.stop_gracefully(pid)
7        end)
8      end
10    Task.await_many(stop_tasks)
12    st
13  end

We also set :restart option to :transient in OurNewApp.CounterSup so that our counters do not restart after graceful shutdown:

1Supervisor.child_spec({OurNewApp.Counter, {start_number, 200}},
2  id: start_number,
3  restart: :transient

Try to stop the app:

1iex -S mix
2iex(1)> Application.stop(:our_new_app)
420:24:02.958 [info]  terminating with :normal, counter is 10260
620:24:02.958 [info]  terminating with :normal, counter is 20260
820:24:02.962 [info]  Application our_new_app exited: :stopped

Now we only stop at numbers divisible by 10.

Using a special supervisor for our counters makes it possible to "find" all the instances quickly and operate with them. This is extremely important when applications go through start/stop stages.


I hope you've managed to wrap your head around supervisors in Elixir, and have found this article helpful, alongside the previous article on hot code reloading.

There is another, even more complicated stage in an application life cycle: application code upgrades. We'll leave that for the third and final part of this series.

Until then, enjoy coding!

P.S. If you'd like to read Elixir Alchemy posts as soon as they get off the press, subscribe to our Elixir Alchemy newsletter and never miss a single post!

Share this article

Ilya Averyanov

Ilya Averyanov

Our guest author Ilya is an Elixir/Erlang/Python developer and a tech leader at [FunBox](https://funbox.ru/). His main occupation is bootstrapping new projects from both human and technological perspectives. Feel free to reach out to him for interesting discussions or consultancy.

All articles by Ilya Averyanov

AppSignal monitors your apps

AppSignal provides insights for Ruby, Rails, Elixir, Phoenix, Node.js, Express and many other frameworks and libraries. We are located in beautiful Amsterdam. We love stroopwafels. If you do too, let us know. We might send you some!

Discover AppSignal
AppSignal monitors your apps