What is the supervisor process in Elixir?

Overview

A supervisor is a process that supervises other child processes and restarts them whenever they crash. To do so, supervisors monitor the complete life-cycle of any supervised processes, including both startup and shutdown.

Myapp.Supervisor.start_link
defmodule Chat.MixProject do
  use Mix.Project

  def project do
    [
      app: :chat,
      version: "0.1.0",
      elixir: "~> 1.13",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
      extra_applications: [:logger]
    ]
  end

  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
    ]
  end
end
Supervisor process

Child specification

In lines 7-8 of the supervisor.ex file, we pass a tuple with the module name to specify the child processes. Here, we use a simpler child specification that requires less reconfiguration. Using these child specifications, we can specify how a child behaves. The child specification is usually a map and contains up to 6 elements. id, start, restart, shutdown, type and modules are all 6 of them.

Supervision tree

A supervision tree models a behavior whose only job is to monitor one or many processes. These processes may be both child processes or child supervisors.

%0 node_1 supervisor node_2 Child_1 node_1->node_2 node_3 Child-supervisor node_1->node_3 node_4 Child_2 node_1->node_4 node_1636457727662 Child_3 node_3->node_1636457727662 node_1636457791277 Child_4 node_3->node_1636457791277
Supervision tree

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved