Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 5 — Behaviours, Protocols & Structs

Erlang has behaviours. Elixir keeps them — and adds protocols, a second, data-centric polymorphism axis. Understanding when to use each is the key idiom of the ecosystem.

The one-line map: behaviours answer “which module implements this interface?”; protocols answer “what does this operation mean for this kind of value?”.

From Erlang you know: use GenServer, @behaviour, behaviour_info/1, @callback, @optional_callbacks — all of it, unchanged, and the compiler enforces the same contract in the same way. Everything new in this chapter is the second axis: protocols dispatch on the type of the data rather than on a module you pass in, and structs give you records with field-level syntax. If you only ever write behaviours, you are writing Erlang that compiles.

5.1 Behaviours (Same as Erlang)

A behaviour is a module contract: callbacks a module must implement.

Erlang:

%% Behaviour definition
-module(serializer).
-callback serialize(term()) -> binary().
-callback deserialize(binary()) -> term().

%% Implementation
-module(json_serializer).
-behaviour(serializer).

-export([serialize/1, deserialize/1]).

serialize(Term) -> jiffy:encode(Term).
deserialize(Bin) -> jiffy:decode(Bin).

Elixir — same contract, plus two quality-of-life upgrades:

defmodule MyBehaviour do
  @callback process(data :: term()) :: {:ok, term()} | {:error, term()}
end

defmodule MyImplementation do
  @behaviour MyBehaviour          # compiler now checks this module's callbacks

  @impl true                       # ← marks the next def as a callback impl
  def process(data) do
    {:ok, do_work(data)}
  end

  defp do_work(data), do: data     # private helpers stay unmarked
end

Everything you know applies: -callback → @callback, -behaviour → @behaviour. Two additions worth adopting immediately:

  • @impl true marks the function as implementing a callback — the compiler verifies signatures and catches typos (def proccess/1 without @impl silently becomes dead code; with @impl, it’s a warning pointing at your mistake). Readers also see intent at the definition site.
  • The compiler warns on missing/incorrect callbacks, same as Erlang’s behaviour_info checking but with better diagnostics.

Every GenServer you write in Elixir uses this exact mechanism:

defmodule Counter do
  use GenServer   # ← use injects @behaviour + boilerplate via macros (Ch 06)

  @impl true
  def init(arg), do: {:ok, arg}

  @impl true
  def handle_call(:get, _from, count), do: {:reply, count, count}
end

Reflection and optional_callbacks

Behaviours compile to the same introspectable metadata, reachable from either language:

iex> GenServer.behaviour_info(:callbacks)
[terminate: 2, init: 1, handle_info: 2, handle_continue: 2, handle_cast: 2,
 handle_call: 3, format_status: 2, format_status: 1, code_change: 3]

iex> GenServer.behaviour_info(:optional_callbacks)
[terminate: 2, handle_info: 2, handle_continue: 2, handle_cast: 2,
 handle_call: 3, format_status: 2, format_status: 1, code_change: 3]

iex> MyImplementation.behaviour_info(:callbacks)
[process: 1]

(Real output on 1.20.4. Note how much of GenServer is optional — nine callbacks declared, eight of them optional, so use GenServer requires exactly one function from you: init/1.)

behaviour_info/1 is generated from the @callback attributes, which is why it works identically from an Erlang shell — you can introspect any OTP behaviour without loading a single Elixir module.

Optional callbacks — ones the compiler will not demand — must still be declared, then marked optional:

defmodule JobQueue do
  @callback perform(args :: map()) :: :ok | {:error, term()}
  @callback timeout(args :: map()) :: pos_integer()
  @optional_callbacks timeout: 1    # implement if you need it; ignore if not

  defmacro __using__(_opts) do      # libraries usually ship this too (Ch 06)
    quote do
      @behaviour JobQueue
    end
  end
end

GenServer marks code_change/3 optional exactly this way.

5.2 Protocols: Dispatch on Data, Not Module

Behaviours dispatch on module (the caller chooses an implementation module up front). Protocols dispatch on the data type itself — like single dispatch on the first argument’s type, checked at compile time and consolidated for speed.

flowchart TD
    subgraph BHV["Behaviour — dispatch on MODULE choice"]
        C1["caller"] -->|"picks implementation"| M1["JSONSerializer"]
        C1 -->|"or…"| M2["MsgpackSerializer"]
        M1 --> CB["calls callbacks<br/>(contract via @callback)"]
    end
    subgraph PROTO["Protocol — dispatch on VALUE type"]
        V["a value<br/>%MapSet{} · [list] · %Date{}"] --> LK{"which type?"}
        LK -->|MapSet| I1["defimpl for MapSet"]
        LK -->|List| I2["defimpl for List"]
        LK -->|Date| I3["defimpl for Date"]
    end
ConceptErlang (Behaviours)Elixir (Protocols + Behaviours)
PolymorphismCallbacks (module-based)Protocols (data-based) + Behaviours
Define-callback in behaviourdefprotocol Name do ... end
ImplementWrite a moduledefimpl Protocol, for: Type do ... end
DispatchCaller passes moduleRuntime type of the value
ConsolidationManualProtocol.consolidate/1 (automatic in Mix releases)
# Protocol: dispatch happens on the FIRST argument's type.
defprotocol Serializer do
  def serialize(term)
end

defimpl Serializer, for: Map do
  def serialize(map), do: Jason.encode!(map)
end

defimpl Serializer, for: List do
  def serialize(list), do: Jason.encode!(list)
end

# Usage — dispatches on data type:
Serializer.serialize(%{name: "Alice"})   # Map implementation
Serializer.serialize([1, 2, 3])          # List implementation

Note what is not here: deserialize/1. A protocol dispatches on its first argument, so deserialize(binary) would dispatch on BitString for every call, and defimpl Serializer, for: Map would never run for it. Decoding has no type to dispatch on — the value is still a binary. That is a behaviour’s job, because the caller chooses the implementation module:

defmodule Codec do
  @callback deserialize(binary()) :: {:ok, term()} | {:error, term()}

  def decode(bin, codec), do: codec.deserialize(bin)
end

defmodule JSONCodec do
  @behaviour Codec
  def deserialize(bin), do: {:ok, Jason.decode!(bin)}
end

Codec.decode(payload, JSONCodec)

Rule of thumb: protocol when the data picks the implementation; behaviour when the caller or configuration does.

The killer feature vs Erlang patterns: you can extend types you don’t own. Want JSON serialization for someone else’s struct? defimpl it for their type — no wrapper modules, no changes to their code.

Where you’ll meet protocols constantly. The Elixir standard library ships five core protocols — plus JSON.Encoder since Elixir 1.18 — and you use them daily:

ProtocolPowersExample
EnumerableEnum + Stream over any collectionEnum.count(mapset)
Collectablecollecting into a data typeEnum.into(1..3, MapSet.new())
Inspectprogramming-language representationinspect(term), iex output
String.Charsto-string for humans/machines"id: #{id}" interpolation
List.Charsto-charlistto_charlist(term)
JSON.Encoderencoding for the built-in JSON module (1.18+)JSON.encode!(term)
iex> String.Chars.impl_for(:ok)       # ask which impl handles a value…
String.Chars.Atom

# Interpolation REQUIRES String.Chars — that's why #{:atom} works:
iex> "status: #{:ok}"
"status: :ok"

# Inspect is derivable on your structs — no hand-written inspect needed:
iex> defmodule Point do
...>   @derive {Inspect, only: [:x]}
...>   defstruct x: 0, y: 0
...> end
iex> inspect(%Point{x: 1, y: 2})
"#Point<x: 1, ...>"

Consolidation, briefly: in dev, protocol dispatch looks up implementations dynamically (so you can add them live). In Mix releases, Mix rewrites every protocol module into a fast lookup table over the known set of implementations — zero-cost dispatch, no dynamic code loading needed. You get Erlang-release-style static behavior for free.

@derive: Generated Implementations for Your Structs

Most struct protocol implementations are boilerplate; derivation generates them at compile time:

defmodule Payment do
  @derive {Inspect, only: [:id, :amount_cents]}   # redact the rest
  @derive Jason.Encoder                            # third-party protocols too
  defstruct [:id, :amount_cents, :cvv]
end

Deriving is macro-generated defimpl under the hood — just less typing — and options like only:/except: encode privacy intent at the definition.

Fallback to Any — With Caution

By default, calling a protocol on an uncovered type raises Protocol.UndefinedError — loud, and usually what you want. When a sensible default genuinely exists, declare it:

defprotocol Size do
  @fallback_to_any true
  def size(data)
end

defimpl Size, for: Any do
  def size(_), do: 1                # atoms, pids, numbers... all "size 1"
end

The trap: structs with no specific implementation also fall through to Any — so Size.size(%Payment{}) quietly returns 1 instead of raising. Verified, with the impl list printed alongside:

Size.size("abcd")        #=> 4          BitString impl
Size.size(:atom)         #=> 1          falls through to Any
Size.size(%Payment{})    #=> 1          ALSO falls through — the trap

Size.impl_for("x")       #=> Size.BitString
Size.impl_for(%Payment{}) #=> Size.Any

Any fallback weakens the “unknown type = bug” signal; reserve it for universal semantics, not domain operations.

Worth knowing since it looks like a trap but is not: a struct does not dispatch to for: Map. Give that a shot and the compiler stops you, because Describe.describe(%Payment{}) has no matching impl and the checker knows:

warning: incompatible types given to Describe.describe/1:
    but expected a type that implements the Describe protocol.
    You either passed the wrong value or you forgot to implement the protocol.

Structs get their own protocol identity (%Payment{} ≠ %{__struct__: ...}), so for: Map is genuinely safe. Write defimpl Describe, for: Payment instead, or use @derive.

The same dispatch-on-data idea extends across the ecosystem: Nx’s Nx.Container (Ch 17), Phoenix’s HTML-safety protocol, JSON encoders — all defprotocol + defimpl.

Four Protocols, Implemented Live

Tiny implementations make the dispatch concrete. First, the two display protocols on a money type:

defmodule Money do
  defstruct cents: 0
end

defimpl String.Chars, for: Money do            # powers "#{money}"
  def to_string(%Money{cents: cents}) do
    :io_lib.format("$~.2f", [cents / 100]) |> IO.iodata_to_binary()
  end
end

defimpl Inspect, for: Money do                 # powers iex echo / inspect/1
  def inspect(%Money{cents: cents}, _opts), do: "#Money<#{cents}c>"
end

iex> "total: #{%Money{cents: 1299}}"
"total: $12.99"
iex> inspect(%Money{cents: 2500})
"#Money<2500c>"

Next, Collectable — teaching Enum.into how to pour elements INTO your type. The contract: return {initial_acc, collector_fn} handling :cont, :done, and :halt:

defmodule Unique do
  defstruct members: []
end

defimpl Collectable, for: Unique do
  def into(%Unique{members: members}) do
    collector = fn
      acc, {:cont, x} -> if x in acc, do: acc, else: [x | acc]
      acc, :done -> %Unique{members: Enum.reverse(acc)}
      _acc, :halt -> :ok
    end

    {members, collector}
  end
end

iex> Enum.into([3, 1, 3, 2], %Unique{})
%Unique{members: [3, 1, 2]}

Finally Enumerable — the protocol behind every Enum call. The required core is reduce/3 driving a {:cont | :halt | :suspend} state machine; count/member?/slice may decline with {:error, __MODULE__} and Enum falls back to plain reducing:

defmodule Naturals do
  defstruct upto: nil
end

defimpl Enumerable, for: Naturals do
  def reduce(%Naturals{upto: upto}, acc, fun),
    do: do_reduce(upto, acc, fun, 1)

  defp do_reduce(_n, {:halt, acc}, _fun, _i), do: {:done, acc}

  defp do_reduce(n, {:suspend, acc}, fun, i),
    do: {:suspended, acc, &do_reduce(n, &1, fun, i)}

  defp do_reduce(:infinity, {:cont, acc}, fun, i),
    do: do_reduce(:infinity, fun.(i, acc), fun, i + 1)

  defp do_reduce(0, {:cont, acc}, _fun, _i), do: {:done, acc}

  defp do_reduce(n, {:cont, acc}, fun, i),
    do: do_reduce(n - 1, fun.(i, acc), fun, i + 1)

  def count(_), do: {:error, __MODULE__}
  def member?(_, _), do: {:error, __MODULE__}
  def slice(_), do: {:error, __MODULE__}
end

iex> Enum.take(%Naturals{upto: :infinity}, 4)   # works on INFINITE data
[1, 2, 3, 4]
iex> Enum.sum(%Naturals{upto: 100})
5050

5.3 Choosing: Protocol vs Behaviour

QuestionAnswer
Do implementations differ by capability owner (driver, adapter, strategy)?Behaviour — caller picks module
Do implementations differ by shape of the data?Protocol — dispatch on value
Need multiple implementations selected at runtime per request?Either; behaviour via config, protocol via type
Extending a library type you don’t own?Protocol (defimpl ..., for: TheirStruct)

Mental model from Erlang: a behaviour is “which module implements this interface”; a protocol is “what does this operation mean for this kind of value.” Real systems use both: an Oban worker (behaviour) might serialize payloads through a protocol internally.

