Skip to content

Elixir OTP — GenServer, Supervisor, and Application

DodaTech Updated 2026-06-29 1 min read

In this tutorial, you will learn about Elixir OTP. We cover key concepts, practical examples, and best practices to help you master this topic.

OTP (Open Telecom Platform) is Elixir's framework for building fault-tolerant, concurrent systems. It provides battle-tested patterns for managing state, handling errors, and organizing processes.

Elixir on BEAM makes OTP approachable. DodaTech uses OTP for concurrent security scan workers.

GenServer

defmodule Counter do
  use GenServer

  # Client API
  def start_link(initial_value) do
    GenServer.start_link(__MODULE__, initial_value, name: __MODULE__)
  end

  def increment do
    GenServer.call(__MODULE__, :increment)
  end

  def value do
    GenServer.call(__MODULE__, :value)
  end

  # Server callbacks
  @impl true
  def init(initial_value) do
    {:ok, initial_value}
  end

  @impl true
  def handle_call(:increment, _from, state) do
    {:reply, state + 1, state + 1}
  end

  @impl true
  def handle_call(:value, _from, state) do
    {:reply, state, state}
  end
end

# Usage
{:ok, _} = Counter.start_link(0)
Counter.increment()  # => 1
Counter.increment()  # => 2
Counter.value()       # => 2

Supervisor

defmodule MyApp.Supervisor do
  use Supervisor

  def start_link(init_arg) do
    Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
  end

  @impl true
  def init(_init_arg) do
    children = [
      {Counter, [0]},
      # More children...
    ]

    Supervisor.init(children, strategy: :one_for_one)
  end
end

# Strategies:
# :one_for_one — restart only the failed child
# :one_for_all — restart all children
# :rest_for_one — restart the failed child and its dependents

Application

defmodule MyApp.Application do
  use Application

  @impl true
  def start(_type, _args) do
    children = [
      MyApp.Supervisor,
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro