liveBook · Manning

OTP behavior

As explained in Elixir in Action, Third Edition

An OTP behavior is a standardized callback contract and supporting framework for implementing recurring process patterns in Erlang and Elixir.

An OTP behaviour standardizes a recurring process pattern. Generic code drives the process, while a callback module supplies specialized functions that satisfy the behaviour’s contract. section 6.2.1 section 6.3

This structure replaces ad hoc process code with OTP conventions: behaviour-powered processes fit supervision trees and provide more detailed error logging than plain spawned processes. section 6.2.7

Common OTP behaviours and wrappers include:

  • GenServer implements a generic stateful server process; callback modules commonly define init, handle_call, handle_cast, and handle_info. section 6.2.1 section 6.3
  • Supervisor provides error handling and recovery for concurrent systems, while Application starts a system’s top-level process, usually a supervisor. section 6.2.1 section 11.1.2
  • Task handles one-off jobs, Agent manages exposed state more simply than GenServer, and GenStage supports back pressure and load control. section 6.2.7

Application callback

An application callback module uses Application and defines start/2. That callback starts the top-level supervisor, returning {:ok, pid} or {:error, reason}. section 11.1.2

defmodule HelloWorld.Application do
  use Application                                                  #1
 
  def start(_type, _args) do                                       #2
    children = []                                                  #3
    opts = [strategy: :one_for_one, name: HelloWorld.Supervisor]   #3
    Supervisor.start_link(children, opts)                          #3
  end
end

Inspect a minimal Application callback that declares a supervisor strategy and starts it with an empty child list. section 11.1.2

How Elixir in Action, Third Edition covers it

How deep it goes
Defines generic logic, callback contracts, compilation checks, and major behaviours, while deferring less-used behaviours to external research.
Examples
Uses GenServer callbacks, OTP-compliant processes, and an Application start/2 callback that launches a supervisor.
What it assumes
Assumes familiarity with Erlang or Elixir processes and introduces behaviour contracts through generic server processes.
What you can do after
Build OTP-compliant processes by implementing callback modules for GenServer, Supervisor, or Application.
How it connects
Connects callback modules with GenServer, Supervisor, Application, supervision trees, concurrency, and fault tolerance.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.