Three-Way Decision: Behaviour vs Protocol vs Plain Fun

One more column completes the picture — most “polymorphism” needs neither mechanism, just a function argument (your funs from Erlang):

MechanismDispatch keyChoose when
Higher-order funthe fn the caller passesone call site, ad-hoc variation
Behaviourmodule chosen at startup/configfew swappable implementations with lifecycle attached (supervision, restarts)
Protocoltype of the VALUEopen set of data types, extensible by anyone

Escalate only as far as the variability demands: fun first, behaviour when supervision is needed, protocol for extending types you do not own.

use vs import vs alias vs require — One Table to Rule Them

These four keywords confuse everyone once; learn them once here:

KeywordEffectErlang analogue
alias Foo.Barrename for qualified calls onlynone (manual naming)
import Foounqualified function calls-import(...)
require Fooallow macro expansion from Foo-include_lib (closest)
use Fooinvoke Foo.__using__/1 macro → injects code into YOUR modulenone — metaprogramming

use is the heavyweight: use GenServer doesn’t just declare a behaviour, it writes default child-spec/callback boilerplate into your module (Ch 06 shows exactly what gets injected).

5.4 Structs in Idiomatic Use

Chapter 2 covered struct syntax. Here is how they combine with the above in a realistic service module:

defmodule MyApp.Accounts.User do
  @enforce_keys [:id]
  defstruct [:id, name: "", email: ""]

  # Constructor — the ONLY sanctioned way to build one with attrs.
  # %__MODULE__{} not %User{}: the struct is MyApp.Accounts.User, and
  # `%User{}` would compile to a top-level `User` that does not exist.
  def new(id, attrs \\ %{}) do
    %__MODULE__{id: id}
    |> struct!(attrs)          # validated update, raises on unknown keys
  end

  # Multi-clause domain logic pattern-matching on shape — record guards reborn:
  def display_name(%__MODULE__{name: ""} = user),
    do: String.split(user.email, "@") |> hd()

  def display_name(%__MODULE__{name: name}), do: name
end

Notes worth internalizing:

  • Multi-clause functions pattern-match structs exactly like records — %User{name: nil} clauses replace #user{name = undefined} guards.
  • __MODULE__ inside its own module keeps copy-paste renames painless.
  • struct!/2 updates only existing keys — an unknown key raises KeyError at the call site instead of silently growing the struct.
  • Updating uses %{user | field: value} — never mutates, returns new struct; the update syntax raises on unknown fields, catching typos like %{user | emial: ...} immediately.

The update syntax carries one invariant worth stating explicitly: it can only ever produce the SAME struct type. The __struct__ tag rides along, the field set is fixed at compile time, and unknown fields raise KeyError instead of growing the map:

iex> user = %MyApp.Accounts.User{id: 1}
iex> %{user | email: "ada@x.io"}       # typed update — still a %User{}
%MyApp.Accounts.User<...>
iex> %{user | emial: "typo"}
** (KeyError) key :emial not found in: %MyApp.Accounts.User<...>

Watch the escape hatch: Map.put(user, :mystery_field, 1) bypasses that guarantee — the result still claims to be a %User{}, but carries a field defstruct never declared, and downstream %User{} matches accept it silently. Stay in update syntax and struct!/2 around typed data; use raw Map functions only at edges you control.

5.5 The Process Toolbox You Don’t Have to Build

The Kernel docs group the standard library’s process-based modules together — these are the OTP patterns you’d otherwise hand-roll in Erlang, now battle-tested and documented:

flowchart TD
    SUP["Supervisor<br/>crash boundary"] --> GS["GenServer<br/>generic client/server state"]
    SUP --> AG["Agent<br/>minimal state holder"]
    SUP --> TS["Task.Supervisor<br/>one-shot async work"]
    TS --> T["Task<br/>async + await"]
    REG["Registry<br/>key → process lookup"] -.-> SUP
ModuleWhat it gives youErlang equivalent you’d write
Agentminimal state-holding processgen_server with one handle_call
Taskone-shot async computation + awaitspawn + receive dance
Task.Supervisorsupervised tasks (restartable, linked safely)custom supervisor for workers
GenServergeneric client/servergen_server itself
Supervisorchild specs & restart strategiessupervisor
Registrykey→process lookup, local namesgproc-style registry
Applicationstart/stop/config lifecycleapplication callback module

All runnable immediately:

