Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More than one Supervisor in Elixir Application

I want to register 2 root supervisors in my Phoenix Application, are there any reasons to not to do this?

Example is below

defmodule MyApp.Application do
  use Application
  import Supervisor.Spec

  def start(_type, _args) do
    children_sv1 = [
      supervisor(MyApp.Repo, []),
      ... # other workers
    ]

    children_sv2 = [
      supervisor(MyApp.Endpoint, []),
      ... # other workers
    ]

    opts1 = [strategy: :one_for_one, name: MyApp.Supervisor1]
    opts2 = [strategy: :one_for_one, name: MyApp.Supervisor2]

    Supervisor.start_link(children_sv1, opts)
    Supervisor.start_link(children_sv2, opts)
  end
end
like image 451
Dmitry Cat Avatar asked Mar 21 '26 03:03

Dmitry Cat


1 Answers

One reason not to do this is that your particular application is itself being supervised as part of an OTP-wide supervision tree. The return value for start is used by the top-level Application supervisor to supervise your particular app.

If you explicitly assign results to the supervisor calls above, you'll see that you're dropping information:

{:ok, sup1_pid} = Supervisor.start_link(children_sv1, opts)
{:ok, sup2_pid} = Supervisor.start_link(children_sv2, opts)
{:ok, sup2_pid}

This means that while the first supervisor will be linked to whatever process is starting your app (e.g. the top-level Application supervisor), it will not appear in the output of functions that look at supervision trees, like Supervisor.count_children. During normal operation, this shouldn't be a big deal, but if anything goes wrong, you yourself might have a hard time dissecting the issue, and OTP tools that depend on a proper supervision hierarchy might behave strangely in the face of this setup. Gracefully stopping the application might or might not be a problem.

It's always a safer bet to specify your entire supervision tree as a proper tree -- you'll end up with a much more predictable application. If you need granular control over which branches of the tree are indepenent and how they should be restarted, child specifications are your best friend.

like image 168
Simon Zelazny Avatar answered Mar 23 '26 17:03

Simon Zelazny