Chapter 26 — OTP Wisdom: Four Ideas That Hold Everything Up
Part V so far has been mechanics: processes and signals (Ch 22), the
GenServer protocol (Ch 23), supervision trees (Ch 24), pattern matching’s
execution rules (Ch 25). This chapter steps back to the wisdom — the four
ideas that make those mechanisms a coherent philosophy rather than a pile of
features. Everything idiomatic in Elixir, from {:ok, _} tuples to Reactor
sagas, is these ideas wearing different clothes.
- Isolation — no shared state, therefore no shared fate.
- Fail fast — crash loudly on the impossible instead of limping on.
- Pattern matching — make state legible and illegal states unmatchable.
- Packaging — when a pattern repeats everywhere, distill it into a library (Reactor, Oban, Broadway — Ch 13–14).
From Erlang you know: none of this is new doctrine — it is the same design principles Joe Armstrong articulated for Erlang. What Part V adds is the mechanical honesty: every piece of advice below resolves to a concrete mechanism you have already traced — copy semantics, exit reasons, receive marks, restart budgets.
26.1 Isolation — No Shared State Means No Shared Fate
Every value in a process is unreachable from another process except as a copy in a mailbox (Ch 22 §22.1). That single fact cascades:
- Memory is private. One process’s runaway allocation or GC pause cannot stall another’s heap.
- Corruption is local. A bad update destroys one process’s state, never half of twelve components’ shared objects.
- Reasoning is local. To know what a process does, read that process — there is no lock order, no visible-vs-volatile, no other thread mutating under you.
- Failure is local by default — which is why links and monitors exist: isolation cuts you off from others’ failures, so the runtime gives you explicit channels to opt back into hearing about them (Ch 22 §22.4).
The Two Demons It Starves: Races and Deadlocks
Shared-memory concurrency has two classic failure modes, and isolation starves both near the root.
No data races — by construction. A data race needs shared mutable state touched concurrently. On the BEAM there is no shared mutable state: state belongs to exactly one process, and everyone else negotiates through message copies. Updates happen inside the owner’s sequential execution of its own mailbox, so lost-update and torn-read bugs cannot exist on owned state:
# elsewhere: counter++ under a lock — and pray every site remembers it
# BEAM: one owner; the mailbox serializes every update for free
GenServer.call(Counter, :increment) # never lost, never torn
Verified live: 500 processes incrementing one counter concurrently end with exactly 500 — not because anyone locked anything, but because only one process ever touches the number.
Deadlocks shrink to one visible shape. There are no locks to order, so
the classic lock-cycle deadlock cannot form. What remains is message
deadlock — the synchronous-call cycle: A calls B while B calls A, each
waiting inside handle_call (Ch 23 §23.8). Even there the runtime stays honest:
calls carry timeouts — 5000 ms by default — so the cycle ends with each
participant exiting {:timeout, {GenServer, :call, [args]}} instead of a
thread pool hung forever. Five seconds is the default, not milliseconds;
size it deliberately, because a too-short timeout turns a slow-but-fine
dependency into a spurious crash. The habit that removes even that: never call synchronously into
a process that may be waiting on you — reply deferred (GenServer.reply/2,
26.3) or go async.
One honesty clause: isolation kills data races, not logic races. Check-then-act across two separate calls (“does the user exist?” … then “create”) can still interleave. The cure is the same principle applied once more: move the decision inside the owning process so it executes against one consistent state — the mailbox becomes your critical section.
The architectural consequence has a name: the error kernel. Keep state that must survive in stable, rarely-crashing processes; put volatile, risky work in expendable ones:
children = [
MyApp.ConfigStore, # kernel: small, boring, vital
MyApp.Repo,
{DynamicSupervisor, name: MyApp.WorkerSup} # expendable workers churn here
]
When a worker dies, the kernel does not care. When the kernel dies, the tree rebuilds everything beneath it. The wisdom: design where crashes are allowed to happen, then let them.
26.2 Fail Fast — Crash Early, Restart Clean
Erlang-style systems do not primarily handle errors; they classify them and spend recovery effort only where it pays:
| Failure class | Example | Response |
|---|---|---|
| Expected, business-level | validation failed, entity missing | return {:error, reason} to the caller |
| Expected, environmental | HTTP timeout, queue down | retry with backoff / circuit-break |
| Unexpected — a bug | MatchError, FunctionClauseError, bad arithmetic | crash now; the supervisor rebuilds clean |
The third row is the counter-intuitive one. The instinct from shared-memory
languages is to defend: catch, log, continue. But continuing means running
with state you can no longer trust — the zombie process whose internal
invariant broke somewhere unlogged. Restarting from scratch re-establishes
every invariant in one move, because init/1 builds fresh, valid state
(26.3: queued messages die too — nothing poisoned survives).
def handle_call(:pop, _from, [head | tail]), do: {:reply, head, tail}
# empty pop on a stack that must never be empty? Do NOT return nil.
# Crashing here surfaces the real bug - who violated the protocol?
This is only affordable because of §26.1 + Ch 24: crash damage stops at the process boundary, and restart cost is bounded by the tree’s budget. Fail fast is not recklessness — it is the cheapest reliable recovery strategy once someone else owns the recovery.
Erlang Is Not a Defender Language
Most mainstream languages train a defensive reflex: null-check every value,
wrap every call in try/catch, re-validate inputs at every layer. That is
rational there — an uncaught error takes down the whole process group,
recovery is hand-written at each site, so every line of code must fend for
itself. The BEAM inverts the economics: recovery lives in the architecture
(supervisors), not in the code text, so you defend once at the boundary and
trust inside:
# defender reflex — survive every possible wrongness right here, everywhere:
name =
if is_map(user) and is_binary(user[:name]) and byte_size(user[:name]) > 0,
do: user[:name],
else: "unknown"
# BEAM reflex — assert the contract; let reality disagree loudly:
%{name: name} = user
The first version hides a corrupt record behind "unknown" forever; the
second turns it into a crash report tonight. Between trusted internal
components, the second is the error handling — the supervisor is the
catch. You still return {:error, _} tuples where failure is part of the
contract (the table’s first two rows); you simply stop pretending that
scattering rescues through business logic makes a system reliable. It
makes it quiet.
26.3 Pattern Matching — Making State Legible
Isolation gives each process private state; fail fast punishes broken invariants. Pattern matching is how you make those invariants visible — in the types-as-shapes, in the clauses, in the control flow (Ch 25).
Three habits carry most of the value:
Tag your outcomes. {:ok, value} / {:error, reason} are not a
convention because they look nice — they exist so that shape carries
meaning and a mismatched shape fails loudly instead of being misread:
{:ok, user} = Accounts.register(attrs) # contract: only ok reaches here
Model states as data, transitions as clauses. A state machine needs no framework when states are plain maps and legal transitions are function heads:
def next(%{status: :cart, items: [_ | _]}), do: {:ok, :checkout}
def next(%{status: :checkout, paid?: true}), do: {:ok, :fulfilled}
def next(%{status: s}) when s in [:cart, :checkout], do: {:error, :incomplete}
def next(_), do: {:error, :unknown_state}
Reading the heads is reading the spec. An impossible state (paid? with no
order) falls to the catch-all and announces itself as :unknown_state
rather than silently computing nonsense.
Let the protocol live in the callbacks. A GenServer whose
handle_call/handle_cast clauses enumerate every request is
self-documenting; the catch-all handle_info from Ch 23 §23.4 then makes stray
traffic visible instead of queued-and-forgotten.
The wisdom: pattern matching moves correctness checking from review-time hope (“does everyone handle this branch?”) to runtime fact (“this clause does not match — crash now”), which is exactly what §26.2 wants.
Why It Fits the Way You Already Think
The article behind this chapter called pattern matching friendly with your brain — and that is a mechanical claim, not a mood. Four reasons:
- Recognition beats navigation. You do not verify “this is my friend”
by measuring their nose; you recognize a whole shape at once. A clause
works the same way:
%{status: :checkout, paid?: true}states a recognizable situation. The conditional-chain equivalent forces you to navigate into the data one probe at a time, mentally tracking where in the structure am I — bookkeeping the pattern style simply deletes. - Case analysis is your default decision procedure. Ask anyone how
refunds work and they answer in cases: *“if it shipped but wasn’t
delivered …; if it never shipped …. Nobody answers in nested booleans.
Piecewise function heads are that spoken answer, one clause per case,
each clause naming its own parts (
paid?,carrier) precisely where those names carry meaning. - One scenario per unit of attention. Understanding a clause means holding one situation in working memory. The imperative alternative asks you to simulate machine state — flags set three lines ago, a variable rebound since — spending cognition on bookkeeping instead of domain meaning.
# navigation: descend probe by probe, tracking where you are
if message["type"] == "payment" and message["status"] == "declined" do
if message["retry_count"] < 3 do
:retry # the *situation* is now buried three levels deep
end
end
# recognition + extraction in one act — each clause names the case AND
# binds the parts that matter to it:
handle = fn
%{type: "payment", status: "declined", retry_count: n} when n < 3 ->
{:retry, n}
%{type: "payment", status: "declined"} ->
:give_up
_message ->
:not_a_payment
end
handle.(%{type: "payment", status: "declined", retry_count: 2})
#=> {:retry, 2}
handle.(%{type: "payment", status: "declined", retry_count: 7})
#=> :give_up
handle.(%{type: "ping"})
#=> :not_a_payment
Extraction composes through nesting the same way — one match, names bound where they belong:
payload = %{
order: %{
items: ["book", "pen"],
customer: %{email: "ada@x.io"},
total: 42
}
}
%{order: %{items: [first_item | _rest], customer: %{email: email}, total: total}} =
payload
first_item
#=> "book"
email
#=> "ada@x.io"
total
#=> 42
- The clause list is both program and document. “What situations exist?” is answered by scanning the heads top-down — the exact scan the runtime performs (Ch 25). When the structure of the code and the structure of your mental table of cases coincide, complexity stops compounding: a new scenario is a new clause beside its peers, not another level inside a nest nobody dares re-indent.
This is the quiet reason BEAM codebases stay readable late into their life: the language’s branching primitive is the shape humans already use to think about situations.
26.4 Reactor — Wisdom Packaged Into a Workflow
The frameworks this chapter closes with are, at bottom, nothing exotic: a process exchanging messages with other processes — GenServer being the everyday example — arranging work that takes locks and thread pools elsewhere. That is why concurrency here is easy to make work: parallelism is “spawn more processes,” coordination is “send and receive,” and safety is §26.1’s mailbox serialization instead of lock discipline.
Run the ideas together and a familiar problem appears. Isolation says there is no cross-service transaction; fail fast says a failed step should just stop; but an order flow that charged a card must not leave the charge standing when shipping fails.
Read Ch 14 first? Then Reactor’s API is already familiar to you, and the rest of this section is the why — why the compensation semantics are what they are. Skip to “Persist the log” below; do not re-read the API. If you have not read Ch 14, the walkthrough here stands on its own and needs no library at all. The resolution is the saga: run steps forward, remember completed work as data, undo it newest-first on failure. Here is the entire idea, using nothing but Ch 25’s matching:
defmodule MiniSaga do
# a step is {name, run, undo};
# run returns {:ok, value, ctx} | {:error, reason}
def run(steps, ctx), do: run(steps, ctx, [])
defp run([], ctx, log), do: {:ok, ctx, log} # log = undo stack, newest first
defp run([{name, run_fn, undo_fn} | rest], ctx, log) do
case run_fn.(ctx) do
{:ok, value, ctx2} ->
run(rest, ctx2, [{name, undo_fn, value} | log])
{:error, reason} ->
# each undo needs ITS OWN step's value, not the starting ctx
Enum.each(log, fn {_name, undo, value} -> undo.(value) end)
{:error, reason}
end
end
end
That third tuple element is the part hand-rolled sagas always get wrong: an
undo typically needs what the forward step produced (the charge id, the
reservation token), not the context that entered it. Logging {name, undo}
alone forces every undo to re-derive its input — or, worse, to close over
the wrong value.
steps = [
# the undo fn receives what the forward step returned
{:reserve, &Reservations.reserve/1, &Reservations.release/1},
{:charge, &Payments.charge/1, &Payments.refund/1},
{:ship, &Shipping.dispatch/1, fn _result -> :nothing_to_undo end}
]
MiniSaga.run(steps, %{order_id: 42})
#=> {:ok, %{order_id: 42, reservation: ..., payment: ..., tracking: ...}, _log}
# if :ship fails, :charge is undone BEFORE :reserve - reverse completion order
#=> {:error, :carrier_down}
Twenty lines, and already the essential saga semantics: forward execution, an explicit undo log as ordinary data, LIFO compensation. Two upgrades take it toward what a real workflow engine provides:
Isolate each step. A step that crashes instead of returning {:error, _} would kill our saga process — exactly backwards for §26.1. Run steps on
a supervisor’s tasks, unlinked, and let failures arrive as values:
task = Task.Supervisor.async_nolink(OrderFlow.Tasks, fn -> run_step(step, ctx) end)
case Task.yield(task, 5_000) || Task.shutdown(task) do
{:ok, {:ok, value, ctx2}} -> advance(step, value, ctx2)
{:ok, {:error, reason}} -> {:error, reason}
{:exit, reason} -> {:error, {:crashed, reason}} # step died - we did not
nil -> {:error, :timeout}
end
(Verified shape: a raising step arrives as {:exit, {exception, stacktrace}}
while the saga process lives on to compensate. This is Ch 05 §5.5.2’s failure
matrix — async_nolink + yield || shutdown — applied to workflow steps.)
Parallelize what is independent. Because concurrency is just more processes — spawning costs microseconds and message passing needs no locks — the saga’s dependency graph falls out naturally: steps with no data dependency run at the same time, and joining is collecting results:
results =
ready_steps
|> Task.async_stream(&run_step(&1, ctx),
# NOT System.schedulers_online(). These steps are IO-bound — charging a
# card, calling a carrier API. Core count bounds CPU work; provider rate
# limits bound everything else. Too low and you under-use connections;
# too high and you get 429s. See Ch 28 §28.4.
max_concurrency: 16
)
|> Enum.map(fn {:ok, result} -> result end)
System.schedulers_online() is the right default for CPU-bound Nx work
(Part IV) and the wrong one here. Choose per step: the resource you are
calling, not the machine you are on.
This is why Reactor advertises concurrent steps as a default rather than a feature-list item (Ch 14): on this runtime, not running independent steps together would be the special case.
Persist the log. An in-memory undo log dies with the node mid-saga. Durability — steps and compensations surviving deploys and crashes — is the line where sagas become Oban jobs or Reactor reactors rather than twenty lines of recursion (Ch 13–14).
That is the “reactor” lesson of this chapter: frameworks like Reactor are
not new runtime magic. They are §26.1–§26.3 compiled into a reusable
shape — steps isolated on supervised tasks, failures normalized into
data by pattern matching, compensation applied by policy. Ch 14 taught you
when to reach for them; now you know why they can be that small inside
— and when your case is simple enough that MiniSaga plus honesty about
durability is the better tool.
flowchart TD
STEP["step crashes mid-flow"] -->|"isolation:<br/>async_nolink"| TASK["task exits,<br/>saga unaffected"]
TASK -->|"fail fast normalized<br/>to a value"| MATCH["pattern match on<br/>exit reason"]
MATCH -->|"compensation"| UNDO["undo log applied<br/>newest first"]
MATCH -->|"unrecoverable"| SAGA["saga itself exits"]
SAGA -->|"supervision"| TREE["supervisor restarts<br/>the whole flow clean"]
UNDO --> OUT["caller sees one<br/>consistent outcome"]
TREE --> OUT
26.5 The Wisdom in One Table
When a design decision stalls, locate it on this map:
| Symptom or question | Governing idea | Mechanism |
|---|---|---|
| “Where do I put state that must not die?” | isolation / error kernel | stable processes low in the tree (26.1) |
| “Should I rescue and continue here?” | fail fast | only at boundaries; else crash (26.2) |
| “How do I represent ‘no result’?” | pattern matching | {:error, :not_found}, never nil into logic |
| “This branch is unreachable, surely” | pattern matching | make it crash — catch-all clause logs (26.3) |
| “Multi-service rollback?” | packaging | saga: Reactor/Oban when durability matters (26.4) |
| “One process per session/connection?” | isolation | Registry + DynamicSupervisor (Ch 24 §24.8) |
| “Many actors updating one resource?” | isolation | one owning process; its mailbox serializes updates (26.1) |
| “Who retries after failure?” | supervision | restart policy + budget, never hand-rolled loops (Ch 24 §24.4–24.5) |
And the meta-wisdom that closes Part V: when you feel the urge to build infrastructure — pools, retries, workflows — first write the twenty-line version from these primitives. The BEAM makes the small version honest; the ecosystem’s frameworks are there for when the pattern, not the feature, is your product.
Explore More
- OTP Design Principles — the source of this wisdom, from error kernel to behaviours
- Joe Armstrong’s thesis — Making reliable distributed systems in the presence of software errors; the intellectual foundation of everything in Part V
- Ch 14 — Reactor’s actual DSL: compensation policies (
:retry/ fallback), declarative step graphs, undo ordering - Exercise idea: extend
MiniSagawith per-stepmax_retriesusing backoff, then kill the node between two steps and observe what an in-memory log cannot save you from - Exercise idea: convert Ch 10’s LiveView-per-session model into the error kernel vocabulary — which parts are kernel, which are expendable?
Checkpoint
- Why does isolation make fail fast affordable, rather than merely possible?
- Your GenServer receives a request that violates its protocol. What does
the wisdom say — return
{:error, _}or exit? How do Ch 22–24 mechanisms carry out that answer? - In the saga, why must compensation run newest-first?
- What does
async_nolink+Task.yieldchange about a step crash, and which of the four ideas does that serve? - When is
MiniSagathe wrong tool despite working fine? - Where can race-like bugs still appear on the BEAM, and what is the standard cure?
- Why does idiomatic BEAM code read happy-path compared to defensive styles, and where does the defense actually live?
- In a saga’s dependency graph, what lets two steps run concurrently — and what makes that safe here when it needs locks elsewhere?
- Nested conditionals and clause lists can express the same dispatch. Name two cognitive costs the nested version adds that clauses avoid.
Answers
- Because a crash’s blast radius stops at the process boundary — no shared state means nothing else is corrupted — so restarting one process truly repairs the damage; supervision then automates the repair.
- Exit if it indicates broken internal invariants or misuse by another
internal component (crash → supervisor rebuilds clean state); return
{:error, _}only for expected, caller-facing cases like validation. Links/monitors deliver the crash as a signal upstream instead of a wrong reply propagating. - Later steps may depend on earlier effects — refunding before releasing inventory would be fine here, but reversing order generally undoes dependent effects before their dependencies, mirroring reverse shutdown order in trees (Ch 24 §24.6).
- A crashing step becomes a value (
{:exit, reason}) delivered to the saga instead of a signal killing it — isolation turned a fatal signal into data that fail-fast policy can act on. - When the flow must survive node restarts or deploys mid-saga: the undo log lives in memory, so you need durable jobs (Oban) or a real reactor engine with persisted state (Ch 13–14).
- Logic races: check-then-act split across two separate calls can interleave between the calls. Cure: move the decision into the single owning process so it executes against one consistent state.
- Recovery moved from code text to architecture: supervisors own repair,
so internal code asserts contracts via patterns and crashes on violation
instead of scattering null-checks and rescues; boundaries still return
{:error, _}for expected cases. - No data dependency between them — each consumes only
ctxplus its own inputs. It is safe without locks because steps run as isolated processes exchanging messages; the mailbox serializes anything they share, and the saga joins results by ordinary receives/collections. - (1) Navigation bookkeeping — tracking position inside a structure across multiple probes, instead of recognizing one shape; (2) machine-state simulation — remembering flags/rebindings from earlier branches, since each clause is otherwise self-contained with its own named parts. The clause list also doubles as the documentation of existing cases.
Next: Chapter 27 — Debugging & Tracing — the Part V capstone: every tool for inspecting what the machinery did. From there, Chapter 30 — The Migration Roadmap returns you to practice.