# Agent: state without writing handle_call
{:ok, pid} = Agent.start_link(fn -> 0 end)
Agent.update(pid, &(&1 + 1))
Agent.get(pid, & &1)                 #=> 1

# Task: fire-and-await
task = Task.async(fn -> Enum.sum(1..100) end)
Task.await(task)                     #=> 5050

# Supervised task that survives caller crashes:
{:ok, sup} = Task.Supervisor.start_link(name: MyApp.TaskSup)
Task.Supervisor.async_nolink(MyApp.TaskSup, fn -> :expensive_work end)

# Registry: name a process by an arbitrary key (gproc-style lookup).
{:ok, _} = Registry.start_link(keys: :unique, name: MyApp.Reg)
Registry.register(MyApp.Reg, "user:1", nil)        # register *this* process
{:via, Registry, {MyApp.Reg, "user:1"}}             # hand that as a GenServer name
GenServer.whereis({:via, Registry, {MyApp.Reg, "user:1"}})  #=> pid of the owner

For processes created on demand rather than at boot, pair Registry with DynamicSupervisor — same pattern as Ch 24 §24.4, where start_child/2 takes an :id you choose:

{:ok, pid} =
  DynamicSupervisor.start_child(
    MyApp.SessionSup,
    Supervisor.child_spec({MyApp.Session, session_id}, id: session_id)
  )

From Erlang you know: these are thin, well-documented wrappers over exactly the spawn/gen_server/supervisor calls you already write. Reading their source is a good early exercise — each is a few hundred lines. Note also Kernel’s own primitives: spawn/spawn_link/ spawn_monitor/3, send/2, exit/1, throw/1, self/0 — identical to their Erlang counterparts.

Choosing guidance: reach for Agent when a plain GenServer would hold state and nothing else; Task for fire-and-collect work; skip straight to GenServer when there are multiple message kinds or timers. None of these replace ETS for shared read-heavy caches (same rule as Erlang).

5.5.1 Agent — State Without a Server

The demo above shows two of Agent’s three access modes. The full picture:

{:ok, pid} = Agent.start_link(fn -> 0 end)

# get: read-only — the fun receives state, returns a value
Agent.get(pid, & &1)                          #=> 0

# update: write-only — the fun returns the new state
Agent.update(pid, &(&1 + 1))                  # state is now 1

# get_and_update: atomic read-modify-write — the fun returns
# {value_to_caller, new_state}, both decided INSIDE the agent
Agent.get_and_update(pid, fn n -> {n * 10, n + 1} end)  #=> 0
Agent.get(pid, & &1)                          #=> 1

# cast: fire-and-forget update, caller never learns when it ran
Agent.cast(pid, &(&1 + 1))

get_and_update is the one to internalize: because the pair is computed inside the agent process, “read the current value and change it” is one atomic step — no read-then-write race between clients. The same shape you’d give a gen_server’s handle_call returning both reply and new state.

Callbacks run in the agent process, serializing all clients. A slow or raising fun blocks everyone — and a raise kills the agent, exactly like a crashing handle_call kills a gen_server:

defmodule MyApp.Counter do
  use Agent

  def start_link(init), do: Agent.start_link(fn -> init end, name: __MODULE__)
end

{:ok, _} = Supervisor.start_link([{MyApp.Counter, 42}], strategy: :one_for_one)
Agent.get(MyApp.Counter, & &1)                #=> 42
try do
  Agent.update(MyApp.Counter, fn _ -> raise "bad" end)
catch
  :exit, _ -> :ok                             # caller catches the agent exit
end
Agent.get(MyApp.Counter, & &1)                #=> 42 — again

The second get returning 42 is the lesson: the supervisor restarted the agent from its start_link fun, so every mutation since startup is gone. Agent state is restartable-ephemeral — important state needs persistence or belongs in a stateful GenServer with handle_continue recovery (Ch 23).

In production you wrap the PID behind a named module API instead of passing raw PIDs around:

defmodule MyApp.Counter do
  use Agent

  def start_link(init), do: Agent.start_link(fn -> init end, name: __MODULE__)
  def inc(by), do: Agent.cast(__MODULE__, &(&1 + by))
  def value, do: Agent.get(__MODULE__, & &1)
end

(start_link/1 above is defined once in §5.5.1 — shown again here only to keep the wrapper complete.)

NeedReach for
State, nothing else; simple get/setAgent
Timers, multiple message kinds, complex transitionsGenServer (Ch 23)
Read-heavy shared data, must survive crashes:ets (Ch 22) — no serialization, no callbacks

