Keep a flaky dependency off the OTP boot path

The Elixir app sends push notifications through FCM (Firebase Cloud Messaging), using Goth and Pigeon. Both were plain children of the application supervisor. One day FCM returned a TLS/certificate error during startup, and the whole app refused to boot: API, background jobs, everything. All because of a push dependency.

The dependency could stop the application in two places:

  • At boot. If a child’s start_link returns an error, its supervisor fails to start, and so does the application. There’s no retry at this stage.
  • At runtime. If a child crashes more than max_restarts times within max_seconds (3 in 5 seconds by default), its supervisor gives up and exits. Its parent sees that as a crash of its own child, and the failure climbs up to the application supervisor, which stops the app.

The fix is to make sure the risky part is never started by the boot tree, so its failures stop at a boundary:

MyApp.Supervisor (one_for_one)
└── MyApp.Push.Supervisor (rest_for_one)
    ├── MyApp.Push.DynamicSupervisor   # starts empty, can't fail
    └── MyApp.Push.Bootstrapper        # starts push after boot, re-arms it
        ···> MyApp.Push.RuntimeSupervisor (temporary)
             ├── Goth
             └── MyApp.FCM

The DynamicSupervisor starts with no children, so its init can’t fail. Now we can safely put it to the boot tree:

defmodule MyApp.Push.Supervisor do
  use Supervisor

  def start_link(arg), do: Supervisor.start_link(__MODULE__, arg, name: __MODULE__)

  @impl true
  def init(_arg) do
    children = [
      {DynamicSupervisor, name: MyApp.Push.DynamicSupervisor, strategy: :one_for_one},
      MyApp.Push.Bootstrapper
    ]

    # If the slot dies, restart the bootstrapper too, so it re-arms a fresh slot
    Supervisor.init(children, strategy: :rest_for_one)
  end
end

The real subsystem has its own supervisor. It’s :temporary, so the dynamic supervisor never restarts it:

defmodule MyApp.Push.RuntimeSupervisor do
  use Supervisor, restart: :temporary

  def start_link(creds), do: Supervisor.start_link(__MODULE__, creds, name: __MODULE__)

  @impl true
  def init(creds) do
    children = [
      {Goth, name: MyApp.Goth, source: {:service_account, creds}},
      MyApp.FCM
    ]

    # Retry for some time, then give up. It's temporary, so nobody restarts us
    Supervisor.init(children, strategy: :rest_for_one, max_restarts: 3, max_seconds: 60)
  end
end

The bootstrapper starts the subtree in handle_continue after the boot tree is already up. It monitors the subsystem and, while the subsystem is down, retries on a timer:

defmodule MyApp.Push.Bootstrapper do
  use GenServer
  require Logger

  @rearm_interval :timer.minutes(5)

  def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)

  @impl true
  def init(_opts), do: {:ok, %{ref: nil}, {:continue, :arm}}

  @impl true
  def handle_continue(:arm, state), do: {:noreply, try_start(state)}

  @impl true
  def handle_info(:rearm, %{ref: nil} = state), do: {:noreply, try_start(state)}
  def handle_info(:rearm, state), do: {:noreply, state}

  def handle_info({:DOWN, ref, :process, _pid, reason}, %{ref: ref} = state) do
    Logger.error("Push disabled: #{inspect(reason)}")
    schedule_rearm()
    {:noreply, %{state | ref: nil}}
  end

  defp try_start(state) do
    spec = {MyApp.Push.RuntimeSupervisor, credentials()}

    case DynamicSupervisor.start_child(MyApp.Push.DynamicSupervisor, spec) do
      {:ok, pid} -> %{state | ref: Process.monitor(pid)}
      {:error, {:already_started, pid}} -> %{state | ref: Process.monitor(pid)}
      {:error, reason} ->
        Logger.error("Push failed to start: #{inspect(reason)}")
        schedule_rearm()
        state
    end
  end

  defp schedule_rearm, do: Process.send_after(self(), :rearm, @rearm_interval)

  defp credentials, do: Application.fetch_env!(:my_app, :fcm_credentials)
end

Now an FCM outage means “push is temporarily disabled” instead of “the whole app is down”. Once FCM recovers, the next re-arm brings the push subtree back without a redeploy.

← All notes