5.5.2 Task — The Failure Matrix

Task.async + await is the happy path. What matters for real systems is what happens on the three unhappy paths — crash, timeout, and caller death. Each variant answers one question: who dies with the failure?

# 1. Plain async: linked. A task crash KILLS THE CALLER too.
task = Task.async(fn -> exit(:boom) end)
Task.await(task)
#=> the caller exits with :boom — the link propagates the exit

# 2. await with a timeout: the CALLER exits, not the task
task = Task.async(fn -> Process.sleep(10_000) end)
Task.await(task, 100)
#=> exits the caller: {:timeout, {Task, :await, [task, 100]}}
#   the task keeps running unobserved in the background

# 3. Supervised + nolink: failure arrives as a VALUE, caller survives
{:ok, _} = Task.Supervisor.start_link(name: MyApp.TaskSup)
task = Task.Supervisor.async_nolink(MyApp.TaskSup, fn -> exit(:boom) end)

case Task.yield(task, 5_000) || Task.shutdown(task) do
  {:ok, result} -> result                  # completed in time
  {:exit, reason} -> {:error, reason}      # crashed — we did not
  nil -> {:error, :timeout}                # yield timed out, shutdown killed it
end

The yield/2 || shutdown/1 pair is the workhorse: Task.yield/2 waits up to the timeout and returns {:ok, _}, {:exit, _}, or nil — a value you pattern-match, never an exit. Task.shutdown/1 cleans up the straggler when the yield gave up. Ch 26 builds saga error handling directly on this triple; Ch 28’s fan-out uses its bounded cousin:

# Many items, bounded concurrency, per-item timeout:
results =
  prompts
  |> Task.async_stream(&LLM.complete/1,
      max_concurrency: 16, timeout: 30_000, on_timeout: :kill_task)
  |> Enum.map(fn
    {:ok, result} -> result
    {:exit, reason} -> {:error, reason}
  end)

max_concurrency bounds how many run at once — verified easily by counting concurrent executions inside the fun. It is a parallelism bound, not a rate limit: an API that allows 10 requests/second still needs retry handling (§28.4’s retry: :transient) even at max_concurrency: 1.

SituationUse
Quick parallel work, caller wants to die on failureTask.async + await
Failure must be a value; caller outlives crashesTask.Supervisor.async_nolink + yield/shutdown
Bounded parallel map over many itemsTask.async_stream + max_concurrency

Explore More

  • Module attributes & behaviours guide
  • Protocols guide — including fallback implementations and consolidation internals
  • use documentation — how __using__ injection works, when to write your own
  • GenServer docs — read the client/server call trace diagrams; they’ll feel like home
  • Erlang Design Principles: behaviours — the rationale behind @callback, from the language’s own designers; it answers “why isn’t dispatch dynamic” better than any Elixir-specific doc
  • Exercise idea: implement the same “pluggable serializer” twice — once as a behaviour with two modules, once as a protocol with two impls — then note which version made the caller’s life easier and why
  • Exercise: reproduce §5.5.2’s failure matrix in iex — a crashing Task.async, an await timeout, and an async_nolink + yield — and observe who dies in each case before reading the comments

Checkpoint

  1. Translate an Erlang -callback pair into Elixir with @impl.
  2. When does a protocol beat a behaviour?
  3. What makes use GenServer different from @behaviour :gen_server?
  4. Which standard protocol must a type implement for "#{term}" to work?
  5. Which Agent function makes “read and replace state” atomic?
  6. In Task.async_stream(..., max_concurrency: 4), what exactly does the 4 bound — and what does it not bound?
Answers
@callback encode(term()) :: binary()
# impl side:
@impl true
def encode(term), do: :erlang.term_to_binary(term)
  1. When selection depends on the value’s type rather than a caller-chosen module — especially for extending types you don’t own.
  2. use GenServer is a macro (Ch 06): it declares the behaviour AND injects default child-spec/callback boilerplate into your module.
  3. String.Chars — interpolation calls to_string/1, which dispatches through it (List.Chars is its charlist sibling).
  4. Agent.get_and_update/3 — the {value, new_state} pair is computed inside the agent process, so no other client can read or write between the read and the write.
  5. It bounds tasks running simultaneously (a parallelism bound). It does not bound requests per unit of time — that’s rate limiting (§28.4) — nor total work submitted.

Next: Chapter 6 — Metaprogramming & DSLs