From Erlang to Elixir
A Practitioner’s Guide to the BEAM Ecosystem
You already know the hardest part: BEAM + OTP. Elixir gives you more places to apply it.
This book is a step-by-step migration guide for Erlang/OTP developers who want to move into the Elixir ecosystem — Web (Phoenix/LiveView), Data (Ecto/Broadway), Edge (Nerves/AtomVM), and AI (Nx/Axon/Bumblebee) — without abandoning anything they already know.
The Central Idea
Erlang/OTP provides the foundation. Elixir builds on it. The ecosystem expands into three major domains, each with flagship libraries:
flowchart TD
OTP["Erlang / OTP"] --> EX["Elixir"]
EX --> WEB["Web"]
EX --> EDGE["Edge"]
EX --> AI["AI"]
WEB --> PHX["Phoenix<br/>LiveView"]
EDGE --> NERVES["Nerves<br/>AtomVM"]
AI --> NX["Nx<br/>EXLA / EMLX"]
PHX --> P["Products"]
NERVES --> P
NX --> P
The arrow direction matters — knowledge flows down from Erlang/OTP through Elixir into products. You don’t replace Erlang; you extend its reach.
Both languages compile to the same BEAM bytecode and use the same OTP libraries. The runtime — schedulers, GC, distribution — is identical. Only the syntax and tooling layer differ.
Table of Contents
Part I — Foundations: What Transfers
| Ch | Title | What You’ll Learn |
|---|---|---|
| 01 | You Already Know the Hard Part | Mental model, what transfers, what doesn’t |
| 02 | Syntax Translation Guide | Modules, structs, pattern matching, full keyword map |
| 03 | Tooling: From rebar3 to Mix | First project step-by-step, deps, tests, releases |
| 04 | Pipes, Enum & Stream | Idiomatic data flow |
| 05 | Behaviours, Protocols & Structs | Polymorphism in Elixir |
Part II — Language Power-ups: What Elixir Adds
| Ch | Title | What You’ll Learn |
|---|---|---|
| 06 | Metaprogramming & DSLs | Macros, AST, why Phoenix/Ecto feel native |
| 07 | Gradual Typing | Set-theoretic types, mix compile diagnostics |
| 08 | The Compilation Model | .ex → AST → macros → BEAM bytecode |
| 09 | Mix, Releases & Running OTP Apps | Build pipeline, config timing, releases, hot upgrades |
Part III — The Ecosystem Map
| Ch | Title | What You’ll Learn |
|---|---|---|
| 10 | Phoenix & LiveView | OTP processes as web architecture |
| 11 | Ecto: The Data Layer | Schemas, changesets, queries, migrations, sandbox testing |
| 12 | Ash: Declarative Domain Modeling | Resources, actions, policies, swappable data layers |
| 13 | Data, Jobs & Pipelines | Oban, Broadway/GenStage, Explorer |
| 14 | High-Level Process Frameworks | Reactor sagas, Jido agents, the abstraction ladder |
| 15 | Livebook | Interactive exploration of live systems |
| 16 | Edge, IoT & Mobile | Nerves, AtomVM, Mob/Dala |
Part IV — AI on the BEAM
| Ch | Title | What You’ll Learn |
|---|---|---|
| 17 | Nx Fundamentals | Tensors, defn, autodiff |
| 18 | Backends: EXLA, EMLX & Hardware | The what/how separation |
| 19 | Training Models with Axon | MNIST end-to-end, CNNs, transfer learning |
| 20 | Bumblebee: Pre-trained Models | Hugging Face in Elixir, zero Python |
| 21 | Production Inference: Nx.Serving | Batched serving + the mnist_phoenix app |
Part V — Under the Hood: Deep Dives
| Ch | Title | What You’ll Learn |
|---|---|---|
| 22 | Processes Deep Dive | Spawn, mailboxes, links, monitors, exit signals |
| 23 | GenServer Under the Microscope | The call protocol decoded, timeouts, terminate, debugging |
| 24 | Supervisors Deep Dive | Child specs, strategies, restart budgets, shutdown order |
| 25 | Pattern Matching Deep Dive | How = executes, pins, maps/structs, binary segments |
| 26 | OTP Wisdom | Fail fast, isolation, matching as design, sagas/Reactor |
| 27 | Debugging & Tracing Techniques | IO.inspect/dbg, pry, breakpoints, IEx setup, Observer, :sys.trace/:dbg/recon, config debugging |
Part VI — Practice & Direction
| Ch | Title | What You’ll Learn |
|---|---|---|
| 28 | LLM Integration & Agents | Adapters, streaming, RAG, agent frameworks |
| 29 | Architecture Philosophy | BEAM orchestrates; specialized runtimes compute |
| 30 | The Migration Roadmap | 8-week step-by-step plan with checklists |
Part VII — AI Practice Labs
Runnable labs pairing chapters with Livebooks in the
part-vii-ai-practice-labs/livebooks/
collection — all-new examples, none reused from earlier chapters.
| Lab | Title | Livebook | Pairs With |
|---|---|---|---|
| LAB 1 | Nx Optimization: Tilting Solar Panels | LAB1_nx_tilt_optimizer.livemd | Ch 17, 18 |
| LAB 2 | Classical ML with Scholar: The Iris Botanist | LAB2_scholar_iris.livemd | Ch 13, 17 |
| LAB 3 | Axon: Untangling the Two Spirals | LAB3_axon_spiral.livemd | Ch 19 |
| LAB 4 | CNN on Fashion-MNIST: Wardrobe Vision | LAB4_cnn_fashion_mnist.livemd | Ch 19, 21 |
| LAB 5 | Character-Level LSTM: A Tiny Text Generator | LAB5_char_lstm.livemd | Ch 19, 20 |
| LAB 6 | Bumblebee Semantic Search: The Support Desk | LAB6_bumblebee_semantic_search.livemd | Ch 20, 28 |
How to Read This Book
Fast track (you want productivity this week): Ch 01 → 02 → 03 → 04 → 09 → 10 → 25 → 30. Ch 25 is here because it is the one chapter that names every Erlang reflex Elixir breaks — rebinding, match semantics, pinned sizes — and Ch 30’s Phase 1 assumes you have read it.
Deep dive (you want the full ecosystem picture): Read straight through. Each chapter ends with a checkpoint.
Under the hood track (you want to know exactly how it works): Part V — Ch 22 → 23 → 24 → 25 → 26 → 27, then on to Ch 28. Self-contained deep dives; drop in whenever a mechanism surprises you, or read as a unit after Ch 14.
Practice lab track (learn AI by running it):
Part VII — LAB 1 → LAB 6. Each lab is a runnable Livebook in
part-vii-ai-practice-labs/livebooks/:
open the .livemd, run the cells top to bottom, then do the exercises.
Labs are self-contained; start with LAB 1 for Nx fundamentals or jump to
LAB 6 for the inference-first pattern. Setup, resource requirements, and
per-lab runtimes are in the Part VII README.
Hands-on track (learn by running things): Type and run every chapter’s Step-by-step blocks as you read.
Prerequisites
- Erlang/OTP 26+ minimum — new installs should use the latest stable line (OTP 28/29 as of writing); check Elixir’s Compatibility and deprecations for the pairing
- Elixir 1.15+, recommended 1.20+ for gradual typing (Ch 07; verified against 1.20.3, re-verified on 1.20.4)
- Livebook for interactive exploration (Ch 15; several chapters run code in Livebook cells):
# macOS
brew install livebook
# Or via mix
mix escript.install hex livebook
# Start a server from the repo root
livebook server # then open http://localhost:8080
Conventions Used
- “From Erlang you know” boxes connect new material to existing knowledge.
- Step-by-step blocks are meant to be typed/run as you read.
- Checkpoint sections let you verify understanding before moving on.
- Explore More sections point to the canonical docs and next exercises.
- Code pairs show Erlang first, Elixir second, unless noted.
Built on the elixir_ecosystem_sharing collection of Livebooks and
runnable examples; the Part VII labs (LAB1–LAB6) are an all-new
companion collection. MIT licensed.
Chapter 1 — You Already Know the Hard Part
If you know Erlang/OTP, you already understand the core engineering model. This chapter establishes exactly what transfers — and what the actual learning curve looks like.
Most migration guides assume you’re learning concurrency from scratch. This one doesn’t, because you aren’t. By the end of this chapter you’ll know precisely which parts of Elixir are new for you (they fit in four layers) and which parts are the same machine wearing different syntax.
1.1 The Mindset Shift That Isn’t One
Learning a new language usually means re-learning three things at once: a concurrency model, a runtime, and a failure philosophy. Yours requires none of that. Look at what you already carry:
- Processes & message passing — lightweight isolated processes, mailboxes,
receiveloops. Elixir callsspawnspawn, sends withsend/2, and its mailboxes behave identically because they are identical.- Supervision & GenServer — restart strategies (:one_for_one,:rest_for_one,:one_for_all), child specs, fault recovery trees. Elixir’sSupervisor/GenServerare thin wrappers over the samesupervisor/gen_servermodules. - Behaviours & distribution — callback contracts,
-behaviourdeclarations, transparent clustering via distribution. All present, all unchanged underneath. - Let-it-crash — error isolation, fail-fast philosophy, restart to known state. If anything, Elixir leans harder into this than most Erlang code bases do.
- ETS, Mnesia,
:timer,:gen_statem— every storage and state primitive is callable directly from Elixir as:ets.new(...),:gen_statem.start(...). - Functional programming — immutability, pattern matching, recursion, single assignment. The semantics you rely on daily transfer untouched.
None of this needs re-learning. It transfers 1:1 because both languages run on the same VM and compile to the same bytecode:
flowchart TD
ER["Erlang<br/>.erl files"] --> BC["BEAM bytecode"]
EX["Elixir<br/>.ex files"] --> BC
GL["Gleam"] --> BC
BC --> VM["Same BEAM VM<br/>schedulers · GC · distribution"]
VM --> OTP["Same OTP libraries<br/>gen_server · supervisor · ets"]
(Gleam is another language on this tree — same runtime, same idea. The point is not that Elixir is special; it’s that the runtime is the platform.)
What this means concretely: when you read Elixir code, translate it to the
Erlang you know and you will almost always be right. %User{name: name}
pattern-matches like a record. A GenServer.handle_call/3 clause dispatches
like gen_server:handle_call/3. The differences are surface, not substance.
Reductions: Why Every Process Gets Its Turn
Does Elixir change scheduling? No — and it is worth recalling why nothing needs changing. The BEAM counts reductions: a function call costs about one, BIFs charge their own rates, and each runnable process receives a fixed budget (4000 reductions by default) before the scheduler forcibly switches to the next process:
scheduler loop (per core):
pick runnable process → run until budget spent (~4000 reductions)
→ save state → pick next process → repeat forever
There is no yield because none is needed — preemption is invisible to your
code whether written in .erl or .ex. Watch the counter move yourself:
iex> {:reductions, r0} = Process.info(self(), :reductions)
{:reductions, 184112}
iex> Enum.each(1..1_000_000, &(&1 * 2))
:ok
iex> {:reductions, r1} = Process.info(self(), :reductions)
{:reductions, 5391077} # cumulative count; preempted in ~4000-reduction slices
The one caveat survives unchanged: NIFs burn no reductions while running, so
a misbehaving native function stalls a scheduler thread exactly as it would
under pure Erlang. A long-running NIF can call enif_consume_timeslice/2 to
report the slice it has used so the scheduler can reschedule it once it
returns; work that cannot yield at all belongs on a dirty scheduler, unchanged.
Distribution: Same spawn, Different Node
Distribution transfers untouched — cookies, Node.connect/1, send/2 to
pids on other nodes. Elixir’s remote-spawn spellings:
iex> Node.ping(:"b@worker.local")
:pong
iex> Node.list()
[:b@worker.local]
# Spawn Demo.report/0 ON the remote node (module must exist there):
iex> :erlang.spawn(:"b@worker.local", Demo, :report, [])
#PID<11173.84.0>
Prefer the MFA form over Node.spawn/2 with a closure: an anonymous fn
references the module that defined it, which may be missing (or stale) on
the far node. MFAs and their argument terms travel cleanly over the
distribution protocol — the same rule you would enforce in an Erlang shop.
1.2 Where the Mindset Does Shift
Everything in §1.1 is true and still incomplete: the runtime mindset transfers untouched, but Elixir is a genuinely different culture at the language layer. Pretending otherwise produces Erlang-flavored Elixir that fights every library you import. Five shifts follow — none about concurrency, all about how code gets written and shared.
Shift 1: Code Is Data — Libraries Extend the Language
In Erlang, the AST is expert territory; parse_transforms are rare and
painful enough that nobody builds on them. In Elixir, macros are everyday
library material — if, |>, ExUnit.test, and Ecto’s query syntax are
all ordinary functions-and-macros you could have written yourself:
# What looks like built-in syntax… # …is a macro over the same AST
if user.verified?, do: :allow, else: :deny # Kernel.if/2 — an ordinary macro
test("splits a pair", fn -> ... end) # ExUnit.Case.test/3
from(u in User, where: u.age > 18) # Ecto.Query.from/2
The practical mindset change: when you see repeated boilerplate, the
Erlang instinct is higher-order functions or living with it; the Elixir
instinct is a small macro or adopting a library whose DSL removes it. For
your first months you will mostly consume macros (use, import) — but
you should recognize what they are, because half of what makes Elixir
libraries feel native is that they ship language-shaped APIs (deep dive in
Ch 06).
Shift 2: Names Carry Contracts
Erlang names describe mechanics; Elixir names encode calling contracts:
| Suffix / shape | Contract | Example |
|---|---|---|
trailing ? | returns a boolean | Map.has_key?/2, your own verified?/1 |
trailing ! | raises on failure instead of returning a tuple | Map.fetch!/2, File.read!/1 |
foo / foo! pair | same operation, tuple vs raise — caller picks by context | Map.fetch/2 ↔ Map.fetch!/2 |
iex> Map.fetch(%{a: 1}, :b) # caller decides what failure means
:error
iex> Map.fetch!(%{a: 1}, :b) # failure IS exceptional here — crash loudly
** (KeyError) key :b not found in:
%{a: 1}
You will start naming your own functions this way within days — it makes call sites readable without opening docs.
Shift 3: {:ok, _}/{:error, _} Tuples Are the API Currency
Erlang conventions are heterogeneous — some APIs return tuples, some throw,
some exit. Elixir standardizes: expected failures are values
({:error, reason}), exceptions are reserved for bugs and boundary
violations, and process death remains the escalation path — let-it-crash
unchanged. This gives you uniform composition (§2.4’s with chains three
fallible steps without a single try), and it explains the ! convention
above: bang variants convert the error value into the exception your
supervisor eventually sees.
Shift 4: Data-First APIs, Piped Top-to-Bottom
The whole stdlib puts the subject first and the function/callback last —
an ecosystem-wide convention, not a language rule, and precisely what lets
|> read top-to-bottom instead of inside-out:
%% Erlang: innermost runs first; staging variables fight the flow
Name0 = maps:get(<<"name">>, Json, <<>>),
Name1 = string:trim(Name0),
Name = string:lowercase(Name1)
json["name"] # subject first…
|> String.trim() # …so each step threads left-to-right, top-to-bottom
|> String.downcase()
When you design new functions, put the primary data first and return the transformed data — your APIs become pipe-able like everyone else’s.
Shift 5: Docs and Tests Are the Culture’s Spine
edoc, EUnit, and Common Test exist in Erlang but run opt-in. In Elixir,
@moduledoc/@doc compile into the .beam (Ch 02 §2.1) and publish to
hexdocs.pm on every release; doctests make documented examples executable;
ExUnit suites run synchronously by default and opt into async: true when
they are process-isolated. Two consequences: documentation
quality is a legitimate selection criterion when choosing Hex packages,
and shipping undocumented public functions reads as unfinished work.
The Habits, Side by Side
| Situation | Erlang instinct | Elixir instinct |
|---|---|---|
| Repeated boilerplate | tolerate or extract higher-order fn | consume/write a macro or DSL |
| Helper returning yes/no | is_valid(Term) | valid?(term) |
| Expected failure | mixed: tuple, throw, or crash | {:error, reason}; ! twin for raise |
| Nested transformations | staging variables, inside-out | pipeline, top-to-bottom |
| Public API hygiene | exports list is the contract | docs + specs + tests are the contract |
None of these are semantic differences — you could write either style in either language. They are the local grammar of professionalism. Adopting them is what makes your code feel native to the ecosystem your code will live in.
1.3 What Actually Differs
The genuinely new learning sits in four layers. They build on each other in this order:
flowchart TD
L1["1 · Language<br/>.ex syntax · structs · macros · pipes"] --> L2["2 · Tooling<br/>Mix · Hex · ExUnit · ExDoc"]
L2 --> L3["3 · Libraries<br/>Phoenix · Ecto · Nx · Oban"]
L3 --> L4["4 · Conventions<br/>product/application style,<br/>contexts, testing culture"]
style L4 fill:#e8f5e9
style L1 fill:#fff3e0
| Layer | From (Erlang) | To (Elixir) | Effort |
|---|---|---|---|
| Language | .erl, records, -export | .ex, structs, def/defp | Days |
| Tooling | rebar3, erlang.mk | Mix, Hex, ExUnit, ExDoc | Days |
| Libraries | OTP apps, jiffy, cowboy | Hex packages: Phoenix, Ecto, Nx… | Weeks |
| Conventions | infrastructure style | product/application style | Ongoing |
Why the effort column matters: layers 1–2 are days — mechanical translation with occasional surprises (strings! §2.7). Layer 3 is weeks only because it’s breadth — each library individually is approachable, since every Hex package is an OTP application you can already read. Layer 4 never ends, just like idiomatic Erlang never stopped evolving for you.
From Erlang you know: the hard 80% (BEAM + OTP) is done. The remaining 20% is surface area, not depth.
1.4 Your Skills, Mapped to New Domains
Every OTP skill has direct applications across the Elixir ecosystem. Read this table as a menu of destinations, not a syllabus:
| Your OTP Skill | Elixir Ecosystem Application |
|---|---|
| GenServer / Supervision | Phoenix LiveView (stateful connections), Nerves device trees |
Distribution / :rpc | Multi-node Phoenix, clustered Nx serving, edge ↔ cloud |
| Message passing | Broadway pipelines, GenStage flow, PubSub real-time |
| Fault isolation | Oban job retries, LiveView crash recovery, device watchdogs |
| ETS / Mnesia | Explorer dataframes, Nx tensor caches, Phoenix.PubSub |
Concrete anchors for those rows:
- A LiveView process is a GenServer whose mailbox receives DOM events — if
you’ve written a
handle_callcounter, you’ve written half a chat app. - Broadway’s backpressure is demand accounting between processes — credit management you could hand-write with raw messages.
- Nerves device watchdogs are supervisors watching GenServers that wrap
hardware — your
:one_for_oneinstincts apply to a Raspberry Pi.
This table is the thesis of the whole book. The question isn’t “Should I learn Elixir?” — it’s “Which of these domains do I want to apply my OTP skills to?”
1.5 Not a Replacement Story
Do not frame Elixir as “a nicer Erlang.” Frame it as an ecosystem expansion around the BEAM:
- Did Erlang stop being good? No — it was never not good. Telecom-grade systems still ship in pure Erlang, and nothing here suggests abandoning it.
- The ecosystem around the BEAM keeps expanding: web frameworks, data pipelines, embedded devices, numerical computing. Each expansion is built on OTP, not instead of it.
- Your existing knowledge lets you participate immediately — you skip the “learn processes” phase entirely and start at the domain layer.
flowchart TD
OTP["Erlang / OTP<br/>what you already master"] --> EX["Elixir<br/>types · tooling · composition"]
EX --> WEB["Web<br/>Phoenix · LiveView"]
EX --> DATA["Data<br/>Ecto · Oban"]
EX --> EDGE["Edge<br/>Nerves · AtomVM"]
EX --> MOB["Mobile<br/>Mob · Dala"]
EX --> AI["AI<br/>Nx → EXLA / EMLX"]
Each branch is an application domain where the leaves are libraries — all running on the same trunk you already know.
1.6 Same Terms, Same Ordering — New Names
Per the official docs (Erlang/OTP Reference Manual ↔ Elixir Kernel), both
languages share the exact same set of runtime terms. Elixir’s Kernel module
just gives them friendlier module wrappers:
| BEAM term | Erlang view | Elixir module / syntax |
|---|---|---|
| Atom | hello | :hello (true, false, nil are atoms) |
| Integer / Float | 1, 1.0 | Integer, Float modules |
| List (linked) | [1, 2, 3] | List, Enum, Stream |
| Tuple | {1, 2} | fixed-size, elem/2, put_elem/3, Tuple |
| Map | #{k => v} | %{k: v}, Map module |
| Binary / bitstring | <<1, 2>> | "binary", <<bits::size(3)>>, :binary |
| PID | <0.90.0> | self(), Process module |
| Port | connected external process | Port module |
| Function object | fun M:f/1 | fn x -> x end, &Mod.fun/1 |
| Reference | make_ref() | make_ref() |
Two data types have no wrapper module at all: bitstrings (created with
<<>>; when divisible by 8 bits they’re binaries) and references
(make_ref/0). You don’t need wrappers for types you mostly construct
literally or compare by identity.
Verify the identity yourself in IEx — this is the fastest way to make the “same terms” claim stop being an assertion:
iex> is_atom(:hello) && is_atom(true)
true # booleans ARE atoms, same as Erlang
iex> &Kernel.is_atom/1 # many Kernel guards are inlined BIFs…
&:erlang.is_atom/1 # ← literally the Erlang function
And because it’s the same VM, the term ordering is identical — this matters the moment you sort mixed collections or use terms as map keys in ordered contexts:
number < atom < reference < function < port < pid < tuple < map < list < bitstring
iex> 1 < :an_atom # numbers sort before atoms — same rule as Erlang
true
iex> Enum.sort([:b, 1, "c", {2}])
[1, :b, {2}, "c"] # number < atom < tuple < bitstring("c")
If you’ve ever debugged lists:sort/1 output wondering why {2} landed
before "c" (bitstring!), you already hold this knowledge — Elixir changes
nothing here.
From Erlang you know:
erlang:term_to_binary, record/tuple ordering, and comparison semantics all carry over untouched. Elixir’s<,==, etc. perform structural comparison on raw terms exactly like Erlang’s.
GC You Never Configure: One Heap Per Process
Memory management tells the same story. Each BEAM process owns its stack and heap; collection runs per process, generational, pausing only that process for microseconds. There is no global stop-the-world event to tune away — which is precisely why BEAM latency profiles survive Elixir code unchanged:
- Short-lived processes often never GC at all; dying releases the whole heap in one step.
- A process crunching a giant list grows its heap alone; neighboring processes’ latencies stay flat.
- Big binaries (over 64 bytes) live on a shared, reference-counted heap and cross process boundaries by pointer — sending a large payload is cheap, same as Erlang.
The usual knobs are one atom away whenever you miss them:
iex> :erlang.memory(:processes) |> div(1024)
51233 # total process-heap bytes VM-wide, in KiB
iex> :erlang.garbage_collect(self())
true
1.7 Truthy/Falsy: One Small Semantic Difference
Here is the one place where intuition can betray you. Elixir adds a concept Erlang doesn’t have: truthiness.
flowchart TD
V["a value"] --> Q{"is it false or nil?"}
Q -->|"yes"| FALSY["falsy<br/>only these two exist"]
Q -->|"no"| TRUTHY["truthy<br/>including 0, #quot;#quot;, [], :ok"]
TRUTHY --> REL["relaxed ops: && · || · !<br/>pass through fine"]
FALSY --> REL2["relaxed ops take the other branch"]
STRICTOPS["strict ops: and · or · not"] -.->|"raise BadBooleanError<br/>on non-booleans"| X["error"]
style FALSY fill:#ffebee
style TRUTHY fill:#e8f5e9
- A value is truthy when it is neither
falsenornil - A value is falsy when it is either
falseornil
That’s the entire rule. Crucially, there is no implicit coercion like
C/Python/JS: 0, "", [], and :ok are all truthy. Coming from Erlang
this is actually more predictable than JS-style truthiness — the falsy set
has exactly two members.
The operators split along this line:
iex> 0 and true # strict operators demand a real boolean ON THE LEFT
** (BadBooleanError) expected a boolean on left-side of "and", got: 0
iex> true and 0 # left side IS a boolean → right side returned as-is
0 # (no check on the right — same as Erlang's andalso)
iex> 0 && :fallback # relaxed operator uses truthiness; 0 is truthy
:fallback
Practical guidance:
- Strict boolean operators
and/or/notrequire the left operand to be a real boolean (raiseBadBooleanErrorotherwise); when the left side istrue/falsethey return the right operand untouched — semantically identical to Erlang’sandalso/orelse. Use them when both sides should be booleans. - Relaxed operators
&&/||/!work on any value via truthiness. Idiomatic Elixir uses them constantly for defaults and guards:get_env("X") || "default". - Pattern matching remains the primary control flow — truthiness is a convenience at the edges, not a replacement for matching on shapes.
1.8 Links and Monitors in Elixir Spelling
Failure-propagation primitives deserve one explicit pass, because the semantics are byte-for-byte Erlang’s while the surface syntax differs:
| Primitive | Direction | Signal | Elixir spelling |
|---|---|---|---|
| Link | bidirectional | an exit kills all linked processes | spawn_link/1 |
| Monitor | unidirectional | {:DOWN, ref, :process, pid, reason} msg | Process.monitor/1 |
# LINK: share fate — the join your supervisors are built from
Process.flag(:trap_exit, true) # without this, the link kills US too
spawn_link(fn -> exit(:disk_full) end)
receive do
{:EXIT, pid, :disk_full} -> {:cleaned_up_after, pid}
end
# MONITOR: observe without sharing fate — one message, then silence
{:ok, worker} = Task.start(fn -> Process.sleep(:infinity) end)
ref = Process.monitor(worker)
Process.exit(worker, :kill)
receive do
{:DOWN, ^ref, :process, ^worker, :killed} -> :observed_the_crash
end
Rules you already know carry over intact: links do not propagate
transitively, monitors stack (one ref each), and
Process.demonitor(ref, [:flush]) clears a pending :DOWN. Supervision
trees are assembled from exactly these two primitives — nothing more, in
either language.
From Erlang you know: because it is one VM, tooling crosses language boundaries freely.
:observer.start()in an IEx session renders Elixir and Erlang applications indistinguishably — Elixir modules simply appear under their atom names (:"Elixir.MyApp.Worker"). Attach it to a mixed cluster and no view tells the languages apart.
Explore More
- Elixir Kernel docs — skim the invariants and guards sections; see how many are annotated as Erlang BIFs
- Compatibility and deprecations — which OTP versions pair with which Elixir releases
- Term ordering reference — the full comparison rules in one page
- ERTS internal docs: processes and reductions — the scheduler loop behind §1.1’s reductions paragraph, from the runtime’s own documentation
- Exercise: in
iex, verify five entries of the §1.6 table usingis_*predicates and&Mod.fun/1captures until the “same terms” claim feels proven, not promised - Exercise:
Process.info(self(), :reductions)before and after a tight loop, and confirm the per-slice figure matches the 4000 default rather than the 2000 that older OTP-era docs quote
Checkpoint
Before Chapter 2, confirm you can answer:
- Which runtime do both languages compile to? (BEAM bytecode on the same VM)
- Name three OTP concepts that transfer without modification.
- Which four layers make up the actual learning curve?
- Why is “nicer Erlang” the wrong framing?
- What are Elixir’s two falsy values, and which operators respect them?
- Name three mindset shifts from §1.2 that are cultural rather than semantic.
Answers
- BEAM bytecode on the same VM.
- Processes and messages, supervision trees, links/monitors, the error kernel (let it crash), reductions and preemption, distribution, term ordering, per-process heaps.
- Language → Tooling → Libraries → Conventions (§1.3).
- Because it implies you must unlearn working instincts (single assignment, mutable-ish idioms) rather than just learn new syntax.
falseandnil.&&/||respect them;and/orraise on them as the left operand.- Macros as a DSL tool;
{:ok, _}/{:error, _}plus!twins as the contract currency; data-first APIs that pipe; docs/specs/tests as the spine of a package.
Next: Chapter 2 — Syntax Translation Guide
Chapter 2 — Syntax Translation Guide
For Erlang developers the biggest perceived barrier is syntax. Reality: the concepts are identical; only keywords and surface forms differ. This chapter is your translation dictionary — read it once, then keep it as a reference.
How to use it: each section pairs a concept table with side-by-side code. The tables are for lookup; the code is for building intuition.
2.1 Code Organization
| Concept | Erlang | Elixir |
|---|---|---|
| File extension | .erl | .ex / .exs |
| Module declaration | -module(name). | defmodule Name do ... end |
| Export functions | -export([fun/arity]). | def fun(args) (public by default) |
| Private functions | Not exported | defp fun(args) |
| Include files | -include("file.hrl"). | Not needed (import/alias) |
| Module attributes | -define(MACRO, value). | @attribute value |
| Comments | % comment | # comment |
Erlang — annotated:
-module(math). % module name = file name = atom
-export([add/2, sub/2]). % opt-in exports; nothing public by default
-define(DEFAULT, 0). % compile-time macro constant
add(A, B) -> A + B.
sub(A, B) -> A - B.
Elixir — same program:
defmodule Math do # CamelCase alias; compiles to atom :"Elixir.Math"
@default 0 # module attribute — inlined at compile time
def default, do: @default
def add(a, b), do: a + b # def = exported (public) by default
def sub(a, b), do: a - b
defp private_fun, do: :ok # defp = private, invisible outside this module
end
Two mental flips worth noting:
- Visibility inverts. Erlang is private-by-default (
-exportopts in); Elixir is public-by-default (defpopts out). Idiomatic Elixir still keeps most functionsdefp— treat public surface as deliberate API design. - Module names are aliases.
MyApp.Utilsis sugar for the atom:"Elixir.MyApp.Utils"; nested naming is convention plus aliasing, covered in §2.2. There are no dotted atoms likemy_app_utils.
.ex vs .exs: .ex compiles to BEAM files on disk (your application);
.exs is script form — evaluated directly, nothing written to disk
(tests, config, Mix files). Like .erl vs running erl -s ... one-offs,
but first-class in tooling.
Attributes vs Macros: What Happens at Compile Time
@attribute succeeds -define, but the mechanics differ in one useful way:
a -define performs textual substitution wherever invoked; an attribute
stores a value (an Elixir term, or quoted code) evaluated once, then
inlined at each reference:
defmodule Config do
@ttl 60 # a plain value — inlined at every use
@routes [:health, :metrics] # lists, maps — any term works
def ttl, do: @ttl # compiles down to the literal 60
def fresh?(now, seen) when now - seen <= @ttl, do: :fresh
def fresh?(_, _), do: :stale # attributes are legal IN GUARDS — by the
end # time guards elaborate, @ttl IS 60
Two power tools ride the same mechanism: accumulate: true collects
repeated attributes into a list, and persist: true writes an attribute into
the .beam metadata — the chunk mechanism that also carries Erlang’s
compile-time attributes.
Be precise about who uses which. accumulate: true is what lets a module
declare @behaviour once and have every clause-defined function contribute
to a single list; the canonical Elixir examples are @before_compile,
@after_compile, and custom DSL registries — Ch 06 §6.4 builds one.
@moduledoc and @doc are a separate mechanism: each clause carries its
own @doc, and both land in the documentation chunk that Chapter 03’s ExDoc
flow consumes. Do not model docs as an accumulating attribute.
2.2 Modules, Imports, Constants
| Concept | Erlang | Elixir |
|---|---|---|
| Define module | -module(name). | defmodule Name do ... end |
| Alias long name | Manual | alias MyApp.LongModule, as: Short |
| Import functions | Not built-in | import Module, only: [fun: arity] |
| Require macros | -include_lib(...) | require Module |
| Compile-time constant | -define(PI, 3.14). | @pi 3.14 |
Four distinct tools replace Erlang’s single include mechanism:
- alias — rename a module for qualified calls:
alias MyApp.Long.Modulelets you writeModule.run/1. Zero runtime effect; pure naming. - import — bring functions into local scope so they’re called unqualified.
Restrict with
only:/except:to keep provenance readable. - require — makes a module’s macros available (macros must be required before use — the compiler needs to expand them).
- @attribute — compile-time constants and annotations, the
-definesuccessor (plus metadata roles like@doc,@spec,@impl).
Side-by-side retry utility:
defmodule MyApp.Utils do
@max_retries 3 # inlined wherever referenced — same
# expansion semantics as -define
def retry(_fun, 0), do: {:error, :max_retries} # clause 1: base case
# (pattern on arg count!)
def retry(fun, n) do # clause 2: recursive case
case fun.() do # note: anonymous fns call
:ok -> :ok # with .()
_ -> retry(fun, n - 1)
end
end
end
The Erlang twin you’d write (retry(F, N) -> case F() of ... end,
clauses and all) has an identical recursion shape: pattern-matching-on-
clauses, first clause the base case. Differences are punctuation: no
terminating dot, clauses separated implicitly by newline, fun.() instead of
(Fun)().
From Erlang you know: module attributes compile to the same constants mechanism as
-define.@max_retries 3is inlined at expansion time.
2.3 Records → Structs
Structs are maps with a compile-time-checked __struct__ field. They replace
records with better pattern matching, enforced keys, and protocol dispatch
(Ch 05):
| Concept | Erlang (Records) | Elixir (Structs) |
|---|---|---|
| Definition | -record(user, {name, age}). | defstruct [:name, :age] inside a module |
| Creation | #user{name = "Alice"} | %User{name: "Alice"} |
| Access | User#user.name | user.name |
| Update | User#user{age = 31} | %{user | age: 31} |
| Pattern match | #user{name = Name} = R | %User{name: name} = user |
| Defaults | -record(user, {name = "", age = 0}) | defstruct name: "", age: 0 |
| Required keys | No | Yes (@enforce_keys) |
defmodule User do
@enforce_keys [:id] # compile error if :id missing at construction
defstruct [:id, name: "", age: 0]
end
# Multi-clause accessors read exactly like record guards:
def get_name(%User{name: name}), do: name
def update_age(%User{} = user, new_age) do
%{user | age: new_age} # update syntax: raises if key doesn't exist
end
Three upgrades over records to appreciate:
- One struct per module — the module becomes home to related functions (constructors, domain logic), not just data.
@enforce_keysturns “forgot to set the field” into a compile-time crash instead of a runtimeundefined.- Structs participate in protocols (§5.2) and get pretty inspection for free.
Structs Under the Hood: Just a Tagged Map
A struct is literally a map carrying a __struct__ key — no new VM type,
which is why records-as-tuples never needed special VM support either:
iex> user = %User{id: 1, name: "Ada"}
iex> user.__struct__
User
iex> is_map(user) && is_struct(user)
true
iex> %{name: name} = user # a plain-map pattern MATCHES a struct…
"Ada"
That last line is the standing footgun: %{} matches any struct, so a
loose map pattern silently accepts foreign types. Match %User{} (pins the
type, not just fields) or guard with is_struct/2 when the type matters.
Conversely, Map and Access functions treat structs as plain maps —
handy for bulk work, risky when invariants matter (see §5.4).
2.4 Control Flow & Functions
Anonymous functions use fn instead of fun; clauses separate with newlines
instead of ;; no terminating dot. Everything below is iex-runnable:
# Anonymous function with multiple clauses — matches like any function head:
fun = fn
{:ok, value} -> value
{:error, reason} -> raise reason
end
fun.({:ok, 42}) #=> 42 # NOTE the .() call syntax for anonymous fns
# case — like Erlang's but semicolon-free; each arrow-clause on its own line
case File.read("config.txt") do
{:ok, body} -> body
{:error, :enoent} -> "default"
end
# try/catch/after — note the extra rescue arm for exceptions (Elixir adds
# structured exceptions ON TOP of Erlang's throw/exit/error classes):
try do
raise "oops"
rescue
e in RuntimeError -> "handled: #{e.message}" # exceptions → rescue
catch
:exit, reason -> handle_exit(reason) # exits → catch (as in Erlang)
after
:cleanup # always runs
end
Error Classes: throw, exit, raise Map Cleanly
Elixir keeps all three Erlang error classes and adds a friendlier front
door for the error class. Full mapping:
| Erlang construct | Class | Elixir home |
|---|---|---|
throw(Term) | :throw | throw(term) + catch arm |
exit(Reason) | :exit | exit(reason) + catch :exit, r -> |
erlang:error(R), badmatch, … | :error | raise + rescue arm |
rescue is sugar over catch :error that unwraps exception structs; the
plain catch clause still speaks raw classes, so interop code translates
verbatim:
try do
throw(:thrown_value)
catch
thrown -> {:caught_throw, thrown} # :throw class: single payload
end
#=> {:caught_throw, :thrown_value}
try do
exit(:shutdown_requested)
catch
:exit, reason -> {:caught_exit, reason}
end
#=> {:caught_exit, :shutdown_requested}
try do
raise ArgumentError, message: "bad input"
rescue
e in ArgumentError -> {:caught_error, e.message}
end
#=> {:caught_error, "bad input"}
Style rule: raise/rescue for your own APIs (structured, pattern-
matchable); reserve throw for non-local early returns inside library
macros (Plug uses it internally); exit stays what it always was — a
process-shutdown signal.
if is a macro built on case, with an optional else block.
Kernel.unless/2 was soft-deprecated in 1.18 — it still compiles with no
warning, and mix format --migrate rewrites it to if not ... — but the style
guide discourages it: unless reads as “if not”, and unless ... else is
actively confusing because the else branch is the “positive” case. Prefer
if not ... or an explicit case.
with: Chain Fallible Steps Without Nesting
The idiomatic answer to Erlang’s most common nesting pattern — a staircase
of cases threading {:ok, _} through several steps:
%% Erlang: each step nests one level deeper
load(Path) ->
case file:read_file(Path) of
{ok, Body} ->
case string:to_integer(string:trim(Body)) of
{Int, []} when Int > 0 -> {ok, Int};
_ -> {error, not_an_integer}
end;
{error, Reason} -> {error, Reason}
end.
defmodule ConfigLoader do
# each <- step runs, then pattern-matches its result;
# ANY mismatch drops straight to the else block
def load(path) do
with {:ok, body} <- File.read(path),
{int, ""} <- Integer.parse(String.trim(body)),
true <- int > 0 do
{:ok, int}
else
:error -> {:error, :not_an_integer} # Integer.parse miss
false -> {:error, :must_be_positive}
{:error, reason} -> {:error, reason} # File.read failure
end
end
end
iex> ConfigLoader.load("missing.txt")
{:error, :enoent}
iex> ConfigLoader.load("/tmp/ttl.txt") # containing "-5\n"
{:error, :must_be_positive}
Reading rules worth internalizing:
pattern <- exprrunsexprand matches the result againstpattern. A match binds and continues; a mismatch short-circuits intoelsecarrying the unmatched value (not an error).- Plain
exprlines (no<-) execute for effect or assert via=— a failed assert raisesMatchError, which is correct for programmer errors. - Without an
elseblock, a falling-through value is returned as-is — convenient when every step already speaks{:error, _}. elsearms are ordinarycaseclauses: order matters, guard them freely, and a final catch-all arm keeps unexpected failures visible instead of silently re-wrapped.
When to reach for which: one fallible call → case. Two or more steps
whose failures share handling → with. And resist the urge to route
control flow through with when there is nothing fallible — plain function
composition still reads best.
Capture Syntax — Read It Before You Need It
You will meet & everywhere in Elixir. Two forms, one idea — reference a
function without calling it:
&(&1 + 1) # anonymous capture: fn x -> x + 1 end
# &1, &2… are positional args
&is_atom/1 # named capture: the existing function is_atom/1
# module-qualified, arity explicit
Enum.filter([1, :a, 2, :b], &is_atom/1) #=> [:a, :b]
Enum.map([1, 2], &(&1 * 10)) #=> [10, 20]
This replaces Erlang’s fun X -> X * 10 end and fun lists:max/1-style
references. When you see &Mod.fun/arity in a pipe chain, mentally read
“pass that function itself along.”
One restriction: & captures functions only, never macros. Integer.is_even/1
is a defguard macro, so &Integer.is_even/1 compiles but raises
function Integer.is_even/1 is undefined or private the moment it is invoked
(shadowing the guard with a same-named function) — and calling it unqualified
needs require Integer first. Use an anonymous capture or a named fn when
the predicate is a guard:
Enum.filter(1..6, &(rem(&1, 2) == 0)) #=> [2, 4, 6]
require Integer
Enum.filter(1..6, fn n -> Integer.is_even(n) end) #=> [2, 4, 6]
Captured Functions with Bound Args
Documentation and discussions often say “a captured function with bound args.” The idea: take a function, pre-fill some arguments, and hand back a function needing only the rest. Four related but distinct concepts hide behind that phrase — learn to tell them apart:
| Concept | Example | What’s captured/bound? |
|---|---|---|
| Function capture | &String.upcase/1 | The function itself, no args |
| Closure | fn x -> x + n end | Variable n from outer scope |
| Partial application | fn x -> add.(10, x) end | Argument 10 |
| Capture with placeholder | &(&1 + 10) | 10 fixed; &1 still variable |
1. Plain capture — the function itself, nothing bound. &String.upcase/1
references the existing function without calling it:
iex> fun = &String.upcase/1
iex> fun.("hello")
"HELLO"
2. Closure — variables from the enclosing scope are baked in. Like an
Erlang fun, an Elixir fn captures surrounding bindings, and since
nothing rebinds, the capture is a frozen snapshot:
prefix = "Hello"
greet = fn name -> "#{prefix}, #{name}!" end # prefix is bound in HERE
greet.("Manh") #=> "Hello, Manh!"
threshold = 10
over? = fn x -> x > threshold end # threshold is baked in HERE
threshold = 999 # rebinds the outer name only
over?.(50) #=> true — still comparing against 10!
# (a live binding would give false)
The Erlang equivalents (Greet = fun(Name) -> ... end closing over
Prefix, Over = fun(X) -> X > Threshold end) behave identically, so this
is confirmation rather than news — but it explains why “stale closure” bugs
from mutable languages simply cannot happen here.
3. Partial application — bind arguments, not just variables. Fix the leading argument(s) of a function and keep the tail open:
add = fn a, b -> a + b end
add_10 = fn b -> add.(10, b) end # 10 is bound; b remains free
add_10.(5) #=> 15
The capture operator makes this one line — bound args written literally,
&1 standing for the argument still to come:
add = &Kernel.+/2
add_10 = &add.(10, &1) # read: "call add with 10 and my arg"
add_10.(5) #=> 15
You will meet this constantly with Enum callbacks — the surrounding value
rides along inside the function value:
factor = 10
Enum.map([1, 2, 3], fn x -> x * factor end) #=> [10, 20, 30]
# equivalently, with the factor bound via the placeholder form:
Enum.map([1, 2, 3], &(&1 * 10)) #=> [10, 20, 30]
4. Placeholder capture — partial application’s inline sugar. &(&1 + 10)
is a function whose 10 was fixed at creation; &1 remains variable. The
distinction to hold onto: in &(&1 + n) the current value of n is
captured (a closure over n), whereas in &(&1 + 10) the literal is simply
part of the expression — there is nothing to go stale.
From Erlang you know: all four ideas already exist in Erlang —
fun lists:max/1(capture),fun(X) -> X > Threshold end(closure),fun(B) -> Add(10, B) end(partial application). Elixir adds only the&shorthand with&1, &2…placeholders, which turns the partial-application pattern from a hand-written wrapper into a one-liner.
Reading &(...) — Placeholders, Arity, and Bound Values
The placeholder form confuses everyone on first sight. The trick is to
separate the two & roles hiding in &(&1 + &2):
- the outer
&says: “turn this expression into a function” &1,&2,&3are the arguments that function will receive
So &(&1 + &2) reads: “make a function whose body is first arg + second
arg” — exactly fn a, b -> a + b end:
iex> add = &(&1 + &2)
iex> add.(10, 20)
30
Two gotchas to internalize early. First, &1/&2 are not variables —
they are syntactic slots that exist only inside the &(...) expression, so
add.(&1, &2) is a compile error. Second, the highest placeholder number
is the arity:
iex> double = &(&1 * 2) # one placeholder → arity 1
iex> double.(10)
20
iex> triple = &{&1, &2, &3} # three placeholders → arity 3
iex> triple.(10, 20, 30)
{10, 20, 30}
So &(&1 + &2 + &3) compiles to fn a, b, c -> a + b + c end, and calling
it with two arguments raises BadArityError — same as calling any Erlang fun
with the wrong count.
Parentheses define the body clearly. & &1 + &2 happens to parse as
&(&1 + &2) (capture binds tighter than +), but & grabs a single
expression, and with mixed operators or nested calls the unparenthesized
form gets hard to read — and ambiguous to the parser in argument lists. Wrap
the body: &(&1 + &2). mix format enforces this for you.
The comparison worth memorizing — two ways to get the same function:
add = &(&1 + &2) # build a new anonymous function...
add = &Kernel.+/2 # ...or capture the EXISTING Kernel.+/2
add.(10, 20) #=> 30 either way
&Kernel.+/2 says “give me the function + with arity 2” — the /2 is the
arity suffix, the same notation as String.upcase/1 in docs. The placeholder
form builds the function fresh; the /arity form references one that already
exists.
Where this pays off daily — Enum callbacks and sorters:
iex> Enum.map([1, 2, 3, 4], &(&1 * 2)) #=> [2, 4, 6, 8]
iex> users = [%{name: "Bob", age: 30}, %{name: "Alice", age: 20}]
iex> Enum.sort_by(users, &(&1.age)) # fn u -> u.age end
[%{name: "Alice", age: 20}, %{name: "Bob", age: 30}]
And the tie back to the previous section: placeholders are the dynamic slots; anything else in the body is a bound value:
x = 10
fun = &(&1 + x) # &1 dynamic, x bound (a closure over the current value)
fun.(5) #=> 15
So &(&1 + &2) has two dynamic arguments, while &(&1 + x) has one dynamic
argument plus one bound value. The mental model: read &(...) as “make this
expression into a function,” then translate each &n to “the n-th argument.”
&(&1 * 2) → fn x -> x * 2 end. & &1.name → fn x -> x.name end. Once
that translation is automatic, the syntax stops being mysterious — it is
Elixir’s compact lambda notation.
Guards (when) — Same Idea, Richer Library
Guards work exactly like Erlang’s, joined by and/or (strict boolean) or
the relaxed &&/||. Kernel auto-imports ~40 guard-safe functions:
type checks (is_integer/1, is_binary/1, is_struct/1…), size checks
(byte_size/1, tuple_size/1, map_size/1, length/1), arithmetic
(div/2, rem/2, abs/1, round/1…), plus hd/1, tl/1, elem/2,
self(), node():
def drive(%User{age: age}) when age >= 16 do
:allowed
end
def classify(term) when is_binary(term), do: :text
def classify(term) when is_integer(term) and term > 0, do: :positive
You can compose your own guard-safe helpers with defguard — reusable guard
fragments that expand inline (so they stay guard-legal):
defmodule MyGuards do
defguard is_adult(age) when is_integer(age) and age >= 18
end
defmodule Voter do
import MyGuards
def check(age) when is_adult(age), do: {:ok, :vote}
def check(_age), do: {:error, :too_young}
end
Numbers: / Is Always Float Division
A classic stumble even for Erlang devs who assumed parity. Kernel docs are
explicit: / returns a float; integer division needs div/2, remainder
rem/2; power is **; both divisions by zero raise ArithmeticError:
iex> 5 / 2 #=> 2.5
iex> 5 / 1 #=> 5.0 ← always float, even when evenly divisible!
iex> div(5, 2) #=> 2
iex> rem(5, 2) #=> 1
iex> 2 ** 10 #=> 1024
iex> round(3.6) #=> 4 (Kernel — returns an integer)
iex> trunc(3.6) #=> 3
iex> Float.floor(3.6) #=> 3.0 (Float module — returns a float)
iex> Float.ceil(3.6) #=> 4.0
Equality: == vs ===
Same distinction as Erlang’s == vs =:= family, different symbols:
iex> 1 == 1.0 #=> true (numeric comparison across int/float)
iex> 1 === 1.0 #=> false (strict match comparison)
iex> 1 !== 1.0 #=> true
Translation line: map Erlang = (match) → Elixir =; map ==/!= →
same symbols; map =:=/=/= (exact) → ===/!==.
Pinning: Everywhere a Pattern Appears
^var reappears beyond the §2.7 gotcha — it is legal in every pattern
position where the name is in scope: case, receive, fn heads, for
generators, and nested matches:
expected = {:ok, :ready}
poll = fn -> {:ok, :ready} end
case poll.() do
^expected -> :unchanged # match AGAINST the earlier binding
other -> {:drifted, other}
end
listener = fn # pins close over the binding captured
^expected -> :exact # when the fn was created
_ -> :drifted
end
One asymmetry worth naming: pinning makes no sense in def heads — module-
level functions have no enclosing lexical scope to pin against. Erlang’s
f(X) when X =:= Expected muscle memory maps to guards over module
attributes (§2.1), not to ^.
Sigils — Literals With a Twist
Sigils build common literals concisely (all runnable):
iex> ~c"hello" # charlist — what Erlang calls "string"
~c"hello"
iex> ~s"hello #{1 + 1}" # string with interpolation
"hello 2"
iex> ~S"#{no_interp}" # raw string, no interpolation/escapes
"\#{no_interp}"
iex> ~w(a b c) # word list — splits on whitespace
["a", "b", "c"]
iex> ~r/\d+/ # Regex struct
~r/\d+/
iex> ~U[2026-08-25 12:00:00Z] |> DateTime.to_date()
~D[2026-08-25]
Mnemonic: lowercase sigils interpolate and process escapes (~s, ~c);
uppercase versions are raw (~S, ~C). Delimiters are interchangeable:
~w(...) ≡ ~w[...] ≡ ~w|...| — pick per readability.
Date/time sigils build calendar structs directly — no parsing, no stringly-typed dates:
iex> ~D[2026-08-25] # Date struct
~D[2026-08-25]
iex> ~T[09:41:00.123] # Time (microsecond precision)
~T[09:41:00.123]
iex> ~N[2026-08-25 09:41:00] # NaiveDateTime — no timezone attached
~N[2026-08-25 09:41:00]
iex> ~U[2026-08-25 09:41:00Z] # DateTime — UTC enforced at build time
~U[2026-08-25 09:41:00Z]
iex> ~w(read write)a # ~w takes a modifier for the element type
[:read, :write]
iex> ~w(1 2)s # s → strings (default); c → charlists; a → atoms
["1", "2"]
Interpolation vs io_lib:format
#{} inside strings calls to_string/1, which dispatches through the
String.Chars protocol (§5.2) — atoms, numbers, binaries and structs with an
implementation pass through; anything else raises:
iex> "n=#{40 + 2}"
"n=42"
iex> "#{:ok}" # atoms implement String.Chars
"ok"
iex> inspect({:ok, 1}) # inspect/1 handles ANY term
"{:ok, 1}"
For printf-style control, the Erlang machinery remains one atom away — format string in, iodata out:
iex> :io_lib.format("~s: ~.2f kg", ["cargo", 12.5]) |> IO.iodata_to_binary()
"cargo: 12.50 kg"
Rule of thumb: interpolation for gluing known-good values; inspect/1 when
debugging arbitrary terms; :io_lib.format when you need widths, precision,
or compatibility with APIs expecting format strings.
2.5 The Pipe Operator
The single most visible ergonomic change. Instead of nesting inside-out — where you read the last operation first:
Result = lists:sum( %% ③ outermost = LAST step
lists:map(fun(X) -> X * 2 end, %% ② middle
lists:filter(fun(X) -> X > 5 end,
lists:seq(1, 10)))). %% ① innermost = FIRST
You thread left-to-right, top-to-bottom, passing each result as the first argument of the next call:
flowchart LR
R["1..10<br/>(range)"] -->|"filter &(&1 > 5)"| A["[6, 7, 8, 9, 10]"]
A -->|"map &(&1 * 2)"| B["[12, 14, 16, 18, 20]"]
B -->|"sum()"| C["80"]
result =
1..10
|> Enum.filter(&(&1 > 5))
|> Enum.map(&(&1 * 2))
|> Enum.sum()
#=> 80
Mechanics worth internalizing once: x |> f(y) rewrites to f(x, y). That
works because Enum functions deliberately take the collection first —
argument order across the stdlib is designed for piping. Same semantics as
threading through staged variables in Erlang, but readable top to bottom.
You will see pipes everywhere; they are the ecosystem’s house style.
2.6 Quick Reference: Keyword Mapping
| Erlang | Elixir | Notes |
|---|---|---|
module | defmodule | |
export | public by default | Use defp for private |
import / include | import / alias / require | More granular, no headers |
define | @attribute | Module attributes |
if / case / receive | if / case / receive | Similar |
fun(X) -> ... end | fn x -> ... end | |
begin / end | do / end | |
; clause separator | none | Clauses separated by pattern |
. terminator | none | Line-based |
= match | = match | Same operator, same semantics |
record | defstruct | Structs are checked maps |
try/catch/after | try/rescue/catch/after | rescue for exceptions |
atoms 'my_atom' | :my_atom | Same runtime representation |
"string" (list of ints) | "string" (UTF-8 binary!) | See gotchas below |
2.7 Gotchas Specific to Erlang Developers
Each gotcha below has bitten every migrating Erlang dev at least once — better here than in production.
1. Strings are binaries by default.
This is THE gotcha. The word "string" means opposite things:
flowchart TD
Q{"double or single quotes?"}
Q -->|"#quot;abc#quot;"| BIN["UTF-8 BINARY<br/><<97, 98, 99>><br/>Elixir's default #quot;string#quot;<br/>≈ Erlang <<#quot;abc#quot;>>"]
Q -->|"'abc' (deprecated) or ~c#quot;abc#quot;"| CL["CHARLIST<br/>[97, 98, 99]<br/>list of codepoints<br/>≈ Erlang #quot;abc#quot;"]
iex> byte_size("abc") # binary: size in bytes
3
iex> "abc" == <<"abc">>
true
iex> ~c"abc" ++ ~c"d" # charlist: plain list ops work
~c"abcd"
Charlists exist mainly for Erlang interop (some OTP APIs want them) — reach
for ~c"" when you need them explicitly. Bare single-quoted literals like
'abc' still work, but Elixir emits a deprecation warning for them; write
~c"..." in new code and run mix format --migrate to convert an existing
codebase.
1b. Binaries are bit-precise, and mostly unchanged. If you parse
protocols, write codecs, or read binary_to_term payloads, this is the one
Elixir syntax that is nearly identical to Erlang — worth confirming rather
than relearning. Only the spellings change:
%% Erlang
<<Len:16/big-unsigned-integer, Rest/binary>> = Frame,
<<X:32/little-float>> = Body,
Bits = <<1:3, Rest2/bitstring>>.
# Elixir — same bytes, different punctuation
<<len::16, rest::binary>> = frame
<<x::little-float-32>> = body
<<1::size(3), rest2::bitstring>> = bits
Translation table for the parts you will actually type:
| Erlang | Elixir | Note |
|---|---|---|
T:8/integer-unsigned-big | T::8 | default is unsigned, big-endian |
T:16/little-unsigned-integer | T::little-unsigned-16 | endianness is a type |
T:32/float | T::float-32 | maps onto IEEE-754 single |
T:Len/binary | T::binary-size(len) | size driven by a pattern var |
T/utf8 | T::utf8 | unchanged; validated on match |
Rest/bitstring | Rest::bitstring | binary = byte-aligned, bitstring = not |
<<X:3, _:5>> = Bin | <<x::size(3), _::size(5)>> = bin | size() replaces N |
Two Elixir-specific hazards, both covered in depth in Ch 25:
- Size must be pinned.
<<x::size(n)>>in a pattern is deprecated as of Elixir 1.20 — write<<x::size(^n)>>. In a construction a barenis fine. binarymeans byte-aligned.<<1::3>>has a 3-bit tail, so matching it against::binaryfails. Pick::bitstringwhen the tail is not a whole byte.
Slicing has the same shape on both sides: binary_part(Bin, Pos, Len) →
binary_part/3 unchanged, or binary_slice(Bin, Pos, Len), or pattern-matched
slices via <<_::binary-size(pos), rest::binary>> = bin.
2. No semicolons or dots. Commas separate arguments; newlines separate expressions within blocks. Clause sequences are just consecutive heads.
3. Parentheses are optional — but keep them. Elixir lets you drop parens
on named calls (add 1, 2 parses fine) and on many zero-arity reads
(Node.self). House style — and mix format — keeps them (add(1, 2)),
because ambiguous-looking calls without parens trigger compiler warnings.
Coming from Erlang where parens are mandatory, the discipline transfers
unchanged: just write them.
4. Module names are CamelCase aliases, resolved at compile time. And the
escape hatch always works: :gen_server.start_link(...) — full Erlang
interop is direct, atoms-and-all.
5. = is always a match operator — and Elixir allows rebinding. This is
the single most important difference from Erlang, and it is why pinning
exists:
%% Erlang: one variable, one binding. The second assignment is badmatch.
X = 1,
X = 2. %% ** exception error: badmatch
iex> x = 1
1
iex> x = 2 # rebinds: no warning, no error
2
Inside a pattern, a bare variable still rebinds rather than comparing. So
%{status: expected, code: actual} will happily bind expected = :error
even if a variable named expected was already bound. To compare against an
existing value you must pin it:
iex> expected = :ok
iex> case result do
...> ^expected -> :matched # ^ pins: match AGAINST the bound value
...> _ -> :other # without ^, expected would REBIND
...> end
Erlang developers rarely need this because rebinding is impossible there; Elixir code that wants a comparison must say so explicitly. Ch 25 unpacks the full rule set, and Ch 30’s pitfall table calls this out as the #1 reflex to unlearn.
6. Keyword lists vs maps. Two key-value structures with different rules — choose by properties, not habit:
flowchart TD
Q{"what do you need?"} --> O["ordered · duplicate keys allowed<br/>keys are atoms · optional-arg style"] --> KL["KEYWORD LIST<br/>[a: 1, a: 2, b: 3]<br/>Keyword module"]
Q --> M["unique keys · arbitrary key terms<br/>fast lookup · pattern-matchable"] --> MAP["MAP<br/>%{a => 1} or %{a: 1}<br/>Map module"]
iex> [a: 1, a: 2, b: 3] # keyword list: duplicates fine — options rely on this
[a: 1, a: 2, b: 3]
iex> %{a: 1} == [{:a, 1}] # map ≠ keyword list — different types!
false
iex> Keyword.get([a: 1, b: 2], :a)
1
Options arguments (def f(opts \\ [])) are keyword lists by ecosystem
convention; anything needing pattern matching or uniqueness is a map.
7. / returns floats; div/rem for integers (§2.4).
8. Structural comparison everywhere. <, >, min/max compare raw
terms using the BEAM term order (Ch 01 §1.6) — so "b" < :atom is false
(bitstrings sort after everything) and sorting mixed types follows VM rules,
not domain rules. For domain-aware ordering, types ship semantic
comparators — e.g. Date.compare/2, Enum.sort(dates, Date).
9. Charlist or binary? Decide at the API boundary.
Both represent text; the choice falls out of who consumes it:
iex> "ab" <> "cd" # binaries concatenate with <>
"abcd"
iex> ~c"ab" ++ ~c"cd" # charlists concatenate with ++
'abcd'
iex> String.codepoints("héllo") # the String module = UTF-8 binaries
["h", "é", "l", "l", "o"]
Default to binaries — the whole Elixir ecosystem (Phoenix, Ecto, String)
speaks UTF-8 binaries. Reach for charlists only where OTP demands them:
some :code, :file, and port-facing APIs predate binaries, and older
Erlang libraries may hand you one back. Use ~c"..." literals or
to_charlist/1 at the boundary and convert immediately; inside your own
modules, one representation — binaries — wins.
Kernel Is the Default Environment
Everything above lives in the Kernel module — Elixir’s default environment.
Its functions and macros are auto-imported: you never write
Kernel.if/2. Two consequences worth knowing:
# Don't like a built-in? Exclude it per module:
import Kernel, except: [if: 2]
# Special forms (defmodule, def, fn, quote, case, =, ::, <<>>, alias,
# import, require...) live in Kernel.SpecialForms: always imported,
# can NEVER be excluded or overridden — they *are* the language.
The rest of the standard library builds outward in groups (per the Kernel
docs): built-in type modules (Atom, Map, List, Process…),
derived data types (Date, Keyword, Range, MapSet, Regex…),
system modules (IO, File, Path, System), protocols
(Enumerable, Inspect, String.Chars…) and process abstractions
(Agent, Task, GenServer, Supervisor, Registry). Chapter 5 covers
that last group.
2.8 A Complete Translation, End to End
Pull the dictionary together with one bounded stack. First in Erlang:
-module(stack).
-export([new/0, push/2, pop/1]).
new() -> [].
push(Stack, Item) -> [Item | Stack].
pop([]) -> {error, empty};
pop([Top | Rest]) -> {ok, Top, Rest}.
Same program in Elixir — notice every line pairing with its neighbor:
defmodule Stack do
def new, do: []
def push(stack, item), do: [item | stack]
def pop([]), do: {:error, :empty}
def pop([top | rest]), do: {:ok, top, rest}
end
iex> s = Stack.push(Stack.push(Stack.new(), 1), 2)
[2, 1]
iex> {:ok, value, _rest} = Stack.pop(s)
{:ok, 2, [1]}
iex> value
2
iex> Stack.pop([])
{:error, :empty}
Note the deliberate argument order: push takes its data first, so the
pipe works naturally — Stack.new() |> Stack.push(1) |> Stack.push(2) builds
the same [2, 1]. That first-argument convention behind |> (§2.5) is an
Enum-family design choice, not a language rule — but adopting it makes your
own APIs pipe-able for free.
Hold onto this pairing habit: read Elixir, mentally render the Erlang, spot-check against the compiler. Within a week the middle step goes silent and you are simply reading code.
Explore More
- Kernel docs — read once end-to-end; it IS the language surface
- Syntax reference — the complete grammar in one page
- Sigils guide — every sigil explained with examples
- Erlang Efficiency Guide: functions
— inlining, BIFs, and list comprehensions; explains the
&Kernel.is_atom/1 → & :erlang.is_atom/1result you can observe in §2.7 - Exercise: take a real
.erlmodule from your codebase and translate it using only §2.6’s table — then run both and diff behaviors (they should be identical modulo the gotchas above) - Exercise: write the same binary parser twice — once Erlang-flavoured, once using §2.7’s Elixir translation table — and confirm both produce identical bytes for an IP header with unusual IHL and total-length fields
Checkpoint
- Translate
-record(state, {pid, count = 0}).plus one accessor into Elixir. - Rewrite a three-deep nested
lists:chain using pipes. - What does
"abc"evaluate to at the BEAM level? And~c"abc"? - How do you call
lists:max/1from Elixir? - What does
10 / 4return? And how do you get2instead? - Which two values are falsy, and which operator would raise on them as
left-hand side:
&&orand? - In a
withclause, what happens when a<-pattern does not match the step’s return value? - Is
&(&1 * factor)a closure, a partial application, or both? What does it capture, and what happens to the resulting function iffactoris rebound afterwards?
Answers
defmodule State do @enforce_keys [:pid] defstruct [:pid, count: 0] end; accessor:def get_count(%State{count: c}), do: c.1..10 |> Enum.filter(&(&1 > 5)) |> Enum.map(&(&1 * 2)) |> Enum.sum()"abc"is a UTF-8 binary (<<97, 98, 99>>);~c"abc"is a charlist ([97, 98, 99]) — what Erlang calls a string. (Bare'abc'works but warns; use the~csigil.):lists.max(list)— any Erlang module is callable as:module.fun(args).10 / 4returns2.5;/always returns floats (raises on zero). Integer division:div(10, 4)→2.falseandnil. The strict operatorandraisesBadBooleanErrorgiven a non-boolean;&&accepts any truthy/falsy value.- Execution short-circuits into the
elseblock with the unmatched value (or returns that value unchanged if there is noelse). Matched steps bind and continue down the chain. - Both. It is a partial application whose multiplier comes from a closure
over
factor: the current binding is captured at creation, so rebindingfactorafterwards changes nothing — the function keeps multiplying by the old value (frozen snapshot, like an Erlangfunclosing over a variable).
Next: Chapter 3 — Tooling: From rebar3 to Mix
Chapter 3 — Tooling: From rebar3 to Mix
Mix is to Elixir what rebar3 is to Erlang — plus package management (Hex), documentation (ExDoc), formatting, and releases, all built in. This chapter gets you productive in one sitting; Chapter 09 goes deep on releases and running OTP apps.
From Erlang you know: the rebar3 → Mix mapping is nearly one-to-one, and the mental model transfers —
project/0≈rebar.config,aliases≈ provider hooks,lib/mix/tasks/≈ plugins,_build/<env>≈ rebar3’s profile directories. Two things are genuinely new: Hex (a package registry, sorebar3’s “fetch from git or nothing” is over), and tasks as first-class modules you can read. That second one is why Elixir tooling is legible in a way~/.config/rebar3/rebar.configrarely is.
3.1 Command Map
| Task | rebar3 | Mix |
|---|---|---|
| New project | rebar3 new app name | mix new name |
| New OTP app w/ supervision | rebar3 new app name + boilerplate | mix new name --sup |
| Fetch deps | (automatic on compile) | mix deps.get |
| Compile | rebar3 compile | mix compile |
| Run tests | rebar3 eunit / ct | mix test |
| Shell | rebar3 shell | iex -S mix |
| Format code | (plugin) | mix format |
| Docs | (edoc plugin) | mix docs (ex_doc) |
| Release | rebar3 release | mix release |
| Run tasks | rebar3 <plugin-task> | mix <task> |
The pattern to notice: tasks that need plugins under rebar3 (formatting, docs) ship with Mix. Fewer decisions per project, more uniform codebases.
3.2 Your First Project, Step by Step
mix new hello --sup
cd hello
The --sup flag generates the application callback + root supervisor for
you — no boilerplate copying from your last project.
Layout comparison:
hello/
├── lib/ ← like Erlang src/, but the app entry lives here too
│ ├── hello/
│ │ └── application.ex ← the {mod, {Mod, []}} + {applications, [...]} of .app.src, as a module
│ └── hello.ex ← a default module
├── test/ ← ExUnit tests (.exs)
│ └── hello_test.exs
├── mix.exs ← like rebar.config + .app.src combined
├── mix.lock ← locked dep versions (created on first deps.get; commit it!)
└── .formatter.exs ← formatter config
The two files that matter
lib/hello/application.ex — this is your OTP application callback.
Read it with your application:start/2 knowledge:
defmodule Hello.Application do
use Application # injects behaviour + defaults (Ch 05)
@impl true
def start(_type, _args) do
children = [
# Hello.Worker ← your GenServers go here — plain child specs,
# same {M, f, a} shape you know from supervisor docs
]
Supervisor.start_link(children, strategy: :one_for_one, name: Hello.Supervisor)
end
end
The .app file is generated, not written by you. After mix compile,
_build/dev/lib/hello/ebin/hello.app contains:
{application,hello,[
{modules,['Elixir.Hello']},
{optional_applications,[]},
{applications,[kernel,stdlib,elixir,logger]},
{description,"hello"},
{registered,[]},
{vsn,"0.1.0"},
{mod,{'Elixir.Hello.Application',[]}}
]}.
Two observations for an Erlang reader. First, same keys and semantics as the
.app.src you hand-wrote — {mod, ...} is present only because
mix.exs declared it. Second, applications is computed: it lists elixir
because every Elixir app depends on it, plus whatever extra_applications and
your deps contribute. There is no src/ directory, and no .app.src to keep
in sync. Ch 08 §8.1 walks the rest of the build tree.
That generates exactly this supervision tree:
flowchart TD
APP["hello app<br/>(mod callback in mix.exs)"] --> SUP["Hello.Supervisor<br/>one_for_one"]
SUP --> W1["Hello.Worker<br/>(your GenServers)"]
SUP --> W2["…more children"]
From Erlang you know: same supervision tree you’d write with
supervisor:start_link. The child spec list replaces the.appmodboilerplate; strategies are identical (:one_for_one,:rest_for_one,:one_for_all). Thename:option registers a local alias so you can address the supervisor by atom instead of pid — handy in Observer and RPC.
mix.exs — project metadata, deps, and compiler config in one place.
Three functions matter:
defmodule Hello.MixProject do
use Mix.Project
def project do
[
app: :hello, # the OTP application name
version: "0.1.0",
elixir: "~> 1.15", # minimum Elixir requirement
start_permanent: Mix.env() == :prod, # prod: VM dies if app dies
deps: deps()
]
end
def application do # ← the .app.src equivalent
[extra_applications: [:logger], mod: {Hello.Application, []}]
# ↑ mod: names your callback module
end
defp deps do
[{:jason, "~> 1.4"}] # Hex packages; git/path also work
end
end
The mapping to rebar3 concepts is direct: project/0 ≈ build config,
application/0 ≈ .app.src (mod, extra_applications), deps/0 ≈
{deps, [...]} — except versions resolve from Hex with a lockfile.
Environments Play the Role of Profiles
rebar3 selects dependency sets and options through profiles (default,
test, prod); Mix reaches the same place with environments plus the
only: / runtime: dependency options:
| rebar3 | Mix | Notes |
|---|---|---|
rebar3 as prod release | MIX_ENV=prod mix release | env-scoped _build subdir |
| profile-gated dep | only: [:dev, :test] | never compiled into prod |
| — (no analogue needed) | runtime: false | compiled, but not started |
defp deps do
[
{:jason, "~> 1.4"},
{:credo, "~> 1.7", only: [:dev, :test]},
{:ex_doc, "~> 0.34", only: :dev, runtime: false}
]
end
mix.lock plays rebar.lock: commit it, review its diffs.
Daily loop
mix deps.get # fetch from Hex (deps are in mix.exs)
mix compile # compile to BEAM bytecode
mix test # run ExUnit
iex -S mix # interactive shell with the app started
mix format # canonical formatting
mix hello.task # run any custom task
Formatting: Zero Configuration Arguments
mix format ships canonical — the team debates nothing. All policy lives
in .formatter.exs:
[
import_deps: [:ecto],
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"],
line_length: 98
]
Enforce in CI with mix format --check-formatted — nonzero exit on drift,
no plugin required.
One migration tool worth knowing on day one, because it rewrites files rather than complaining:
mix format --migrate
Verified on a file containing def a, do: 'charlist':
# before
def a, do: 'charlist'
# after
def a, do: ~c"charlist"
That is what converts deprecated charlist literals ('…' → ~c"…") and
unless expressions in bulk — see Ch 02 §2.7 on the 1.17+ charlist
deprecation. It
changes the AST, so the docs’ own advice applies: run it in its own commit
and review the diff before committing, especially in a macro-heavy project
(--migrate needs an .formatter.exs with :inputs to know what to touch).
Docs Flow Straight to hexdocs
Write @moduledoc / @doc (persisted into .beam documentation chunks —
see §2.1’s attribute notes), then:
mix docs # generates doc/ via ex_doc — edoc's successor
mix hex.publish # publishing a package pushes docs to hexdocs.pm too
mix hex.docs publish # or push docs for an already-published release
Consumers read the result at hexdocs.pm/your_package — zero extra
infrastructure, unlike standing up an edoc site.
flowchart LR
NEW["mix new --sup"] --> EDIT["edit lib/*.ex"] --> COMP{"mix compile"}
COMP -->|"warnings/errors"| FIX["fix · recompile"]
FIX --> COMP
COMP -->|ok| TST["mix test"]
TST -->|"red"| EDIT
TST -->|"green"| SH["iex -S mix<br/>dbg · h · i helpers"]
SH --> FMT["mix format"] --> REL["MIX_ENV=prod mix release"]
IEx Helpers You’ll Use Constantly
Start the shell and lean on these (all built into IEx):
iex> h Enum.reduce # documentation for anything — no browser needed
iex> i self() # introspect any term's type/implementation/raw repr
iex> recompile() # after editing source without leaving iex
iex> Hello.Math.add(1, 2)
3
# Kernel's dbg/1 — inspect a pipeline step by step:
iex> dbg(1..5 |> Enum.map(&(&1 * 2)) |> Enum.sum())
dbg/1 prints the code with each intermediate value plus the final result —
the fastest way to see what a pipe chain is doing:
1..5 |> Enum.map(&(&1 * 2)) |> Enum.sum()
#⇒ [1, 2, 3, 4, 5] |> Enum.map(&(&1 * 2))
#⇒ [2, 4, 6, 8, 10] |> Enum.sum()
#⇒ 30
Also worth adopting early: timeouts accept readable durations via
to_timeout/1 (to_timeout(hour: 2) instead of magic milliseconds) — handy
for Process.send_after/3 and GenServer timeouts.
Aliases and Custom Tasks Replace rebar3 Plugins
rebar3 plugins mostly existed to glue command sequences together. Mix covers
both halves natively. Half one, aliases — named pipelines of tasks in
mix.exs; entries run in order, failing fast:
def project do
[
# ...,
aliases: aliases()
]
end
defp aliases do
[
setup: ["deps.get", "compile"],
check: ["format --check-formatted", "test", "credo"]
]
end
Now mix check runs the whole gate — the provider-chain feel of rebar3
hooks, minus the configuration ceremony. It does require the credo dep from
step 1 above; without it the credo task is simply not defined. Half two,
custom tasks: drop a
module under lib/mix/tasks/ whose name descends from Mix.Tasks:
# lib/mix/tasks/hello.greet.ex — file name mirrors the task name
defmodule Mix.Tasks.Hello.Greet do
use Mix.Task
@shortdoc "Greets whoever you pass"
@impl Mix.Task
def run(args) do
Mix.shell().info("hello, #{Enum.join(args, " ")}")
end
end
mix hello.greet ada grace #=> hello, ada grace
mix help hello.greet # @shortdoc shows up in the listing
That is the entire plugin mechanism — no plugin registration in .app.src,
no provider wiring.
3.3 Tests: ExUnit vs EUnit/Common Test
defmodule Hello.MathTest do
use ExUnit.Case, async: true # concurrent suite — safe because processes isolate
test "add returns the sum" do
assert Hello.Math.add(1, 2) == 3
end
test "pattern matching failures" do
assert {:error, :enoent} = File.read("nope.txt") # assert MATCHES the pattern
end
end
Reading guide:
assert pattern = valueasserts that the match succeeds AND binds — failures print both sides. This makes most tests one line.async: trueruns suites concurrently on separate processes — safe by default because processes are isolated. (Shared resources — DBs, ports — need sandboxing; Ch 11 shows Ecto’s approach.)- Setup/teardown via
setupblocks instead ofinit/end_per_testcase. - Property testing: StreamData fills the QuickCheck niche.
- Process-based tests (like Common Test’s process scenarios) use
start_supervised!/1— starts a child under a test-owned supervisor that shuts down cleanly after each test.
Run it:
mix test # all
mix test path/to/file.exs # one file
mix test --trace # no timeouts, sequential (debug async issues)
mix test --failed # re-run only what last failed
mix test --cover # built-in line coverage summary
Two more that close loops Chapter 01 opened:
-
Doctests. Every
iex>block in a@doc/@moduledocbecomes a real test — but only if you ask for it, once per module:defmodule Hello.MathTest do use ExUnit.Case, async: true doctest Hello.Math # runs every example in Hello.Math's docs endIf a documented example is wrong,
mix testsays so. That is the entire mechanism behind “docs are executable” — and the reason the examples in this book carryiex>prompts. -
xref / dialyzer. Your rebar3 instincts carry over with different names:
rebar3 Mix rebar3 xrefmix xref graph --format dot/mix xref callers|calleesrebar3 dialyzermix dialyzer(viadialyxir), plus Elixir’s own gradual types (Ch 07)rebar3 eunitmix testrebar3 ctmix test+start_supervised!/1(Common Test’s process scenarios)
3.4 Releases
mix release produces a self-contained, OTP-native release — same
bin/app interface you know from rebar3 release:
MIX_ENV=prod mix release
_build/prod/rel/hello/bin/hello start # foreground
_build/prod/rel/hello/bin/hello daemon # background
Supports runtime config (config/runtime.exs), overlays, and hot upgrades via
the standard relup tooling when needed. The full walkthrough — release
anatomy, daemon operation, remote shells, and step-by-step hot upgrades —
is Chapter 09.
3.5 Calling Erlang from Elixir (and vice versa)
Interop is zero-friction — every Erlang library is available immediately:
:lists.max([3, 1, 2]) #=> 3
:ets.new(:cache, [:set, :named_table])
:gen_server.start_link(:my_mod, arg, []) # Erlang modules are lowercase atoms
{:ok, pid} = :file.open("data.txt")
Erlang libraries are ordinary Mix dependencies — same registry, different spelling of the source:
def deps do
[
# a Hex package that happens to be written in Erlang
{:cowboy, "~> 2.10"}, # called as :cowboy.start_clear/3
# an Erlang library straight from git
{:my_erl_lib, git: "https://github.com/org/lib.git", tag: "v1.0.0"},
# a sibling checkout in your working tree
{:local_lib, path: "../local_lib", override: true}
]
end
Mix compiles Erlang sources in the dependency just as it compiles Elixir
ones, so you get .beam files and a working .app file with no extra setup.
The one thing to know is that the application starts under an Erlang-style
atom: :cowboy, :my_erl_lib — not Cowboy, MyErlLib.
Any existing Erlang application can be added as a dependency and used
directly — no wrapper needed until you want an idiomatic Elixir API over it.
In practice teams wrap gradually: raw :module.fun calls first, then an
alias-heavy facade module, then (sometimes) a proper Elixir API package.
3.6 Step-by-Step Exercise
- Create:
mix new portme --sup - Add a supervised GenServer that holds state (Ch 05 shows idiomatic style).
- Call an Erlang function inside it (
:calendar.system_time_to_rfc3339/2). - Write an ExUnit test asserting its state transitions.
- Build a release and run it:
MIX_ENV=prod mix release && ...start. - Bonus: add
{:credo, "~> 1.7", only: [:dev, :test]}and runmix credo.
3.7 Umbrella Projects: rebar3 Sub-Apps, Unified
If you maintain a rebar3 repository holding several OTP apps under apps/,
Mix umbrellas will feel immediate:
mix new company --umbrella
cd company/apps && mix new billing --sup && mix new web
company/
├── mix.exs ← umbrella root: shared version + shared deps only
└── apps/
├── billing/ ← a COMPLETE mix project (own mix.exs, own app)
└── web/ ← depends on :billing via a normal deps entry
Root-level commands fan out to every child — mix test, mix compile, and
mix format all recurse; mix cmd --app web ... targets a single child.
Inter-app dependencies resolve locally first, mirroring how rebar3 orders
sub-app builds. Differences worth knowing: children share one _build and
one deps/ (faster, less disk), yet each still compiles to its own .beam
set and can be released individually or as one combined release.
Explore More
- Mix docs — environments, dependencies, aliases, configuration deep-dive
mix newtask — all generator flags including--umbrella- ExUnit docs — tags, contexts,
capture_log, and the full assertion library - Hex packages — browse by “downloads” to find the battle-tested library for any job
mix formattask — the full option list, including--migrateand--check-formatted- Erlang/OTP Design Principles
— the release-handling and application-controller rules that
application.eximplements for you - Exercise idea: recreate your favorite rebar3 plugin’s functionality as a custom Mix task (§9.3 of Ch 09 shows how)
Checkpoint
- Which file plays the role of
.app.src’smoddeclaration? - How do you start your app + shell at once?
- How would you depend on an existing Erlang hex/repo package?
- What does
--supsave you writing, and where does that code live?
Answers
mod: {Hello.Application, []}inapplication/0insidemix.exs, implemented byHello.Application.start/2.iex -S mix- Add it to
deps()— Hex packages or git repos work regardless of whether they’re written in Erlang or Elixir. - The
Applicationbehaviour module and root supervisor boilerplate; generated atlib/hello/application.exwith children wired intoSupervisor.start_link/2.
Next: Chapter 4 — Pipes, Enum & Stream
Chapter 4 — Pipes, Enum & Stream
Elixir’s daily-driver data flow. Concepts map directly onto the lists:
module — the syntax just got better, and laziness became first-class.
The chapter in one sentence: pipes shape how data flows, Enum executes
eagerly like lists:, and Stream defers execution so composition stays
cheap until a consumer pulls.
From Erlang you know:
Enumislists:with the arguments inverted, and nothing else.Streamhas nolists:equivalent — the closest thing in your current toolkit is a hand-rolled generator orqueue-based pipeline, which is why laziness is the genuinely new material here. The decision of when to be lazy is also new: in Erlang you rarely had the option.
4.1 Enum ↔ lists Module
Erlang (lists) | Elixir (Enum) |
|---|---|
lists:map(Fun, L) | Enum.map(list, fun) |
lists:filter(Pred, L) | Enum.filter(list, pred) |
lists:foldl(Fun, Acc, L) | Enum.reduce(list, acc, fun) |
lists:foreach(Fun, L) | Enum.each(list, fun) |
lists:all(Pred, L) | Enum.all?(list, pred) |
lists:any(Pred, L) | Enum.any?(list, pred) |
lists:member(E, L) | Enum.member?(list, elem) |
lists:reverse(L) | Enum.reverse(list) |
lists:sort(L) | Enum.sort(list) |
lists:usort(L) | Enum.sort(Enum.uniq(list)) — no single equivalent |
lists:uniq(L) | Enum.uniq(list) (both preserve first-seen order) |
lists:keystore(K, N, L, V) | Keyword.replace(opts, key, value) |
lists:keyfind(K, N, L) | Keyword.get(opts, key) / Map.fetch(map, key) |
lists:zip(A, B) | Enum.zip(a, b) |
lists:flatmap(Fun, L) | Enum.flat_map(list, fun) |
lists:partition(Pred, L) | Enum.split_with(list, pred) |
lists:split(N, L) | Enum.split(list, n) |
lists:takewhile(Pred, L) | Enum.take_while(list, pred) |
lists:dropwhile(Pred, L) | Enum.drop_while(list, pred) |
Two conventions to absorb with the table:
- Predicates end in
?(Enum.all?,Enum.member?) — boolean-ish functions read like questions. You’ll start writing your own predicates this way within days. - Data goes first. The collection is always the first argument and
the function/callback comes last. That inversion vs
lists:is exactly what makes pipes work (§4.2) — the piped value lands in the first argument slot.
Enum Works on More Than Lists
Erlang muscle memory says maps:to_list/1 before any iteration; in Elixir,
every Enum function accepts anything implementing the Enumerable
protocol (§5.2) — maps iterate as {key, value} pairs, ranges stream
without materializing:
iex> Enum.map(%{a: 1, b: 2}, fn {k, v} -> {k, v * 10} end)
[a: 10, b: 20]
iex> for {k, v} <- %{a: 1, b: 2}, v > 1, do: k # comprehensions too
[:b]
iex> Map.new([a: 1, b: 2], fn {k, v} -> {v, k} end) # build maps without
%{1 => :a, 2 => :b} # lists:foldl dances
The map-specific module still matters — Map.get/3, Map.update/4, and
friends are O(log n) keyed operations rather than full iterations — but the
“convert, iterate, rebuild” ritual is gone.
4.2 Pipes in Practice
The pipe passes the previous result as the first argument:
flowchart LR
S["1..10"] -->|"filter(is_even)"| A["[2, 4, 6, 8, 10]"]
A -->|"map(square)"| B["[4, 16, 36, 64, 100]"]
B -->|"sum()"| C["220"]
sum =
1..10
|> Enum.filter(&(rem(&1, 2) == 0))
|> Enum.map(&(&1 * &1))
|> Enum.sum()
#=> 220
Same program, eager Erlang style — note the bookkeeping of intermediate variables you no longer need:
List = lists:seq(1, 10),
Evens = lists:filter(fun(X) -> X rem 2 == 0 end, List),
Squared = lists:map(fun(X) -> X*X end, Evens),
Sum = lists:foldl(fun(X, Acc) -> X + Acc end, 0, Squared).
%% Sum = 220
Style rules you’ll absorb quickly:
- Pipe chains start from a raw value on its own line.
- Don’t pipe into
Enummore than ~5 steps without extracting a function. - Never pipe into a macro that doesn’t expect the value first.
Two Kernel helpers slot perfectly into chains — then/2 (transform) and
tap/2 (side effect, value passes through unchanged):
iex> 5 |> then(&(&1 * &1)) |> tap(&IO.puts("got #{&1}")) |> Kernel.+(1)
got 25
26
iex> user = %{name: "Ada"} |> put_in([Access.key!(:name)], "Grace")
Mental model: then replaces the value mid-chain; tap observes without
disturbing it — perfect for logging or dbg at any chain position.
Ranges Are First-Class
first..last creates inclusive ranges; append //step to step them; bare
.. is the full-slice range used in Access and binary_slice/2:
iex> Enum.to_list(1..5)
[1, 2, 3, 4, 5]
iex> Enum.to_list(1..10//2)
[1, 3, 5, 7, 9]
iex> Enum.to_list(10..1//-1) # descending needs an explicit negative step
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Ranges implement the Enumerable protocol (Ch 05), so every Enum/Stream
function works on them — including 1..10 |> Enum.sum() — without ever
building the list in between.
Deep Updates: put_in, update_in, get_in, pop_in
Nested structures update via path-based macros — the functional equivalent of walking pointers, rebuilt immutably at each level:
iex> user = %{name: "Ada", prefs: %{theme: "light", lang: "en"}}
iex> put_in(user.prefs.theme, "dark")
%{name: "Ada", prefs: %{theme: "dark", lang: "en"}}
iex> update_in(user.prefs.lang, &String.upcase/1)
%{name: "Ada", prefs: %{theme: "light", lang: "EN"}}
The dotted syntax works when keys are static; for runtime-computed paths,
pass explicit Access paths:
iex> key = :theme
iex> update_in(user, [Access.key!(:prefs), Access.key!(key)], fn
...> "light" -> "dark"
...> other -> other
...> end)
%{name: "Ada", prefs: %{lang: "en", theme: "dark"}}
Erlang needs hand-rolled nested updates for this; it is one of those conveniences that quietly changes how much nesting you will tolerate.
Comprehension Options: reduce: and uniq:
Two options cover the cases where bare for almost fits:
iex> for n <- 1..10, reduce: 0 do # threaded accumulator — a fold whose
...> acc when n > 5 -> acc + n # body is multi-clause
...> acc -> acc
...> end
40
iex> for w <- ~w(go stop go wait go), uniq: true, do: w
["go", "stop", "wait"]
iex> for <<c <- "abc">>, into: "", do: String.upcase(<<c>>)
"ABC"
With reduce: there is no implicit result list — the accumulator IS the
return value. Handy when accumulation logic branches per element and a
single reduce closure would need a case inside.
reduce_while: Fold With an Escape Hatch
Where Erlang’s foldl runs to completion unless you throw,
Enum.reduce_while/3 lets the fun decide per element:
iex> Enum.reduce_while(1..100, 0, fn i, acc ->
...> if acc + i >= 15, do: {:halt, acc + i}, else: {:cont, acc + i}
...> end)
15
iex> 1..100 |> Enum.take_while(&(&1 < 10)) |> Enum.sum()
45
{:halt, acc} stops and returns; {:cont, acc} continues. Pair with
take_while/drop_while when there is no accumulator to thread at all.
Comprehensions (for) — Special Form
for is a Kernel special form combining map/filter/reduce ergonomics
(generators <-, filters, into: for other collections):
iex> for n <- 1..10, rem(n, 2) == 0, do: n * n # generator + filter
[4, 16, 36, 64, 100]
iex> for {k, v} <- [a: 1, b: 2], into: %{}, do: {v, k} # collect into a map
%{1 => :a, 2 => :b}
# Multiple generators = cartesian product (nested loops, functionally):
iex> for x <- [1, 2], y <- [:a, :b], do: {x, y}
[{1, :a}, {1, :b}, {2, :a}, {2, :b}]
Reach for for when the operation reads naturally as “collect matching
transformations of these elements”; reach for reduce when state threads
through the iteration. They’re tools with overlapping territory — pick the
one that reads best.
4.3 Stream: Lazy, Composable Sequences
Stream mirrors Enum but builds a lazy computation. Nothing runs until a
final Enum operation pulls values through.
| Concept | Erlang (lists, eager) | Elixir (Stream, lazy) |
|---|---|---|
| Evaluation | Immediate per step | On demand |
| Memory | Intermediate lists each step | Constant (single pass) |
| Infinite sequences | Not practical | Stream.cycle/1, Stream.iterate/2 |
| Execution | At call time | At Enum.to_list/1, Enum.take/2, … |
Side by side on the same problem — sum the first five results of map→filter over 100k numbers:
flowchart TB
subgraph EAGER["Enum — eager: each step materializes"]
direction LR
E1["1..100_000"] --> E2["map ×100<br/>(100_000-elem list)"]
E2 --> E3["filter > 500<br/>(~100_000-elem list)"]
E3 --> E4["take 5<br/>FINALLY stops"]
end
subgraph LAZY["Stream — lazy: one element flows at a time"]
direction LR
L1["1..100_000"] -.->|"pull"| L2["map ×100"]
L2 -.-> L3["filter > 500"]
L3 -.->|"enough! stop pulling"| L4["take 5"]
end
style EAGER fill:#ffebee
style LAZY fill:#e8f5e9
# eager: maps/filters ALL 100_000 before taking 5
1..100_000 |> Enum.map(&(&1 * 100)) |> Enum.filter(&(&1 > 500)) |> Enum.take(5)
# lazy: stops after enough elements pass — never touches most of the range
1..100_000 |> Stream.map(&(&1 * 100)) |> Stream.filter(&(&1 > 500)) |> Enum.take(5)
#=> [600, 700, 800, 900, 1000]
Both return [600, 700, 800, 900, 1000]; the lazy version allocates no
intermediate lists and short-circuits after the fifth match.
Prove the short-circuit with a side effect rather than taking the word for
it. Each IO.puts fires only when its element is actually pulled:
iex> 1..5 |> Enum.map(fn x -> IO.puts("eager map #{x}"); x end) |> Enum.take(2)
eager map 1
eager map 2
eager map 3 # ← already ran, and its result was discarded
eager map 4 # ← ditto
eager map 5 # ← ditto
[1, 2]
iex> 1..5 |> Stream.map(fn x -> IO.puts("lazy map #{x}"); x end) |> Enum.take(2)
lazy map 1
lazy map 2
[1, 2] # three, four, five were never touched
That output is the whole argument for Stream, and it is worth internalizing
as a reflex: if a pipeline has a terminating consumer like take/2 early in
the chain, the eager version did work whose result you threw away.
A corollary that catches people: Enum.map over a huge collection is not
just slower than Stream.map — it holds the result in memory. Measured:
:erts_debug.size/1 reports 2,000,000 words for
Enum.to_list(1..1_000_000) — about 16 MB on a 64-bit VM, two words per cons
cell (the small integers are immediates, so they are not boxed). Streams
allocate none of that until a consumer forces materialization.
Infinite sequences are where streams stop being an optimization and become a different capability entirely:
iex> stream =
...> Stream.iterate(1, &(&1 + 1)) # infinite: 1, 2, 3, ...
...> |> Stream.map(&(&1 * 2)) # 2, 4, 6, ...
...> |> Stream.filter(&(&1 > 1000)) # 1002, 1004, ...
iex> Enum.take(stream, 10)
[1002, 1004, 1006, 1008, 1010, 1012, 1014, 1016, 1018, 1020]
iex> stream |> Enum.take(10) |> Enum.sum()
10110
Note the composition itself is instant (Stream.iterate on an infinite
sequence returns immediately) — nothing executes until an Enum function
pulls. Stream.run/1 drains a stream purely for side effects:
iex> ~w(a b c) |> Stream.each(&IO.puts(&1)) |> Stream.run()
a
b
c
:ok
Stream.resource/3: Wrapping External Handles
Streams shine when the data source needs lifecycle management — files,
sockets, cursors. Stream.resource/3 gives you three hooks: open (lazily),
next, close.
lines = fn path ->
Stream.resource(
fn -> File.open!(path) end, # start hook: runs at FIRST pull
fn device ->
case IO.read(device, :line) do
data when is_binary(data) -> {[data], device} # emit + continue
:eof -> {:halt, device} # stop pulling
end
end,
fn device -> File.close(device) end # after hook: guaranteed close
)
end
iex> "README.md" |> lines.() |> Enum.take(2) |> length()
2
iex> "README.md" |> lines.() |> Stream.map(&String.upcase/1) |> Stream.run()
:ok
Three properties worth memorizing:
- Lazy open — the file opens only when the first
Enumconsumer pulls; building and passing the stream costs nothing. - Close on completion or early halt — after successful initialization,
the after-fun runs both on natural exhaustion and when a consumer such
as
Enum.take/2stops early. Taking two lines closes the file; draining the remaining lines withStream.run/1is unnecessary. - Cleanup has limits — constructing a stream without consuming it opens nothing. Normal enumeration also runs cleanup if processing raises, but forcibly killing the consuming process can bypass cleanup. Do not rely on garbage collection to manage external resources.
Building Sequences: unfold and chunking
Stream.unfold/2 is the general stateful generator — each call returns
{value, next_state} or nil:
iex> fib = Stream.unfold({0, 1}, fn {a, b} -> {a, {b, a + b}} end)
iex> Enum.take(fib, 8)
[0, 1, 1, 2, 3, 5, 8, 13]
Chunking splits lazily too — windows with overlap, incomplete-part policy — without materializing the input:
iex> Enum.chunk_every(1..6, 4, 2, :discard) # window of 4, step 2
[[1, 2, 3, 4], [3, 4, 5, 6]]
Between unfold and chunk_while, most hand-rolled generators disappear.
In practice you rarely hand-roll the file wrapper at all — File.stream!/1
is exactly that Stream.resource machine, built in:
iex> File.stream!("README.md") |> Enum.take(2) |> length()
2
Two Limits of Laziness
Two behaviors surprise people who meet Stream after Enum:
- Laziness is not concurrency. A stream is a single-process,
single-pass pull machine — elements flow one at a time, in order, in
the consuming process. Parallelizing work per element is a different
tool:
Task.async_stream/3(Ch 05) or GenStage/Broadway (Ch 13). - Re-enumeration re-runs the work. A composed stream is a recipe,
not a cache. This one bites hardest because
Streamlooks like a collection, so you expectEnum.to_list(s)twice to mean the same values — it does, but at twice the side effects:
iex> tracked = Stream.map(1..3, fn i -> send(self(), {:ran, i}); i end)
iex> Enum.to_list(tracked)
[1, 2, 3]
iex> flush()
[:ran, :ran, :ran]
iex> Enum.to_list(tracked) # same recipe, run again
[1, 2, 3]
iex> flush()
[:ran, :ran, :ran] # six total, not three
Materialize once if you need the elements twice:
elements = Enum.to_list(tracked) # side effects happen exactly once, here
Caveat worth knowing: streams built from generators rather than
collections are single-pass and cannot be re-enumerated at all. You
will meet this with file handles and Stream.resource — the after-hook
has already closed the device.
From Erlang you know: this is the difference between a list you hold and a computation you describe. In Erlang you rarely had to think about it because
lists:map/2always gave you the list. The Elixir discipline that transfers: materialize at a boundary (when you cross from description to use), and stay lazy inside a single expression.
Laziness Is Not Automatically Faster
The opposite trap deserves equal billing. Over a finite collection with a
consumer that needs everything, laziness buys you little in speed: it replaces
an intermediate list with a closure and an extra protocol dispatch per element.
On a 100k-element map |> sum, eager Enum and lazy Stream land within
run-to-run noise of each other:
n = 1..100_000
Enum.sum(Enum.map(n, &(&1 * 2))) # eager: allocates the mapped list first
Enum.sum(Stream.map(n, &(&1 * 2))) # lazy: no intermediate list, more overhead
So do not reach for Stream expecting raw speed. Reach for it for one of
three real reasons: avoiding the intermediate allocation on a large
collection, terminating early, or consuming an unbounded source or an
external handle. Everything else is Enum, and the ergonomic default should
be too.
The flip side: laziness composes with concurrency when the source is
task-shaped. Task.async_stream/3 returns a stream that only launches work as
the consumer pulls, but it does overshoot — verified: ten items,
max_concurrency: 4, Enum.take/2 returns 3 results and starts 6 tasks.
async_stream keeps its pool full, so it launches ahead to
max_concurrency plus whatever is already in flight, then the puller stops
it. Work you hoped was skipped has already run.
This is the right mental model, and it generalizes: lazy ≠ “no work
happened.” It means “no work happens past the point you stopped pulling.”
Anything a stream function does as a side effect before its emit point has
already happened. Bounded fan-out (§28.4) is the pattern that gets you a real
bound.
4.4 Choosing Between Them
| Situation | Use |
|---|---|
| Small/medium collections, simple transforms | Enum (eager) |
| Large datasets, file/IO streams | Stream |
| Composing transformations across function boundaries | Stream |
| You need results more than once | Materialize once into a list |
| Nx tensor pipelines (Part IV) | Neither — tensors batch natively |
Rule of thumb: eager by default, lazy when memory or composition matters.
A useful heuristic from practice: if a pipeline touches files, network
responses, or anything unbounded, start with Stream; otherwise Enum’s
simplicity wins.
One warning worth internalizing early: calling Enum.* on a stream
materializes it — that’s the design (streams are consumed by eager
functions), but accidentally interleaving an Enum.map mid-chain silently
turns your lazy pipeline eager up to that point.
Measure It: Two Minutes, Permanent Intuition
Do not take laziness on faith — :timer.tc/1 tells the story on your own
hardware:
eager = fn ->
1..5_000_000 |> Enum.map(&(&1 * 2)) |> Enum.filter(&rem(&1, 3) == 0)
|> Enum.take(5)
end
lazy = fn ->
1..5_000_000 |> Stream.map(&(&1 * 2)) |> Stream.filter(&rem(&1, 3) == 0)
|> Enum.take(5)
end
{t_eager, r1} = :timer.tc(eager) # microseconds
{t_lazy, _r2} = :timer.tc(lazy)
r1
#=> [6, 12, 18, 24, 30] # identical results…
IO.puts("eager #{div(t_eager, 1000)}ms vs lazy #{div(t_lazy, 1000)}ms")
#=> eager ~190ms vs lazy ~0ms # …but lazy stops after five matches
For memory, sample :erlang.memory(:processes) before and after each
variant, or run :observer.start() and eyeball the per-process graph.
Numbers beat doctrine — especially before imposing Stream on a hot path
where per-element closures would cost more than they save.
4.5 Streams Are Everywhere in the Ecosystem
You will meet Stream again in this book:
- Nx batching:
Nx.to_batched(tensor, size)returns a lazy stream of batches (Ch 19). - LLM streaming: token chunks arrive as a
Stream.resource(Ch 28). - Broadway/GenStage: dataflow pipelines are stream-shaped (Ch 13).
Explore More
- Enum docs — skim the full function list once; knowing what exists saves reinventions
- Stream docs — especially
resource/3, the bridge from any external source to a lazy sequence - Comprehensions guide —
reduce:options and binary generators - Erlang Efficiency Guide: lists
— the same trade-offs written for
lists:, including whenlists:foldlbeats building intermediates - Exercise: take an eager pipeline from your own code, convert to
Stream, and measure memory with:erlang.memory(:processes)before/after on large input — feel the difference instead of believing it - Exercise: reproduce §4.3’s short-circuit proof with an
IO.putsside effect (eager prints 3, 4, 5 and discards them; lazy never does), then reproduce theTask.async_streamovershoot — count tasks that actually started when youEnum.take/2fewer than you asked for - Integration exercise: read a large log file with
File.stream!/1, trim and filter lines lazily, fan the expensive ones out throughTask.async_stream(..., max_concurrency: 8), and fold the results withEnum.reduce— the whole shape of this chapter in one pipeline
Checkpoint
- Convert
lists:foldlaccumulation over filtered input into a pipe chain. - When does a
Streampipeline actually execute? - Why is
Streamsafer than eager chains on unbounded input? - What’s the difference between
then/2andtap/2in a pipe? - How do you iterate
1..10by twos? - When
Enum.map/2walks a map, what shape arrives at your function? - You write
Enum.map(1..1000, side_effect) |> Enum.take(2). How many times doesside_effectrun, and why is the number surprising? - You enumerate the same
Streamtwice with differentEnumfunctions. What happens to the side effects inside it?
Answers
input |> Enum.filter(pred) |> Enum.reduce(acc, fun)- When a reduction-hungry
Enumfunction consumes it (to_list,take,sum,each,run…). - It pulls element-by-element with constant memory and short-circuits on
take-style termination, so unbounded sources never blow the heap. thencontinues the pipe with the function’s return value;tapruns a side effect and passes the original value through.1..10//2— a stepped range (Enum.to_list(1..10//2)→[1, 3, 5, 7, 9]).{key, value}tuples — maps implementEnumerable, so nomaps:to_list/1conversion step is needed.- All 1000.
Enum.mapis eager: it builds the whole list, and only then doestake/2keep two elements. The other 998 results were computed and discarded.Stream.mapwould run it twice. - They run twice. A
Streamis a recipe, not a cache — every enumeration re-executes every step. Materialize withEnum.to_list/1once if you need the elements more than once, and remember generator-backed streams (file handles,Stream.resource) are single-pass and cannot be re-run at all.
Next: Chapter 5 — Behaviours, Protocols & Structs
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 truemarks the function as implementing a callback — the compiler verifies signatures and catches typos (def proccess/1without@implsilently 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_infochecking 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
| Concept | Erlang (Behaviours) | Elixir (Protocols + Behaviours) |
|---|---|---|
| Polymorphism | Callbacks (module-based) | Protocols (data-based) + Behaviours |
| Define | -callback in behaviour | defprotocol Name do ... end |
| Implement | Write a module | defimpl Protocol, for: Type do ... end |
| Dispatch | Caller passes module | Runtime type of the value |
| Consolidation | Manual | Protocol.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:
| Protocol | Powers | Example |
|---|---|---|
Enumerable | Enum + Stream over any collection | Enum.count(mapset) |
Collectable | collecting into a data type | Enum.into(1..3, MapSet.new()) |
Inspect | programming-language representation | inspect(term), iex output |
String.Chars | to-string for humans/machines | "id: #{id}" interpolation |
List.Chars | to-charlist | to_charlist(term) |
JSON.Encoder | encoding 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
| Question | Answer |
|---|---|
| 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):
| Mechanism | Dispatch key | Choose when |
|---|---|---|
| Higher-order fun | the fn the caller passes | one call site, ad-hoc variation |
| Behaviour | module chosen at startup/config | few swappable implementations with lifecycle attached (supervision, restarts) |
| Protocol | type of the VALUE | open 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:
| Keyword | Effect | Erlang analogue |
|---|---|---|
alias Foo.Bar | rename for qualified calls only | none (manual naming) |
import Foo | unqualified function calls | -import(...) |
require Foo | allow macro expansion from Foo | -include_lib (closest) |
use Foo | invoke Foo.__using__/1 macro → injects code into YOUR module | none — 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!/2updates only existing keys — an unknown key raisesKeyErrorat 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 fielddefstructnever declared, and downstream%User{}matches accept it silently. Stay in update syntax andstruct!/2around typed data; use rawMapfunctions 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
| Module | What it gives you | Erlang equivalent you’d write |
|---|---|---|
Agent | minimal state-holding process | gen_server with one handle_call |
Task | one-shot async computation + await | spawn + receive dance |
Task.Supervisor | supervised tasks (restartable, linked safely) | custom supervisor for workers |
GenServer | generic client/server | gen_server itself |
Supervisor | child specs & restart strategies | supervisor |
Registry | key→process lookup, local names | gproc-style registry |
Application | start/stop/config lifecycle | application 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/supervisorcalls 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.)
| Need | Reach for |
|---|---|
| State, nothing else; simple get/set | Agent |
| Timers, multiple message kinds, complex transitions | GenServer (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.
| Situation | Use |
|---|---|
| Quick parallel work, caller wants to die on failure | Task.async + await |
| Failure must be a value; caller outlives crashes | Task.Supervisor.async_nolink + yield/shutdown |
| Bounded parallel map over many items | Task.async_stream + max_concurrency |
Explore More
- Module attributes & behaviours guide
- Protocols guide — including fallback implementations and consolidation internals
usedocumentation — 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 crashingTask.async, anawaittimeout, and anasync_nolink+yield— and observe who dies in each case before reading the comments
Checkpoint
- Translate an Erlang
-callbackpair into Elixir with@impl. - When does a protocol beat a behaviour?
- What makes
use GenServerdifferent from@behaviour :gen_server? - Which standard protocol must a type implement for
"#{term}"to work? - Which
Agentfunction makes “read and replace state” atomic? - 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)
- When selection depends on the value’s type rather than a caller-chosen module — especially for extending types you don’t own.
use GenServeris a macro (Ch 06): it declares the behaviour AND injects default child-spec/callback boilerplate into your module.String.Chars— interpolation callsto_string/1, which dispatches through it (List.Charsis its charlist sibling).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.- 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
Chapter 6 — Metaprogramming & DSLs
Elixir macros operate on the language’s own AST at compile time. This is not a party trick — it is the infrastructure the ecosystem is built on. It explains why Phoenix routes, Ecto queries, and Nx kernels all feel like native language constructs.
From Erlang you know: you have already written the crude version of this — a
parse_transform, or-compile(export_all)plus manual code generation. Three differences make macros a daily tool rather than a legend: they are hygienic (no variable capture surprises), they are scoped (expansion happens at a call site, not to a whole module), and they are ordinary functions you can unit-test. Same underlying idea — code that runs at compile time and emits code — with the sharp edges filed off.
6.1 What Compilers Actually Do With Your Code
Before macros, fix the compilation picture:
flowchart TD
SRC["Elixir source (.ex)"] --> PARSE["Parse → AST"]
PARSE --> EXP["Macro expansion<br/>← compile-time code generation"]
EXP --> LOWER["Lowered to BEAM code"]
LOWER --> BEAM["BEAM bytecode (.beam)"]
BEAM --> VM["BEAM VM / OTP"]
Macros are functions that run during expansion: they receive quoted code, return transformed/generated code. Everything downstream never knew they existed. Ch 08 expands this picture; here you only need the stage where macros live.
6.2 A Minimal Macro
Two cells (paste in Livebook or IEx). Keep them separate — see the note after cell 2.
Cell 1 — define (evaluate on its own):
defmodule Greeting do
defmacro __using__(_opts) do
quote do
import Greeting, only: [hi: 1]
def hello(name) do
"Your name is #{inspect(name)}"
end
end
end
defmacro hi(name) do
quote do
"Hi, " <> unquote(name)
end
end
end
Cell 2 — use it (a separate cell, after cell 1 has been evaluated):
defmodule Hello do
use Greeting
def my_fun, do: hi("BEAM")
end
IO.puts Hello.hello("Erlang")
IO.puts Hello.my_fun()
Do not paste definition and use into one cell, or into one
.exsfile. It fails withmodule Greeting is not loaded but was defined, becauseuseexpands torequire Greeting; Greeting.__using__(opts)— a remote call that needs the module already compiled. Everyrequire/useexample in this chapter assumes this, as does every library you try first.
Reading guide:
-
quote do ... endreturns the AST of its body instead of executing it. -
unquote(...)splices runtime values into that AST. -
defmacro hi/1runs at compile time of callers:hi("BEAM")becomes"Hi, " <> "BEAM"before the BEAM ever sees it. -
__using__/1defines whatuse Greetinginjects — imports, function definitions, behaviour declarations. This is the hook behind everyuse Phoenix.LiveView,use Ecto.Schema,use GenServer. -
useis exactly two things:use Fooexpands torequire Foo; Foo.__using__(opts). Nothing more. The four callbacks a library can hook are:Callback Fires Used by __using__/1at use Fooinject imports/defs/ @behaviour__before_compile__/1after the module body, before compile DSLs that collect clauses (§6.4) __after_compile__/2after compile, gets the bytecode emit files, run codegen __on_definition__/6on every defin the using modulemacro tracing, DSL registries Erlang has no equivalent for any of these; the closest is a parse transform, the last section of this chapter, which is coarser and unhygienic.
Step by Step: What quote Returns
An AST node is a three-element tuple: {form, metadata, args} —
Erlang’s abstract-format idea with friendlier metadata. Literals represent
themselves; everything else is a tuple:
iex> quote do: 1 + 2
{:+, [context: Elixir, imports: [{1, Kernel}, {2, Kernel}]],
[1, 2]}
iex> quote do: x
{:x, [], Elixir}
- form — node kind: operator, call target, variable name
- metadata — compile-time info: line/column,
context,imports - args — child nodes; a variable’s third element names its hygiene
context (
Elixirat the shell, a unique tag inside macros)
Hygiene: Broken, Then Fixed
The classic first mistake is treating a macro argument as a value instead of splicing it:
Evaluate the defmodule and the require/calls as separate cells, as in
§6.2 — one cell for the module, one for the use:
# cell 1
defmodule Hygiene do
defmacro double_broken(x), do: quote(do: x * 2) # fresh hygienic var
defmacro double_fixed(x), do: quote(do: unquote(x) * 2)
end
# cell 2
require Hygiene
Hygiene.double_broken(21)
#=> ** (CompileError) undefined variable x
Hygiene.double_fixed(21)
#=> 42
Hygiene renamed x inside quote, so the broken version references a
variable nobody bound; splicing the argument’s AST fixes it.
The actual compiler output for the broken version is worth reading once, because it names the variable’s context — which is the mechanism made visible:
warning: variable "x" is unused (if the variable is not meant to be used,
prefix it with an underscore)
│
2 │ defmacro double_broken(x), do: quote(do: x * 2)
│ ~
error: undefined variable "x" (context Hygiene)
│
2 │ Hygiene.double_broken(21)
│ ^^^^^^^^^^^^^^^^^^^^^
(context Hygiene) is the whole of hygiene in three words: the x inside your
quote is not the x bound as the macro’s parameter — it is a fresh
variable in the macro’s own context. unquote(x) is what splices the
caller’s actual AST in place of it.
When a macro must assign one of the caller’s variables, var!/1
deliberately breaks hygiene:
defmodule Ctx do
defmacro put(_key, val) do
quote do: var!(assigned) = unquote(val)
end
end
defmodule CallerMod do
require Ctx
def go do
Ctx.put(:k, 41 + 1)
assigned # ← visible here only because of var!
end
end
CallerMod.go() #=> 42
bind_quoted & unquote_splicing: The Injection Toolkit
Two mechanics appear in every serious macro (including the Validator DSL in §6.3) and deserve their own pass before you meet them in the wild.
bind_quoted: solves double evaluation. Splicing the same argument AST
twice evaluates it twice at the call site:
defmodule Twice do
# BAD: x's AST spliced twice → caller's expression runs twice
defmacro twice_bad(x), do: quote(do: unquote(x) + unquote(x))
# GOOD: bind_quoted evaluates x ONCE, binds the result under x,
# and disables bare unquote inside this quote block
defmacro twice_good(x), do: quote(bind_quoted: [x: x], do: x + x)
end
require Twice
side_effect = fn -> IO.puts("evaluated!"); 21 end
Twice.twice_bad(side_effect.()) # prints "evaluated!" twice → 42
Twice.twice_good(side_effect.()) # prints "evaluated!" once → 42
The bind_quoted: [x: x] form means “evaluate the outer x once at
macro-expansion time, inject the result as a hygienic variable named x.”
That disabling of stray unquote is deliberate — mixing both mechanisms in
one quote is how subtle expansion bugs happen; if you truly need both, opt
back in with quote unquote: true, bind_quoted: [...].
unquote_splicing: splats a list of AST nodes into an argument list —
the difference between inserting one node and many:
defmodule MyDef do
defmacro deflogged(name, args, do: body) do
quote do
def unquote(name)(unquote_splicing(args)) do # ← args become the
IO.puts("-> #{unquote(name)}") # parameter list
unquote(body)
end
end
end
end
defmodule Demo do
require MyDef
MyDef.deflogged :double, [x], do: x * 2
end
Demo.double(21) #=> prints "-> double", returns 42
Without the splice, def f([x]) would define a one-argument function whose
parameter is a literal list. With it, [x] becomes the parameter list
(x).
Re-reading §6.3’s Validator with these eyes: field/2 records through
bind_quoted, and __before_compile__ builds its clause list then splices
it with unquote_splicing(clauses) ahead of the fallback clause. There is
no third mechanism to learn for reading most library macros.
Debugging Your Expansions
Three moves cover 95% of macro debugging:
iex> ast = quote do: if List.first([1]), do: :yes
iex> ast |> Macro.expand_once(__ENV__) |> Macro.to_string() |> IO.puts()
case(List.first([1])) do
x when :erlang.orelse(:erlang."=:="(x, false), :erlang."=:="(x, nil)) ->
nil
_ -> :yes
end
# Peek INSIDE a macro while it expands — plain IO.puts at compile time:
defmacro loud(x) do
IO.puts("expanding with: #{Macro.to_string(x)}")
quote(do: unquote(x))
end
Macro.expand_once/2 performs one expansion step against your environment;
Macro.to_string/1 renders any AST back into readable code. Expand,
print, read — no debugger required.
6.3 Why the Ecosystem Looks Like It Does
Metaprogramming pipeline feeding major libraries:
flowchart TD
AST["Elixir AST"] --> MC["Macro / Compiler"]
MC --> PHX["Phoenix<br/>routes · plugs"]
MC --> ECTO["Ecto<br/>schema · queries"]
MC --> ASH["Ash<br/>resources · policies"]
PHX --> OUT["plain Elixir code<br/>(no runtime magic)"]
ECTO --> OUT
ASH --> OUT
Phoenix — declarative routing
scope "/", MyAppWeb do
pipe_through(:browser)
live "/dashboard", DashboardLive
live "/users", UserLive.Index, :index
end
pipeline :authenticated do
plug(MyAppWeb.Plugs.EnsureAuthenticated)
end
live, plug, pipe_through, scope are macros building a route table at
compile time. No reflection at request time — it compiles down to plain
pattern matches.
Ecto — schemas and composable queries
defmodule MyApp.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do # ← macro defining fields as struct keys
field :name, :string
field :email, :string
has_many :posts, MyApp.Blog.Post
timestamps()
end
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email])
|> validate_required([:name, :email])
|> unique_constraint(:email)
end
end
import Ecto.Query
query =
from u in User, # ← macro producing a query AST...
where: u.email == ^email, # ...checked & compiled to SQL
preload: [:posts],
limit: 1
The query DSL is parsed at compile time and translated to SQL — invalid queries fail early, not at runtime.
Ash — declarative domain resources
Verified against ash ~> 3.0; the DSL shifts between minor versions, so check
the installed version’s docs before copying.
defmodule MyApp.Accounts.User2 do
use Ash.Resource,
domain: MyApp.Accounts,
data_layer: Ash.DataLayer.Ets
attributes do
uuid_primary_key :id
attribute :name, :string, allow_nil?: false
attribute :email, :ci_string, allow_nil?: false
timestamps()
end
actions do
defaults [:read, :destroy]
create :register do
accept [:name, :email]
end
end
code_interface do
# `define :register` generates a function named after the action; pass
# `action: :register` explicitly when they differ.
define :register, args: [:name, :email]
end
end
# Usage (the code_interface puts it on the resource, not the domain):
# MyApp.Accounts.User2.register!("Alice", "alice@example.com")
Nx — numerical definitions (preview of Part IV)
defmodule MyModel do
import Nx.Defn
defn forward(x, params) do
x
|> linear_layer(params.w1, params.b1)
|> relu()
|> linear_layer(params.w2, params.b2)
end
end
defn restricts Elixir to a tensor-safe subset, then hands the AST to a
compiler backend (XLA/MLX). Same macro machinery, targeting accelerators
instead of SQL.
Roll Your Own: A Tiny Compile-Time Validation DSL
Everything above scales down to a weekend-sized example: accumulate
fields as module attributes during the body, generate validator clauses
in __before_compile__ — exactly the trick behind schema do ... end:
defmodule Validator do
defmacro __using__(_) do
quote do
import Validator, only: [field: 2]
Module.register_attribute(__MODULE__, :fields, accumulate: true)
@before_compile Validator
end
end
# Runs at the *caller's* compile time: records, generates nothing yet.
defmacro field(name, opts) do
quote bind_quoted: [name: name, opts: opts] do
@fields {name, Keyword.get(opts, :presence, false)}
end
end
# Runs after the caller's body finished accumulating @fields.
defmacro __before_compile__(env) do
fields = Module.get_attribute(env.module, :fields) |> Enum.reverse()
clauses =
for {name, true} <- fields do # presence flag filters here
quote do
def validate(unquote(name), data) do
case Map.fetch(data, unquote(name)) do
{:ok, v} when v in [nil, ""] ->
{:error, "#{unquote(name)} is required"}
{:ok, _} -> :ok
:error -> {:error, "#{unquote(name)} is missing"}
end
end
end
end
quote do
unquote_splicing(clauses)
def validate(_field, _data), do: :ok
end
end
end
defmodule Signup do
use Validator
field :email, presence: true
field :bio, presence: false
end
Signup.validate(:email, %{email: ""}) #=> {:error, "email is required"}
Signup.validate(:email, %{}) #=> {:error, "email is missing"}
Signup.validate(:bio, %{}) #=> :ok (fallback clause)
Two details carry the design: accumulate: true makes @fields grow
into a list instead of being overwritten per call, and generated code is
plain pattern-matched clauses — zero runtime reflection.
6.4 Practical Guidance for Erlang Developers
| Situation | Reach for |
|---|---|
| Plain abstraction | Functions / higher-order functions |
| Module contracts | Behaviours (Ch 05) |
| Delegate an API to another module | defdelegate (no macro needed) |
| Compile-time injection of boilerplate across modules | __using__ macro |
| New syntax for a domain | Full DSL macro |
| Reading libraries’ source | Start with their __using__ — it lists everything injected |
Two more Kernel building blocks worth knowing by name:
# defdelegate — expose another module's function (plain code, not magic):
defmodule MyRepo do
defdelegate all(query), to: BaseRepo
defdelegate insert(changeset), to: BaseRepo
end
# defoverridable — let callers replace injected defaults:
defmodule Base do
defmacro __using__(_) do
quote do
def name, do: "default"
defoverridable name: 0
end
end
end
defmodule Child do
use Base
def name, do: "custom" # overrides the injected default
end
Macro hygiene in one paragraph: variables inside quote are renamed per
call site so macros don’t leak bindings. When a macro must touch the
caller’s variables, it uses var!(name); when it must resolve an alias at
the call site, alias!(Alias). You’ll read these far more often than write
them.
Rules of thumb:
- Write macros last. Most needs are solved by functions + behaviours.
- Read macros first. When a library “feels magical,” find its
defmacro __using__— magic is always a finite list of injections. - Macros expand at compile time, so stack traces point at the generated code
unless the generator preserves locations. Keeping locations is a
one-flag decision inside your
quote:
quote location: :keep do
def unquote(name)(unquote_splicing(args)) do
unquote(body)
end
end
Verified on 1.20.4. A __using__/1 generating boom/0 that raises,
with a caller in a third module:
no keep: {Loc2.Plain, :boom, 0, [file: ~c"lib/m.ex", line: 24]}
location: :keep: {Loc2.Keep, :boom, 0, [file: ~c"lib/m.ex", line: 8]}
Line 24 is the use Loc2.M call; line 8 is raise("kaboom") inside the
macro’s quote. So the precise statement is: without :keep, every
generated definition is attributed to the use line that instantiated
it — one line for all of them, which is useless when the macro emits ten
functions. With :keep, each generated definition keeps the line inside
your quote where its body was written.
Note it does not point at the caller of boom/0 — no quoting flag
does that. What :keep buys is a stack trace that points into your
macro’s source rather than collapsing onto one use line.
Inspect any expansion live:
iex> Macro.expand_once(quote(do: if(true, do: 1)), __ENV__)
{:case, [optimize_boolean: true, type_check: {:case, :if}],
[
true,
[
do: [
# clause 1: {:->, _, [[{:when, _, [x, :erlang.orelse(
# :erlang."=:="(x, false), :erlang."=:="(x, nil))]}], nil]}
# clause 2: {:->, _, [[{:_, _, Kernel}], 1]}
]
]
]} # shape shown abbreviated — print it with Macro.to_string/1 to read
# dbg/1 is itself a great example of a small, useful macro:
iex> quote do: dbg(x)
{:dbg, [context: Elixir, imports: [...]], [{:x, [], Elixir}]}
# dbg receives CODE, can print + re-inject it
When Not to Write a Macro
Reach for a macro only when functions genuinely cannot do the job — the
common trap is wrapping trivial computation because it feels framework-y.
defmacro square(x) buys nothing over def square(x): no new syntax, no
deferred evaluation, no injected definitions. Functions compose with &
captures and appear intact in stack traces:
defmodule Math do
def square(x), do: x * x
end
Enum.map([1, 2, 3], &Math.square/1) #=> [1, 4, 9]
Justified macro uses: new surface syntax (where: in Ecto), controlling
when arguments evaluate (if/unless defer them), injecting definitions
across modules (child_spec). If none apply, write a function.
Macros vs Erlang Parse Transforms
Erlang’s escape hatch for metaprogramming is the parse transform: a
compiler plugin receiving a module’s entire abstract format after
parsing, returning rewritten erl_parse trees. Enabled per module, no
hygiene:
%% pt_version.erl — injects module_version/0 wherever enabled via -compile
-module(pt_version).
-export([parse_transform/2]).
parse_transform(Forms, _Opts) ->
Fun = {function, 0, module_version, 0,
[{clause, 0, [], [], [{integer, 0, 20260825}]}]},
Forms ++ [Fun].
| Concern | Parse transform | Elixir macros |
|---|---|---|
| Scope | whole module, all-at-once | per call site |
| Input | raw abstract format | quoted Elixir AST |
| Activation | -compile({...}) attribute | require / use |
| Hygiene | none | automatic (var! opts out) |
Elixir source never routes through parse transforms — its own front end expands macros before Erlang compilation begins; you meet transforms only inside Erlang dependencies. Where Erlang rewrites modules wholesale, Elixir libraries grow syntax callers opt into line by line.
Elixir’s metaprogramming is not a party trick. It is infrastructure for the ecosystem.
Explore More
- Quote and unquote guide — the AST construction mechanics behind §6.2
- Domain-Specific Languages guide — building your own DSL the way Ash/Ecto do
Macromodule —expand_once,to_string, traversal helpers; your debugging toolkit- Erlang Efficiency Guide: the compiler — the parse-transform and compile-time story from the Erlang side, useful for reading a macro-heavy Erlang dependency you inherited
- Metaprogramming Elixir (Chris McCord) — short, classic, still relevant
- Exercise: run
Macro.expand_once(quote(do: x = 1 && 2), __ENV__)and read the generated case tree — demystify one “magic” construct today - Exercise: reproduce the
location: :keepexperiment in §6.4 — a__using__/1that emitsboom/0raising an error, with and without:keep, and compare thefile:linein each stacktrace
Checkpoint
- At which stage of compilation do macros run?
- What does
use Somethingtypically inject? - How does Ecto validate queries early?
- What is the shape of an AST node for
1 + 2? - Which two
Kernelmacros let you opt out of hygiene? - Why does
bind_quotedexist, and what does it disable inside its quote? - What does
location: :keepactually change in a stacktrace — and what does it not fix?
Answers
- Between parsing and lowering to BEAM code — during macro expansion.
- Imports, aliases, injected function/clause definitions, behaviour
declarations, compile-time configuration — whatever its
__using__/1quotes. - The query DSL builds a typed AST at compile time; it is translated to SQL against the adapter, so structural errors surface before execution.
- A 3-tuple
{:+, metadata, [1, 2]}— operator, metadata, arguments. var!/1(escape a variable binding) andalias!/1(resolve an alias at the expansion site). Both are ordinaryKernelmacros — they are not inKernel.SpecialForms, which holds only the irreducible language core (defmodule,def,case,=,<<>>,quote, …).- It evaluates the argument once at expansion time and injects the result —
avoiding double evaluation when the same AST is spliced more than once.
Inside a
bind_quotedblock, bareunquoteis disabled (opt back in withunquote: true). - Without it, every definition your macro generates is attributed to the
useline that instantiated it — one line for all of them. With it, each generated definition keeps its own line inside yourquote, so a macro emitting ten functions gives ten distinct stacktrace lines instead of ten identical ones. What it does not do is point at the caller of the generated function; no quoting flag does that.
Next: Chapter 7 — Gradual Typing
Chapter 7 — Gradual Typing
Erlang gave you Dialyzer’s success typings. Elixir is now building something more ambitious: a set-theoretic, gradual type system built into the compiler — inference first, annotations optional. Gradual typing has landed incrementally since Elixir 1.17 and matured through the 1.19/1.20 lines; this chapter was verified against 1.20.3 and re-verified on 1.20.4. The official “Typespecs reference” page documents the annotation syntax; this chapter focuses on the workflow.
Version gating matters here. 1.17 checked patterns against types inferred within the same function. 1.18 added inference across function calls and for tuples/lists/return values. 1.19 added guard-derived types. 1.20 is mature. The examples below assume 1.19+; on 1.17/1.18 you get the same-function warnings but not the cross-function and guard ones.
From Erlang you know: Dialyzer’s success typings and this are answers to the same question — “which arguments can this function actually be called with?” — with two structural differences worth holding onto. Dialyzer is a separate post-hoc pass over a whole-project PLT, so it reports only at analysis time, on success typings, and every finding is a plausibility claim it cannot prove. The built-in checker is part of
mix compile, so findings arrive while you edit; it reports only provable violations; and untyped code is not “unchecked” so much asdynamic()— a region of deliberate uncertainty rather than a hole in coverage. Keep running both. They fail differently.
7.1 Set-Theoretic Types in One Minute
Traditional type systems ask: “What single named type is this value?”
Set-theoretic typing asks: “What set of values can this expression represent?” Sets compose with standard operations:
A ∪ B union (integer() or binary())
A ∩ B intersection (a map that has :id AND is not nil)
¬A negation (anything except nil)
A \ B difference (integer minus {0})
This models real data shapes directly and describes relationships between values — not just categories.
Set Operations in the Wild
You already reason this way in Erlang — the vocabulary is new, the algebra is not:
| Construct | Set reading |
|---|---|
integer() | binary() in a spec | union — accept either set |
Guard is_integer(x) on a clause | intersection — narrows the input set |
| Multiple function clauses | union of each clause’s accepted input set |
:error | {:ok, t} | tagged disjoint union — same convention as Erlang |
Negation is the operation Dialyzer never gave you directly. The checker
uses complements internally to justify exclusions — when it reports that a
value “cannot be nil” at a call site, it derived ¬nil from the paths
reaching there.
One thing to know before you read your first warning: the syntax the compiler
prints is not the syntax you write. Diagnostics use the set-theoretic
keywords — you will see dynamic(:many or :one or :two) — but the annotation
language is still classic typespecs. Verified on 1.20.4: writing or, and,
or not in a @spec/@type is a Kernel.TypespecError, because those are
resolved as ordinary remote types (or/2 undefined).
# what you write — classic typespecs, all valid
@spec fetch(String.t() | nil) :: {:ok, term()} | {:error, String.t()}
@spec either(integer() | binary()) :: :ok
@type named :: %{id: pos_integer(), name: String.t()}
# what the compiler prints — set-theoretic, read-only
dynamic(:many or :one or :two)
So negation and intersection are inferred and reported, not hand-writable.
That is the honest current state: you describe what you know with |,
dynamic(), and maps/structs, and the compiler does the set algebra.
7.2 Gradual Means You Adopt It by Doing Nothing
The codebase splits into zones that coexist:
flowchart TD
EXIST["Existing Elixir code<br/>(untyped, unchanged)"] --> DYN["dynamic() zone<br/>checker treats values as unknown"]
EXIST --> PREC["more precisely described code<br/>inferred types · optional @specs"]
DYN --> SAME["same ecosystem · same compile step<br/>no separate analysis pass"]
PREC --> SAME
- Untyped code keeps working; its values are typed
dynamic(). - The checker infers types from your code without annotations.
- It reports only verified bugs — inputs guaranteed to fail at runtime if executed.
- Add annotations where you want stronger guarantees.
7.3 Seeing It Work
Sixty seconds, zero annotations. Create a scratch project and paste the
examples below into lib/:
mix new typing_demo
cd typing_demo
# write Example 1 to lib/example1.ex …
mix compile # watch the type-checker report the violation
Example 1 — inferred union flows into an impossible call:
defmodule GradualExample.Example1 do
def percentage_or_error(value) when is_integer(value) do
value_or_error =
if value > 1 do
value # integer branch
else
"not well" # binary branch → value_or_error: integer() or binary()
end
if value > 1 do
value_or_error / 100
else
String.upcase(value_or_error)
end
end
def input(string) when is_binary(string) do
percentage_or_error(string) # ← binary() into integer()-only function
end
end
mix compile output (excerpt, Elixir 1.20.3):
warning: incompatible types given to percentage_or_error/1:
percentage_or_error(string)
given types:
-binary()-
but expected one of:
integer()
where "string" was given the types:
# type: binary()
# from: lib/example1.ex:17:13
string
# type: binary()
# from: lib/example1.ex:17:26
is_binary(string)
type warning found at:
│
18 │ percentage_or_error(string)
│ ~
Note what happened: no annotations anywhere, yet the checker knew
percentage_or_error/1’s guard restricts it to integer() and caught the
caller passing binary().
Example 2 — literal atoms as singleton types:
defmodule GradualExample.Example2 do
def sum(a, b), do: get(a) + get(b)
def get(:a), do: 1
def get(:b), do: {:ok, 3}
def run, do: sum(:a, :b) # get(:b) returns {:ok, 3} → + on a tuple
end
warning: incompatible types given to sum/2:
sum(:a, :b)
given types:
:a, -:b-
but expected one of:
:a, :a
type warning found at:
│
7 │ def run, do: sum(:a, :b)
│ ~
(The -dashes- mark the offending type in the terminal output.) Each atom
literal is its own singleton type, so clause coverage is tracked precisely.
Example 3 — case exhaustiveness through inferred return sets:
defmodule GradualExample.Example3 do
def num_to_descr(num) do
case num do
1 -> :one
2 -> :two
_ -> :many
end
end
def print(num) do
case num_to_descr(num) do
:zero -> IO.puts("zero") # ← unreachable: :zero not in result set
x -> IO.puts("Other: #{x}")
end
end
end
Compiling this reports the dead clause with the inferred union:
warning: the following clause will never match:
:zero ->
because it attempts to match on the result of:
num_to_descr(num)
which has type:
dynamic(:many or :one or :two)
Reading a Diagnostic Like a Provenance Trail
The Example 1 warning deserves a slow read — every section is a fact the checker proved:
given types: binary() ← what flowed INTO the call
but expected one of: integer() ← the callee's guard-derived contract
where "string" was given the types:
# from: lib/example1.ex:20:13 ← where that value was born
string
This is the structural difference from Dialyzer output: instead of a bare
“spec is a supertype of the success typing”, you get a flow trace —
declaration site, definition site, call site — across module boundaries.
When a warning appears, the interesting question is rarely why but which
upstream branch leaked the wrong type in, and the from: lines answer it.
Match Expressions Refine, Not Just Consume
Patterns and guards work symmetrically: branches produce unions going out, patterns narrow types coming in.
defmodule Shapes do
def describe(shape) do
case shape do
{:circle, r} -> {:round, r} # narrowed to {:circle, integer()}
{:rect, w, h} -> {:box, w * h} # narrowed to {:rect, _, _}
other -> {:unknown, other} # whatever remains of the union
end
end
end
A verified warning appears only when every path into a call fails. Where the value’s type is fully known locally, singletons propagate and the checker reports provably fatal calls:
def down do
y = 5
String.length(y) # ← reported: integer() into binary()-only call
end
But inference across function boundaries keeps dynamic() in the mix
whenever any clause admits unknown input — describe/1 above accepts a
dynamic other, so its inferred contract lets r stay partly dynamic and
a downstream String.length/1 stays silent. That is the gradual
contract working as designed: report only what is provably fatal, absorb
everything else as dynamic().
7.4 Dialyzer Comparison for Erlang Developers
| Aspect | Dialyzer | Elixir gradual set-theoretic types |
|---|---|---|
| Analysis | Success typing (post-hoc tool) | Built into mix compile |
| Baseline | Whole program, whole-project analysis | Whole codebase, on by default — there is no opt-in attribute |
| Annotations | -spec (optional specs) | Typespecs, optional; inference needs none |
| False positives | Known issue with success typing | Reports only verified failures |
| Contracts across modules | Specs | Inferred signatures + specs |
Keep using Dialyzer during migration — they complement each other. Over time, the built-in checker becomes primary because it runs on every compile with no separate PLT build step.
Known Blind Spots (1.20) — Measured, Not Guessed
Silence is not proof, and the boundary is sharper than you might guess. I ran
the same violation — String.upcase/1 given an integer() — through nine
shapes on 1.20.4. Reported: direct, case clause, with clause, if
branch, and an immediately-invoked fn. Not reported: for
comprehension, and any callback handed to Enum.*.
def for_comp, do: (for i <- [1], do: String.upcase(i)) # SILENT
def enum_map_fn, do: Enum.map([1], fn v -> String.upcase(v) end) # SILENT
def enum_map_cap, do: Enum.map([1], &String.upcase/1) # SILENT
def enum_reduce, do: Enum.reduce([1], "", fn v, _ -> String.upcase(v) end) # SILENT
def map_new, do: Map.new([1], fn v -> {v, String.upcase(v)} end) # SILENT
def case_clause, do: (case 1 do v -> String.upcase(v) end) # reported
def with_clause, do: (with x <- 1, do: String.upcase(x)) # reported
def if_branch, do: (if true, do: String.upcase(1)) # reported
def anon_called, do: (fn v -> String.upcase(v) end).(1) # reported
So the rule is not “comprehensions and closures.” It is closer to: the
checker follows values through language constructs, but not through
higher-order boundaries where you pass a function to someone else. The
moment a callback crosses into Enum.map/2, the parameter’s type is whatever
that function’s spec says — usually dynamic() — and everything downstream
of it is unchecked too.
That has a direct practical consequence for how you review code: a
violation hidden inside an Enum.* callback is invisible, and pipeline
chaining is the dominant Elixir idiom. Annotate the callback boundary
yourself when the data comes from outside:
def to_labels(users), do: Enum.map(users, &String.upcase/1)
Annotating that boundary does not help, and that is the single most important thing to know in this chapter. Verified on 1.20.4:
defmodule Callee do
@spec only_binary(binary()) :: :ok
def only_binary(_x), do: :ok # arg unused => body infers dynamic()
end
defmodule Caller do
def a, do: Callee.only_binary(42) # an atom, where the spec says binary()
end
mix compile --force is silent. Add a guard so the body constrains the
parameter, and the identical call is reported:
def only_binary(x) when is_binary(x), do: :ok
#=> warning: incompatible types given to Callee.only_binary/1
# given types: -integer()-
# but expected one of: binary()
The rule for 1.20 is blunt: inference drives the checking; @spec is
documentation. It will not make a call site fail, and it is not validated
against the body either — this compiles clean, spec and body disagreeing
about the return type entirely:
@spec liar(integer()) :: :atom
def liar(x), do: x * 2 # returns an integer; spec claims an atom. No warning.
This inverts the Dialyzer instinct. You arrive expecting @spec to be the
contract; here it is a comment. Your actual leverage is guards and clauses
— is_integer/1, when x > 0, exhaustive multi-clause heads — because those
are what inference reads. Type aliases in a spec are worth exactly as much as
the guards behind them.
Keep writing @spec for the consumers who benefit (ExDoc, Dialyzer, your own
future self). Just do not expect CI to enforce it.
Two more calibration notes:
dynamic()on its own means unknown.dynamic(t)is narrower: the runtime value istor unknown, so you are only warned if no member oftwould be accepted.@type t :: %__MODULE__{...}is a classic typespec — it does not make the compiler check your struct’s fields on construction. Typed structs with real field checking are still roadmap work.
Why Success Typings and Gradual Checks Disagree
Dialyzer computes a success typing: for each function, the set of
arguments for which execution cannot crash, derived optimistically from
the whole program. Optimistic means assumptions — code that looks dead
is assumed reachable, so contradictions sometimes surface as warnings that
blame correct code. The gradual checker inverts the contract: report only
when failure follows from the types on every admitted path, otherwise
stay silent (dynamic() absorbs doubt). Fewer guarantees, near-zero noise.
%% Dialyzer's world: optional specs, whole-app analysis, a PLT to build.
-spec percentage(number()) -> number().
percentage(X) -> X / 100.
%% dialyzer --plt ~/.dialyzer_plt --succ_typings myapp
During migration the two disagree productively: Dialyzer finds latent bugs
in zones the gradual checker still treats as dynamic(), while the
compiler catches regressions on every build in zones you have tightened.
7.5 Adoption Playbook (Step-by-Step)
- Upgrade to Elixir 1.20+ (
mise use elixir 1.20, asdf, etc.). - Run
mix compile --warnings-as-errorsin CI to freeze current state. - Read each type warning; fix genuine bugs immediately (they’re verified).
- Add guards and clauses at public boundaries — this is what the checker
reads. Write
@spectoo, for docs and Dialyzer, but understand it does not enforce anything on its own (§7.4). - Tighten gradually inward; leave glue/UI layers
dynamic()longest.
A first annotation, showing the new type syntax alongside classic typespecs:
defmodule Percentage do
@type result :: {:ok, number()} | {:error, String.t()}
# Guards refine parameter types — the checker reads them:
@spec of(non_neg_integer()) :: float()
def of(value) when is_integer(value) and value >= 0 do
value / 100 # ← always a float; `/` returns floats (Ch 02)
end
end
The exciting part is not “Elixir becomes Java/C#.” It is stronger compile-time reasoning while preserving dynamic style.
Typed Structs and Opaque Boundaries
Struct types use the familiar %Module{} syntax; @opaque hides the
representation exactly as -opaque does in Erlang headers:
defmodule Account do
@enforce_keys [:id]
defstruct [:id, :balance]
@type t :: %__MODULE__{id: String.t(), balance: number()}
end
defmodule Ledger do
@opaque t :: {:ledger, list(Account.t())}
end
Callers type against Account.t() and Ledger.t(); only Ledger may
pattern-match the tuple inside — the same information-hiding contract you
know from Erlang’s -opaque.
Freezing the Baseline in CI
# CI excerpt — fail the build on any new type warning:
mix compile --warnings-as-errors
mix test
Pair this with the playbook above: today’s clean compile becomes
tomorrow’s contract. New warnings block merges; legacy dynamic() zones
tighten at your own pace, module by module, starting with pure domain
logic where inference is strongest.
Explore More
- Typespecs reference — annotation syntax including the new set-theoretic forms
- Gradual set-theoretic types — the official design page; read the “type inference” section twice
- the
typing_demoscratch project from §7.3 — break it on purpose: change a guard, watch the checker trace exactly where the incompatible type flows from - Dialyzer docs — for comparison; keep both running during migration (§7.4). Dialyzer’s success typing page explains the reference model this chapter contrasts against
- Exercise idea: take one of your pure modules, delete nothing, and count how
many verified warnings plain
mix compilesurfaces on Elixir 1.20+ - Exercise idea: reproduce §7.4’s
@specfinding. Write a callee with a narrow@specand a body that infersdynamic(), call it wrongly from another module, and confirm silence. Then add one guard and confirm the warning appears — that difference is the whole chapter in one experiment
Checkpoint
- What does
dynamic()mean and where does it come from? - Why are reported warnings trustworthy?
- What’s the cheapest first step to benefit today?
- A function’s
@specsays it acceptsbinary(). A caller passes an integer. Does the build fail? (Hint: it depends on the body, not the spec.) - Where does a type error most often hide, given that
case,with,if, and immediately-invokedfnare all checked?
Answers
- The type of all untyped values — anything not yet constrained; gradual typing’s escape hatch that lets typed and untyped zones interoperate.
- They represent inputs guaranteed to raise/fail at runtime if executed — no speculative warnings.
- Upgrade to 1.20+ and just run
mix compile— inference starts finding bugs in existing untyped code with zero changes. - Probably not. The checker infers the callee’s contract from its body; a
narrow
@specover a body that infersdynamic()buys no caller-side checking, and the spec is not validated against the body either. Add a guard (when is_binary(x)) and the same call is reported. That is §7.4’s central finding — write guards, not specs, if you want enforcement. - Inside a callback passed to a higher-order function:
Enum.map/2,Enum.reduce/3,Map.new/2, andforcomprehensions. The moment a function crosses into one of those, its parameter types are whatever that function’s own spec says — usuallydynamic()— and everything downstream is unchecked.
Next: Chapter 8 — The Compilation Model
Chapter 8 — The Compilation Model
An Erlang developer already knows the destination: BEAM bytecode. This chapter confirms there is no runtime surprise waiting — and shows exactly where Elixir adds steps.
From Erlang you know:
rebar3’s compile pipeline,.app.src→.app,beam_lib:chunks/2,beam_disasm, and the hot-code-loading model all apply unchanged. What is new is where Elixir sits in that pipeline and the incremental-build graph Mix maintains for you. Nothing about the artifact differs; only the front end does.
8.1 From .ex to Execution
flowchart TD
SRC["Elixir source (.ex)"] --> AST["Parse → AST"]
AST --> EXP["Macro expansion<br/>← Ch 06 lives here"]
EXP --> LOW["Lowered to Erlang/BEAM code"]
LOW --> BC["BEAM bytecode (.beam)"]
BC --> VM["BEAM VM / OTP"]
VM --> P["Processes<br/>schedulers · GC<br/>distribution"]
Steps at a high level:
- Parse — source becomes the internal AST representation
- Macro expansion — macros execute at compile time, transform/generate code (types from Ch 07 are checked around here too)
- Compilation — resulting program compiled to BEAM-compatible modules
.beamoutput — same file format Erlang produces- Runtime — OTP executes them exactly as Erlang modules
You can prove identity to yourself. Compile the module, then ask the runtime from the other language:
mix compile
erl -pa _build/dev/lib/hello/ebin -noshell -eval '
io:format("which: ~p~n", [code:which('"'"'Elixir.Hello'"'"')]),
io:format("exports: ~p~n", ['"'"'Elixir.Hello'"'"':module_info(exports)]),
halt().'
which: ".../_build/dev/lib/hello/ebin/Elixir.Hello.beam"
exports: [{'__info__',1},{add,2},{module_info,0},{module_info,1}]
(That export list is real output, not a sketch.) Note the quoted module name:
in an Erlang shell, unquoted Hello parses as a variable — Elixir modules
are always addressed as 'Elixir.Name' from Erlang.
Your Elixir module is callable from Erlang as any other module — because it
is one. (Names are atoms like :"Elixir.Hello".)
What Mix Actually Writes
The build output is worth reading once, because it makes several later
chapters concrete. After mix compile in a two-file app:
_build/dev/lib/hello/
├── .mix/compile.app_cache ← build graph; delete it and everything rebuilds
├── .mix/compile.elixir ← per-module manifests: mtimes, deps, digests
├── .mix/compile.elixir_scm
├── consolidated/ ← protocol dispatch tables (Ch 05)
│ ├── Elixir.Collectable.beam
│ ├── Elixir.Enumerable.beam
│ ├── Elixir.IEx.Info.beam
│ ├── Elixir.Inspect.beam
│ ├── Elixir.List.Chars.beam
│ ├── Elixir.String.Chars.beam
│ └── Elixir.JSON.Encoder.beam
├── ebin/Elixir.Hello.beam ← your code
└── ebin/hello.app ← generated, NOT hand-written
Three things an Erlang developer should notice:
There is no src/ directory and no .app.src. Mix generates the .app
from mix.exs. Here is the real content of a minimal app:
{application,hello,[
{modules,['Elixir.Hello']},
{optional_applications,[]},
{applications,[kernel,stdlib,elixir,logger]},
{description,"hello"},
{registered,[]},
{vsn,"0.1.0"},
{mod,{'Elixir.Hello.Application',[]}}
]}.
Compare that to the .app.src you used to write by hand: same keys, same
semantics, {mod, ...} present only because you declared it. The one real
difference is elixir sitting in applications — every Elixir app depends on
the elixir OTP application, and the dependency list is computed from your
extra_applications plus your deps, not typed out.
The consolidated/ directory is new to you. Erlang devs implement
-callback dispatch; protocol dispatch (Ch 05 §5.2) is Elixir’s addition, and
Mix builds its lookup tables here. Delete the directory and protocol calls
get slower; nothing breaks.
.mix/compile.elixir is the incremental-build state. §8.5 is about what
that file records.
Inside the .beam: Chunks
A .beam file is a container of named chunks — and beam_lib opens it
from either language. From an Erlang shell:
1> beam_lib:chunks("Elixir.Hello.beam", [attributes, compile_info, exports]).
{ok,{'Elixir.Hello',
[{attributes,[{vsn,[...]}]},
{compile_info,[{version,"10.0.3"},
{options,...},
{source,"…/lib/hello.ex"}]},
{exports,[{'__info__',1},{add,2},{module_info,0},{module_info,1}]}]}}
Note '__info__',1 in the exports list: that is Elixir’s reflection entry
point. Hello.__info__(:functions), (:attributes), (:macros),
(:compile) are what Elixir tooling (docs, compilers, mix xref) calls; the
Erlang-side equivalent is Hello:module_info/0,1. No Erlang module has
__info__/1.
(beam_lib:chunks/2 takes chunk aliases — pass atoms
(abstract_code, attributes, compile_info, exports, imports, …),
not the raw chunk ids as strings.)
Chunks worth knowing by name:
| Chunk | Content |
|---|---|
Dbgi (debug_info) | debug info — the source of abstract_code reconstruction |
CInf (compile_info) | compiler version, options, source path, timestamp |
ExpT (exports) | the interface Erlang tooling dispatches on |
Ask for abstract_code and you get the expanded program: macros from
Ch 06 are gone by now, and types were checked around Ch 07’s stage. The
forms come back as Erlang erl_parse trees, because at that point the
code is Erlang-shaped. One caveat: Elixir stores debug info in its own
format, so abstract_code needs the Elixir compiler backend on the code
path — run the query from iex/mix, or add Elixir’s elib to an
erl session, or you’ll get {error, {missing_backend, _, elixir_erl}}.
Prove It: Disassemble Both Sides
beam_disasm opens Elixir-produced .beam files exactly like any other,
because there is no “other”. Compile defmodule Hello do def add(a, b), do: a + b end, then from an Erlang shell:
1> {beam_file, M, _Exports, _Attrs, _Compile, Funs} =
beam_disasm:file("Elixir.Hello.beam").
2> {function, add, 2, _Label, Asm} = lists:keyfind(add, 2, Funs).
3> io:format("~p~n", [Asm]).
[{label,10},
{line,[{location,"hello.ex",2}]},
{func_info,{atom,'Elixir.Hello'},{atom,add},2},
{label,11},
{gc_bif,'+',{f,0},2,[{x,0},{x,1}],{x,0}},
return]
The hot path is two instructions: put both arguments through the same
GC-safe + BIF your Erlang code compiles to (the func_info preamble is
standard export trampoline boilerplate, present in every module).
Hand-write the twin in pure Erlang (add(A, B) -> A + B.), disassemble it,
and the opcode sequence matches modulo label numbers and line info. The
only meaningful difference anywhere in either file: the module atom reads
'Elixir.Hello'.
8.2 .ex vs .exs
| Extension | Purpose | Execution |
|---|---|---|
.ex | Application code | Compiled to .beam by mix compile |
.exs | Scripts, tests, config | Compiled in memory and executed; no .beam written to disk |
That second row is the one worth getting right: .exs is not interpreted.
The same pipeline runs — parse, expand, compile to BEAM bytecode — the only
difference is that the bytecode is loaded and executed immediately instead of
being persisted. The mental model is erl -eval or escript, not a
scripting engine. Tests (test/**/*_test.exs) and config files stay .exs;
everything shipped stays .ex.
There is a third case worth knowing, because it catches people migrating: a
.exs file sitting inside lib/ is silently ignored by mix compile.
Only .ex files there are compiled; the .exs is not even a warning. If you
are porting a module and nothing appears in ebin/, check the extension before
you check anything else.
The rule in one line: .exs is a load-and-run format for things Mix should
not own — tests, scripts, config/*.exs, mix.exs. Anything Mix should
own, including a Mix task, belongs in lib/mix/tasks/*.ex.
When you bypass Mix, elixirc takes the same options the compiler exposes
through mix compile:
$ elixirc --warnings-as-errors --no-docs -o ebin lib/hello.ex
$ ls ebin
Elixir.Hello.beam
elixirc exposes only the negative forms: there is no --docs or
--debug-info flag, because both chunks are on by default and you use
--no-docs/--no-debug-info to strip them. The compiler switches are
--warnings-as-errors, --no-docs, --no-debug-info,
--ignore-module-conflict, --verbose, and --profile time. Everything
else is configured through mix.exs (:docs, :debug_info).
8.3 What Is Identical at Runtime
Nothing below the language layer changed:
- Preemptive scheduling — reductions-based, per process
- Per-process heaps & GC — no stop-the-world pauses
- Distribution — same EPMD/Dist protocol; nodes cluster identically
- OTP behaviours — GenServer/supervisor semantics byte-for-byte
- Hot code loading — two-version module model intact
Mental model:
flowchart TD
EX["Elixir"] --> CM["compiled modules"]
CM --> BEAM["BEAM"]
BEAM --> OTP["OTP runtime"]
OTP --> R["processes · schedulers ·<br/>supervision · distribution"]
Code Loading: Two Versions, Same Rules
Modules load interactively (on demand from the code path — your dev
shell) or embedded (everything up front at boot — what releases use;
Ch 09’s RELEASE_MODE flips it). Either way the two-version model holds:
each module has at most a current and an old incarnation. Redefine a
module and the new code becomes current immediately, while any process
still executing the old incarnation keeps running it until
:code.purge/1 retires that copy:
iex> defmodule Hello, do: (def v, do: :first)
iex> Code.compiler_options(ignore_module_conflict: true)
iex> defmodule Hello, do: (def v, do: :second)
iex> Hello.v()
:second
Same machinery an Erlang hot upgrade lives inside — the redefine-and-purge
dance your shell’s l(Module) performs (l/1 in erl comes from the c
module: c:l(Hello); in IEx the equivalent is recompile()). Here it is
reached through defmodule re-evaluation. Ch 09 §9.8 shows processes being
walked across versions deliberately, code_change and all.
8.4 Where Kernel Meets :erlang (BIF Inlining)
Many Kernel functions are inlined by the compiler into their Erlang
counterparts in the :erlang module — the BIFs you already know. Capture a
guard and you can see it directly:
iex> &Kernel.is_atom/1
&:erlang.is_atom/1
iex> &Kernel.byte_size/1
&:erlang.byte_size/1
This is why guards are cheap, why they’re allowed in match contexts, and why
Kernel’s docs mark functions “inlined by the compiler.” The same applies to
operators: +, <, == compile to :erlang arithmetic and comparison.
One asymmetry to respect: special forms (defmodule, def, quote,
case, =, <<>>, …) live in Kernel.SpecialForms — they’re always
imported and cannot be excluded or overridden. They aren’t functions at
all; they’re the language’s irreducible core, handled directly by the
compiler.
8.5 Compile-Time Dependencies & Incremental Recompiles
Edit one module, watch Mix recompile ten — this is Mix’s dependency graph at work, and it has no Erlang-make analogue worth missing. While compiling each file, the compiler records what that file depends on to compile:
| Dependency kind | Created by | Consequence |
|---|---|---|
| compile-time | import, require, macro calls, defstruct expansion, behaviours | changing the source forces recompiling dependents |
| runtime | plain remote calls (OtherMod.fun(...)) | no recompilation of callers |
The struct case surprises everyone once: %User{} patterns compile the
struct’s field layout into the using module (§5.4), so editing
User’s defstruct correctly triggers recompilation of every module
that pattern-matches it. The graph is derived by the compiler — not
hand-maintained in a makefile.
Measured, because “correctly triggers” deserves evidence. Two files, U
(defining a struct) and V:
# V with a direct struct pattern
defmodule V do
def name_of(%U{name: n}), do: n
end
Add one field to U’s defstruct and Mix recompiles both files:
$ mix compile
Compiling 1 file (.ex) ← lib/u.ex
Compiling 1 file (.ex) ← lib/v.ex, because its pattern no longer matches
Change V to a remote call instead, then extend the struct again:
defmodule V do
def name_of(u), do: U.name(u) # no struct pattern in V
end
$ mix compile
Compiling 1 file (.ex) ← only lib/u.ex
One line of difference, and the cascade disappears. That asymmetry is the whole design: a struct pattern embeds the layout (so it must be recompiled when the layout moves), while a call resolves at runtime and does not. In Erlang the equivalent question never arises because records carry no compile-time shape at all.
Inspect and manage it:
mix xref graph --label compile-connected # files whose compilation cascades
mix xref graph --sink lib/my_app/user.ex # who recompiles when user.ex changes
mix xref unreachable # remote calls to undefined modules
Practical rule: keep macros, imports, and structs out of low-stability
modules; put them behind small facade modules so the cascade stops there.
A shrinking compile-connected set is the health metric for large
codebases’ build times.
8.6 Key Takeaway
Elixir changes the programming experience more than it changes the runtime model.
That is why migration cost stays low: your operational knowledge — observer,
crash dumps, :sys.get_state, distribution debugging — applies unchanged.
And when you later attach native runtimes (Part IV: XLA, MLX, llama.cpp),
they slot in beside the BEAM through Ports/NIFs, exactly as they would from
Erlang.
Explore More
- Compilation model notes — the abstract format your code becomes after parsing
Codemodule —compile_string,quoted_to_algebra; program the compiler yourself for a daymix xref— the full graph command reference behind §8.5’s recompilation management- BEAM module docs (
:code,:compile) — the Erlang-side view of the same pipeline - Erlang Efficiency Guide: modules and functions — where the Erlang compiler makes the same compile-time vs runtime calls, from the other direction
- Exercise idea: compile a tiny
.exby hand withelixirc, then inspect the.beamwithbeam_lib:chunks("Elixir.Hello.beam", [abstract_code])from an Erlang shell - Exercise idea: reproduce §8.5’s struct cascade yourself — write
Uwith a struct andVwith a%U{}pattern, add a field toU, and watch how many files recompile. Then delete the pattern and repeat.
Checkpoint
- Where do macros sit relative to type checking?
- Which extension would you give a one-off ops script? A library module?
- How can an Erlang shell call your Elixir module?
- Why does editing a struct’s
defstructforce recompilation of modules that merely pattern-match it? - Is
.exsinterpreted? If not, what actually differs from.ex? - Which directory does Mix generate rather than expect you to write, and
what does
consolidated/hold?
Answers
- Macros expand after parsing; type checking operates on expanded forms (Ch 07 diagnostics reference expanded call sites).
- Script:
.exs. Library module:.ex. - Add its
_build/<env>/lib/*/ebinto the path and call'Elixir.MyModule':fun(Args).from the Erlang shell (or:"Elixir.MyModule".fun(args)from Elixir). Quoting matters: bareHelloin an Erlang shell is a variable. %Struct{}patterns embed the field layout at each using module’s compile time (a compile-time dependency), so dependents must recompile to see the new layout. §8.5 measures it: adding a field recompiles both files; replacing the pattern with a plain remote call recompiles one.- No — it compiles to bytecode and runs it, just without writing the
.beam. A.exsinsidelib/is silently ignored bymix compile, which is the confusing symptom when a ported module never shows up inebin/. ebin/hello.app, generated frommix.exs— there is no.app.srcand nosrc/directory.consolidated/holds protocol dispatch tables built bymix compile(Ch 05), which is what turns protocol calls from dynamic lookups into static dispatch.
Next: Chapter 9 — Mix, Releases & Running OTP Apps
Chapter 9 — Mix, Releases & Running OTP Apps
Chapter 03 gave you daily-driver Mix: new, compile, test, format.
This chapter goes one level deeper — how Mix actually orchestrates the
compiler you met in Ch 08, how mix release assembles a self-contained OTP
release, and how to operate a live node: foreground, daemonized, remoted
into, upgraded while running.
Why this matters: everything here has an Erlang analogue — rebar3 profiles ↔ Mix environments,
sys.config↔runtime.exs,systools+release_handler↔mix releaseplus a hand-drivenrelease_handler. You are learning new names for machinery you already trust.One difference is worth naming before you need it: the
.appupfile is yours. rebar3 could generate relups from a callback module; Mix does not, because it cannot know what your processes should do with new state. Ch 09.8 is the chapter section where that bites.
9.1 What Mix Actually Does
Mix is an orchestrator, not a compiler. When you run mix compile, it:
- Loads and evaluates
mix.exs(it is ordinary Elixir code) - Resolves and fetches dependencies declared in
deps/0 - Compiles dependencies first, your app last
- Tracks per-file changes in manifests so only stale files recompile (the graph Ch 08 §8.5 describes)
- Consolidates protocols (Ch 05) so dispatch stops being dynamic — those
consolidated/*.beamfiles in the build tree are the artifact
flowchart TD
A["mix compile"] --> B["Evaluate mix.exs"]
B --> C["Resolve deps<br/>(Hex / git / path)"]
C --> D["Compile dependencies<br/>_build/dev/lib/<dep>/ebin/*.beam"]
D --> E["Compile your app<br/>.mix/compile.elixir manifests"]
E --> F["Write your .app<br/>ebin/my_app.app"]
F --> G["Consolidate protocols<br/>consolidated/*.beam"]
G --> H["_build/dev/lib/my_app/ebin/*.beam<br/>+ hello.app"]
(The .ez in older diagrams is Distillery’s archive format. Mix does not
produce archives — deps are plain directories with ebin/, the same shape
you get from rebar3. Ch 08 §8.1 shows the tree this produces.)
Everything lands in _build/<env>/ — the same shape as rebar3’s _build,
including the per-profile split you already know.
| Task | rebar3 world | Mix world |
|---|---|---|
| Profiles | {profiles, [...]} in rebar.config | Mix.env() + MIX_ENV |
| Hooks | {pre_hooks, ...} | compiler options, custom compilers |
| Plugins | rebar3 plugins | Mix tasks published to Hex |
| Locking | rebar.lock | mix.lock |
From Erlang you know: Mix evaluates
mix.exsat every invocation — it is a program, not a config file. Anything you can express in Elixir, you can express in your build. That is Ch 06’s metaprogramming paying off in your tooling.
9.2 Environments: MIX_ENV
Three environments, each a separate build universe:
| Env | Selected by | Used for | Config loaded |
|---|---|---|---|
:dev | default | everyday compile, iex -S mix | config/config.exs |
:test | mix test automatically | ExUnit runs | config/test.exs |
:prod | MIX_ENV=prod ... | releases | config/prod.exs + runtime.exs |
flowchart LR
CMD["your command"] --> Q{"MIX_ENV?"}
Q -->|"unset"| DEV[":dev<br/>_build/dev"]
Q -->|"mix test"| TST[":test<br/>_build/test"]
Q -->|"MIX_ENV=prod"| PRD[":prod<br/>_build/prod"]
DEV --> CFG["config/config.exs"]
TST --> CFG2["config/test.exs"]
PRD --> CFG3["config/prod.exs<br/>+ runtime.exs"]
Each environment compiles into its own _build/<env> tree — switching envs
never pollutes another build. start_permanent: Mix.env() == :prod in the
generated mix.exs is why dev nodes exit when the supervision tree stops
but prod nodes treat shutdown as fatal.
MIX_ENV Mechanics Worth Knowing
MIX_ENVselects the environment for that command only — no persisted state exists.mix compile && mix releasebuilds the second artifact unless you repeat the prefix on both commands.- Dependencies compile per environment:
_build/dev/lib/jasonand_build/prod/lib/jasonare separate artifacts, which is why switching envs recompiles dependencies the first time. Mix.env()is build-time-only — valid inmix.exs, config files, and module-attribute positions, never in code that ships.- Dev conveniences gate exactly like rebar3 profiles: check your
def projectfor what each env switches (start_permanent, compiler options, and friends).
$ mix compile # populates _build/dev/
$ MIX_ENV=prod mix compile # populates _build/prod/
$ ls _build # isolated build universes
dev prod
A bare
mix releasebuilds_build/**dev**/rel/...— the task does not select:prodfor you. Verified on 1.20.4. Always writeMIX_ENV=prod mix release. The other common slip compounds it: a Docker layer running plainmix deps.compilebefore settingMIX_ENV=prodcompiles everything twice and busts the cache.
9.3 Custom Tasks and Aliases
Mix tasks are just modules — behaviour + naming convention:
# lib/mix/tasks/hello.greet.ex — file location matters for discoverability
defmodule Mix.Tasks.Hello.Greet do
@shortdoc "Greets someone from the command line"
@moduledoc """
## Usage
mix hello.greet Ada
"""
use Mix.Task
@impl Mix.Task
def run(args) do
case args do
[name] -> Mix.shell().info("Hello, #{name}!")
_ -> Mix.raise("expected exactly one argument: mix hello.greet NAME")
end
end
end
$ mix hello.greet Ada
Hello, Ada!
$ mix hello.great Ada # typo → Mix suggests the closest task
** (Mix) The task "hello.great" could not be found. Did you mean "hello.greet"?
$ mix help hello.greet
mix hello.greet
There is no documentation for this task
All three outputs are real, which means the @shortdoc in the listing only
appears once you also ship a @moduledoc (as above) — mix help reads the
moduledoc, mix help listing reads the shortdoc. Worth knowing before you
assume your task is invisible for a mysterious reason.
Notes worth adopting immediately:
-
@shortdocputs the task in themix helptask list;@moduledocis whatmix help <task>prints -
@impl Mix.Taskcatches signature mistakes at compile time (Ch 05 habit) -
Mix.shell().info/1instead ofIO.putsso tests can capture output -
@requirements ["app.config"]makes a task depend on your application being configured beforerun/1fires; use"app.start"if it needs the supervision tree up. This is Mix’s plugin lifecycle:"app.config"runs your task after configuration,"app.start"after boot. A mistyped requirement fails loudly at the task level:$ mix n.app ** (Mix) The task "nosuchapp.start" could not be foundwhich is friendlier than the failure mode it replaces — a task that reads
Application.get_env/3, getsnil, and misbehaves somewhere unrelated.
Aliases chain existing tasks declaratively inside mix.exs:
defp aliases do
[
setup: ["deps.get", "compile"],
check: ["format --check-formatted", "credo", "test"]
]
end
Now mix setup and mix check work like little shell scripts — no plugin
needed.
9.4 Configuration: Compile-Time vs Runtime
Elixir splits configuration along the question “when is this value
evaluated?” — and getting this right is the single biggest config lesson
coming from sys.config:
| File | Evaluated | Can call System.get_env? | Typical content |
|---|---|---|---|
config/config.exs | during mix compile | yes, but value is frozen into the build | framework defaults |
config/prod.exs | during mix compile (prod) | same caveat | prod overrides |
config/runtime.exs | every time the release boots | yes — this is its purpose | secrets, hosts, pool sizes |
flowchart LR
subgraph CT["Compile time — frozen into .beam files"]
CE["config.exs<br/>evaluates once per build"]
CE --> BEAM["Application env baked in<br/>via compile_env"]
end
subgraph RT["Boot time — fresh every start"]
RE["runtime.exs<br/>evaluates on every boot"]
RE --> APPENV["Application.put_env<br/>before apps start"]
end
BUILD["mix release"] --> CT
START["bin/app start"] --> RT
# config/runtime.exs — evaluated at VM boot, every boot
import Config
if config_env() == :prod do
config :hello, Hello.Repo,
url: System.fetch_env!("DATABASE_URL"),
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
config :hello, port: String.to_integer(System.get_env("PORT") || "8080")
end
The ! vs non-! choice in that snippet is a policy decision, so know what
each buys:
System.get_env("PORT") #=> nil when unset
System.fetch_env!("PORT") #=> "8080", or raises:
# System.EnvError: could not fetch environment variable "PORT" because it is not set
fetch_env!/1 raising during boot is usually what you want for a value the
app cannot run without — it fails at deploy time with a clear message rather
than at the first request that needs the setting. Use get_env/2 (with a
default) for everything genuinely optional.
Reading values back follows one rule you should burn in:
# Library code — read at RUNTIME so consumers can configure after compiling:
def timeout, do: Application.get_env(:my_lib, :timeout, 5_000)
# Your own application — compile-time read is fine, you control the build:
@port Application.compile_env!(:hello, :port)
A module attribute reading Application.get_env/3 in a library silently
freezes the value at compile time — the classic “why is my config ignored”
bug. Libraries read lazily; applications may read eagerly.
From Erlang you know:
runtime.exsplays the rolesys.configplayed — environment values applied before applications boot.config.exsis the extra convenience layer Erlang never had: defaults resolved at build time so the release ships self-contained.
Tracing One Value Across All Four Layers
Follow pool_size from source to process:
| Stage | Where written | Evaluated | Value |
|---|---|---|---|
| Hard-coded default | in a module function | evaluated on each call | 10 |
| Build defaults | config/config.exs | once per build | pool_size: 10 |
| Env override | config/prod.exs | merged over defaults | pool_size: 20 |
| Runtime override | config/runtime.exs | every boot | from POOL_SIZE |
Later stages win. The first three are frozen into the release: Mix
evaluates them during assembly and writes the resulting terms into
releases/<vsn>/sys.config. Only the last stage runs on the target host —
which is why secrets belong exclusively there.
runtime.exs Internals: The Config Provider
runtime.exs is not special-cased by the VM. Mix ships it as a config
provider: a module implementing the Config.Provider behaviour,
registered per release, executed by the boot script after the VM starts
but before applications load. That timing is exactly why it may read env
vars or probe network services — and why a failure there prevents boot
rather than surfacing mid-request.
Register additional providers for richer sources:
# mix.exs — the releases key inside def project
[
releases: [
hello: [
config_providers: [{MyApp.EnvFileProvider, "/etc/hello/env"}]
]
]
]
# lib/my_app/env_file_provider.ex — evaluated on the target at boot
defmodule MyApp.EnvFileProvider do
@behaviour Config.Provider
@impl true
def init(path), do: path
@impl true
def load(config, path) do
vars =
path
|> File.read!()
|> String.split("\n", trim: true)
|> Map.new(fn kv ->
[k, v] = String.split(kv, "=", parts: 2)
{k, v}
end)
Config.Reader.merge(config,
hello: [
port: String.to_integer(vars["PORT"] || "4000"),
secret_key_base: Map.fetch!(vars, "SECRET_KEY_BASE")
]
)
end
end
init/1 runs at build time and its return value is serialized into
the release; load/2 receives that value on the target and returns the
merged configuration. Whatever Config.Reader.merge/2 can express lands
in application env before your supervision tree starts.
Evaluation Order and Branching
Config files are scripts evaluated top to bottom: later config
calls override earlier keys, import_config splices another file inline
at that point, and config_env() branches per environment inside one
file:
# config/config.exs — order is semantics:
import Config
config :hello, pool_size: 10 # base value
if config_env() == :test do # branch inside one file
config :hello, pool_size: 1
end
import_config "dev.secret.exs" # spliced HERE — overrides above
config :hello, pool_size: 5 # would override even the secret
Two habits prevent most config confusion: keep config.exs free of
machine-specific values (they freeze into every build), and never
import_config "runtime.exs" from a build-time file — it would evaluate
at assembly time, defeating its purpose entirely.
9.5 How mix release Assembles a Release
One command turns _build/prod into a self-contained, bootable OTP release:
flowchart TD
A["MIX_ENV=prod mix release"] --> B["Compile all deps + app<br/>in :prod"]
B --> C["Gather ERTS<br/>(include_erts: true default)"]
C --> D["Collect each dep as<br/>lib/name-vsn + ebin"]
D --> E["Render templates<br/>rel/env.sh.eex · rel/vm.args.eex"]
E --> F["Write boot scripts<br/>releases/vsn/start.boot + .rel"]
F --> G["Apply overlays<br/>(rel/overlays/**)"]
G --> H["Assembled tree<br/>(add the :tar step to also<br/>emit name-vsn.tar.gz)"]
The generated tree — annotated against what rebar3’s release gives you:
_build/prod/rel/hello/
├── bin/
│ └── hello ← control script: start/rpc/remote/stop...
│
├── erts-17.0.5/ ← private copy of the VM — no system install needed
│ (the number tracks OTP: 15.x = OTP 27,
│ 16.x = OTP 28, 17.x = OTP 29. Check
│ `:erlang.system_info(:otp_release)`.)
├── lib/
│ ├── hello-0.1.0/ebin/ ← your app, exactly an OTP app directory
│ ├── jason-1.4.4/ebin/
│ └── ... ← every dependency, vendored
├── releases/
│ ├── COOKIE ← distribution cookie (rotate via env var)
│ ├── start_erl.data ← pairs ERTS version ↔ release version
│ └── 0.1.0/
│ ├── hello.rel ← the .rel file you know from systools
│ ├── start.boot ← compiled boot script
│ ├── sys.config ← runtime.exs result, applied before boot
│ ├── env.sh ← rendered from rel/env.sh.eex
│ └── vm.args ← rendered from rel/vm.args.eex
└── tmp/ · tmp/log/ ← daemon scratch space + logs
By default mix release assembles this tree. Add the packaging step once in
mix.exs to also emit a deployable tarball:
[releases: [hello: [steps: [:assemble, :tar]]]]
# → _build/prod/hello-0.1.0.tar.gz
Customize the two .eex templates and they are re-rendered on every build:
# rel/vm.args.eex — raw Erlang flags, exactly like a rebar3 vm.args
+P 1000000 # max processes
+S 4:4 # scheduler threads : schedulers online
-heart
# rel/env.sh.eex — sourced before the VM starts, set RELEASE_* here
case "$RELEASE_MODE" in
daemon) export ELIXIR_ERL_OPTIONS="+MMscs 1024" ;;
esac
export RELEASE_DISTRIBUTION=name
export RELEASE_NODE="hello@$(hostname -s)"
Overlays: Shipping Extra Files Verbatim
Create rel/overlays/ and everything inside is copied to the release
root on every assemble — the declarative answer to “how do I ship a
systemd unit, a migrations folder, or a LICENSE alongside the VM?”:
rel/
├── env.sh.eex · vm.args.eex # templates, re-rendered each build
└── overlays/
├── etc/hello/sysctl.conf # → <release>/etc/hello/sysctl.conf
└── bin/migrate.sh # → <release>/bin/migrate.sh
Overlays apply last, so they can also overwrite generated files (a custom control wrapper, for instance). Because they are plain files, they diff cleanly in review — prefer an overlay over post-editing template output.
Stripping and Reproducibility
By default the release strips BEAM files (strip_beams: true),
removing debug-info chunks from shipped artifacts: smaller tarballs, at
the price of losing abstract_code reconstruction (Dialyzer against a
stripped release, some tracing tools). Keep chunks selectively:
[
releases: [
hello: [strip_beams: [keep: ["Docs", "Dbgi"]]]
]
]
Keeping only Docs drops Dbgi, and with it abstract_code — which means
no dbg call tracing, no Dialyzer PLT against these beams, and no readable
disassembly in production. Keeping both costs disk and buys you the ability to
debug a running node with the same tooling you use in dev. Strip aggressively
only once you have decided you will never need it.
For reproducible archives, SOURCE_DATE_EPOCH pins timestamps: identical
inputs plus the same epoch produce identical tarballs, making
checksum-based deploy verification meaningful.
Inspecting the Tarball Before It Ships
Five minutes with the archive teaches the boot model better than any diagram:
$ mkdir /tmp/inspect && tar xzf _build/prod/hello-0.1.0.tar.gz -C /tmp/inspect
$ cat /tmp/inspect/releases/start_erl.data
17.0.5 0.1.0 # ERTS version paired with release version
$ cat /tmp/inspect/releases/0.1.0/hello.rel
{release,{"hello","0.1.0"},
{erts,"17.0.5"},
[{kernel,"11.0.3",permanent},
{stdlib,"8.0.3",permanent},
{elixir,"1.20.4",permanent},
{sasl,"4.4",permanent},
{hello,"0.1.0",permanent},
{iex,"1.20.4",none},
{compiler,"10.0.3",permanent},
{logger,"1.20.4",permanent}]}.
$ cat /tmp/inspect/releases/0.1.0/sys.config
%% coding: utf-8
%% RUNTIME_CONFIG=false
[].
(Real output from mix release on Elixir 1.20.4 / OTP 29. Two things an
Erlang reader should notice: elixir appears in the .rel manifest, which
is how the boot script knows to start the Elixir application; and
sys.config is literally [] until your runtime.exs puts something in it —
the RUNTIME_CONFIG=false marker is how Mix distinguishes “no runtime config”
from “runtime config that happened to be empty.”)
The .rel file is the manifest you knew from systools: every
application, its version, its load type. During assembly Mix feeds it
through systools:script2boot to produce start.boot — the instruction
sequence erl -boot executes. start_erl.data exists so bin/hello can
pair the right private ERTS with the right release version.
9.6 Running the OTP App
The bin/hello script is a front-end over release_handler and plain
erl. Every subcommand maps to an operation you have typed by hand before:
| Command | What happens | Erlang equivalent |
|---|---|---|
bin/hello start | boot in foreground | erl -boot start |
bin/hello start_iex | boot in foreground with IEx attached | -remsh to self |
bin/hello daemon | background boot via run_erl, logs to tmp/log/ | run_erl |
bin/hello daemon_iex | daemon + IEx prompt on the tty | — |
bin/hello stop | graceful shutdown | init:stop() |
bin/hello restart | stop + start in one call | init:restart() |
bin/hello rpc "EXPR" | evaluate an expression on the running node | erl -remsh + call |
bin/hello remote | full remote IEx shell into the node | erl -remsh node |
bin/hello eval "EXPR" | boot a throwaway VM (no apps started), evaluate, exit | erl -eval |
bin/hello pid | print the running node’s OS PID | cat pipe/$FP |
bin/hello version | print release name/version about to boot | — |
That list is the complete set, printed by bin/hello with no arguments — the
one command worth typing first. Note what is absent: there is no ping
(that was Distillery’s, and :net_adm.ping/1 from rpc is the equivalent) and
no console; the interactive-shell commands are start_iex (boots a fresh
node) and remote (attaches to one already running).
There is deliberately no upgrade command — hot upgrades need your
.appup knowledge (§9.8), so Mix leaves driving release_handler to you.
MIX_ENV is not implied by the task. A bare mix release builds
_build/dev/rel/...; only MIX_ENV=prod mix release produces the prod tree.
Write the prefix every time — this is the single most common reason a release
behaves differently than expected, because dev and prod compile different
config/*.exs files and different dependency sets.
Environment variables steer behavior without editing files:
RELEASE_DISTRIBUTION=sname # default: short names, same host
RELEASE_DISTRIBUTION=name # longnames — required across hosts / for IPs
RELEASE_NODE=myapp@host1 # node identity when DISTRIBUTION=name
RELEASE_COOKIE=secret-from-vault # overrides releases/COOKIE
RELEASE_TMP=/mnt/ramdisk # where pipes/logs/tmp go
RELEASE_MODE=interactive # see §9.6's embedded-vs-interactive note
All of these are read by bin/hello itself, not by your application — the
control script is a readable shell file, so grep RELEASE_ bin/hello is a
legitimate debugging move. RELEASE_COOKIE is worth internalizing: line 29 of
the script is RELEASE_COOKIE="${RELEASE_COOKIE:-"$(cat "$RELEASE_ROOT/releases/COOKIE")"}",
so the generated cookie file is a default, and setting the env var is how you
supply a real secret instead.
Boot sequence, end to end:
flowchart TD
A["bin/hello start"] --> B["source env.sh<br/>(releases/0.1.0)"]
B --> C["exec erl -boot releases/0.1.0/start"]
C --> D["kernel loads apps in .rel order"]
D --> E["runtime.exs evaluated<br/>Application.put_env"]
E --> F["each app's mod:start/2 runs"]
F --> G["your supervision tree is up<br/>node is serving"]
Two operational habits from day one:
# Inspect a live daemon without attaching:
bin/hello rpc "Hello.Repo.aggregate(Hello.Accounts.User, :count)"
# Observer is a GUI: :observer.start() run via rpc opens it on the *server*,
# which on a headless host has no display. Instead, run observer locally and
# point it at the remote node:
# bin/hello remote # then, in that shell:
# :observer.start() # or start observer on your workstation and Node.connect/1
# The eval variant boots a THROWAWAY node — safe for migrations/cron:
bin/hello eval "Hello.Release.migrate()"
From Erlang you know:
rpc/remote/evalare the-remshand-evalworkflows you already run — Mix just wraps the plumbing (cookie, node name, boot flags) so the incantation is one word.
vm.args and ERL_FLAGS: Tuning the Emulator
vm.args.eex accepts any erl flag — the ones you have typed for years.
Start conservative; every line below is documented in erl(1):
### Capacity — raise before load tests hit defaults:
+P 2000000 # max processes
+Q 100000 # max ports
### Scheduler pressure — stop burning CPU on busy-wait while idle:
+sbwt none # none | very_short | short | medium | long | very_long
+sbwtdcpu none # dirty CPU schedulers, same scale
+sbwtdio none # dirty IO schedulers
### Distribution over IPv6-only networks:
-proto_dist inet6_tcp
(Old-timers’ +K true is gone from this list: kernel-poll is always on
where available on modern OTP, and the flag is a no-op.)
Flags also arrive through the environment, which beats rebuilding images
for experiments: ERL_FLAGS="+sbwt none" bin/hello console. Prefer
vm.args.eex for deliberate, versioned settings; ERL_FLAGS for
temporary probes.
RELEASE_MODE (default embedded) selects the code-loading mode from
Ch 08: embedded preloads modules at boot for faster, more predictable
startup; interactive loads on demand. Measure with your own workload —
the default suits the overwhelmingly common case.
9.7 Deploying Releases
A release directory is self-contained: copy it, run it. The VM travels
inside (erts-*), so targets need no Erlang installed — same OS family and
architecture is the only constraint.
Copy-the-folder (works everywhere):
MIX_ENV=prod mix release
rsync -a _build/prod/rel/hello/ host:/srv/hello/
ssh host '/srv/hello/bin/hello daemon'
Docker multi-stage (the common container shape):
# ---- build stage ----
# Pin a digest in production; the floating tag is fine for a guide.
FROM hexpm/elixir:1.20-erlang-28-debian-bookworm-slim AS build
RUN apt-get update -y && apt-get install -y build-essential git && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY mix.exs mix.lock ./
RUN mix local.rebar --force && mix local.hex --force
RUN MIX_ENV=prod mix deps.get
COPY config config
# deps.compile is here for layer caching, not because mix release needs it —
# mix release compiles the whole project anyway. The MIX_ENV prefix on every
# step is the point: deps.fetched/compiled per-env, and the deps.compile layer
# only invalidates when mix.lock or a dep's source changes.
RUN MIX_ENV=prod mix deps.compile
COPY lib lib
RUN MIX_ENV=prod mix release
# ---- runtime stage: no Elixir, no Hex, no build tools ----
FROM debian:bookworm-slim
RUN apt-get update -y && apt-get install -y libssl3 && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=build /app/_build/prod/rel/hello ./
ENV RELEASE_DISTRIBUTION=none PORT=8080
CMD ["/app/bin/hello", "start"]
Secrets come from the environment at boot through runtime.exs — the image
contains no credentials, matching twelve-factor expectations.
A Pre-Flight Checklist
Before the first real deploy, retire each assumption in the chain:
tar tzf hello-0.1.0.tar.gz | head # tarball exists and is shaped
file rel/hello/erts-*/bin/erlexec # ERTS matches the target arch
grep -r SECRET lib config rel # nothing baked in
RELEASE_DISTRIBUTION=name bin/hello daemon && sleep 2 && bin/hello ping
bin/hello rpc ":erlang.system_info(:otp_release)"
Packaging, architecture, hygiene, boot, and finally that the running node is the OTP release you built against — five commands, five retired assumptions.
9.8 Hot Code Upgrades — The Deep Dive
The capability Erlang made famous survives intact in Mix releases: installing
a new version without stopping the node. Be precise about what ships and
what doesn’t: Elixir’s release script has no upgrade command — but the
full OTP machinery underneath (release_handler, systools) is present in
every release, and Mix automates everything around it: packaging both
versions, boot scripts, and the rpc channel you drive it through. Only
relup generation and state-migration callbacks are left to you, because
only you know how your processes should migrate state.
One-time release configuration
# mix.exs — the releases key inside def project
[
releases: [
hello: [
applications: [sasl: :permanent], # release_handler lives in SASL
steps: [:assemble, :tar] # emit deployable tarballs
]
]
]
The four moving parts
| Piece | Role | Who provides it |
|---|---|---|
.appup file | per-app instructions: which modules to load, which processes to restart, which callback migrates state | you write it |
relup script | ordered, global instruction list across all apps | systools:make_relup derives it from the two .rel + .appup files |
| upgrade driver | drives release_handler on the target | you do — there is no bin/app upgrade; see below |
| state migration | code_change/3 callbacks, or supervised child restarts | you write it |
Walkthrough: hello 0.1.0 → 0.2.0, live
Suppose Hello.Counter (a GenServer holding {integer(), pid-history})
gains a :reason field. Version 0.1.0 is already running as a daemon.
1. Freeze the currently-deployed artifact:
MIX_ENV=prod mix release
cp _build/prod/hello-0.1.0.tar.gz /tmp/v1.tar.gz
2. Make the code change, then declare the migration in
priv/appups/hello.appup — plain Erlang terms, evaluated by systools:
%% priv/appups/hello.appup — instructions for upgrading hello itself
{"0.2.0",
[{"0.1.0",
%% High-level instructions. Valid forms are:
%% {load_module, Mod}
%% {load_module, Mod, DepMods}
%% {load_module, Mod, PrePurge, PostPurge, DepMods} %% 5-tuple
%% {update, Mod, ModType} ModType = soft | {advanced, Extra}
%% {update, Mod, ModType, Timeout}
%% {update, Mod, supervisor, ...}
%% {apply, {M,F,A}, PrePurge, PostPurge, DepMods}
%% Note there is no 3-tuple {load_module, Mod, Purge}: the third slot is
%% a dependency-module *list*, and purge strategies only appear in the
%% 5-tuple form.
[ {load_module, 'Elixir.Hello.Counter'},
{update, 'Elixir.Hello.Counter', {advanced, []}} ]}],
[{"0.1.0", []}] %% downgrade: no special instructions — modules are
%% loaded/purged in reverse; state migrations rarely
%% reverse cleanly, so decide explicitly
}.
To purge aggressively, use the 5-tuple explicitly:
{load_module, 'Elixir.Hello.Counter', brutal_purge, brutal_purge, []}
What those instructions mean:
{load_module, Mod}— load the new code for a module whose signatures did not change{update, Mod, {advanced, Extra}}— load new code and tell every process runningModas a behaviour to call itsMod:code_change(OldVsn, State, Extra)callback — your state migration hooksoft_purgewaits until no process still runs the old code;brutal_purgekills stragglers — choose honestly per module
3. Implement the migration hook on the GenServer:
defmodule Hello.Counter do
use GenServer
# ... start_link/handle_call as before ...
@doc "Called by release_handler mid-upgrade because of the {advanced, Extra}"
@impl true
def code_change(_old_vsn, count, _extra) when is_integer(count) do
{:ok, %{value: count, reason: :legacy_import}} # old state → new shape
end
end
4. Bump version in mix.exs to “0.2.0”, place the .appup where
systools will find it, and build:
MIX_ENV=prod mix compile
cp priv/appups/hello.appup _build/prod/lib/hello/ebin/
MIX_ENV=prod mix release
(In practice this becomes a tiny script or alias — the point is: the .appup
must exist as hello.appup inside lib/hello-0.2.0/ebin/ of the new
release.)
5. Derive the relup with the OTP tools, using both releases:
mkdir -p /tmp/upg/hello/{0.1.0,0.2.0}
cd /tmp/upg
tar xzf /tmp/v1.tar.gz -C hello/0.1.0
tar xzf <repo>/_build/prod/hello-0.2.0.tar.gz -C hello/0.2.0
erl -noshell -eval '
systools:make_relup("hello-0.2.0", ["hello-0.1.0"], [],
[{path, ["hello/0.2.0/releases/0.2.0",
"hello/0.1.0/releases/0.1.0",
"hello/0.2.0/lib/*/ebin",
"hello/0.1.0/lib/*/ebin"]}]),
halt().'
# → writes ./hello-0.2.0.relup
#
# Name gotcha: Name and UpFrom are *release file basenames*, not versions.
# systools looks for <Name>.rel; for a Mix release those are
# hello-0.2.0.rel and hello-0.1.0.rel under releases/<vsn>/. Adjust to your
# own releases/*/*.rel layout.
cp hello-0.2.0.relup hello/0.2.0/releases/0.2.0/relup
(cd hello/0.2.0 && tar czf /tmp/hello-0.2.0-upgrade.tar.gz .)
6. Install it on the live node by driving release_handler through the
rpc channel — three calls, exactly the classic sequence:
cp /tmp/hello-0.2.0-upgrade.tar.gz \
_build/prod/rel/hello/releases/hello_0.2.0.tar.gz # where release_handler looks
# Erlang's release_handler wants charlists (string()), not Elixir binaries —
# the ~c sigil keeps it a list. Plain "..." here is a badarg.
bin/hello rpc ':ok = elem(:release_handler.unpack_release(~c"hello_0.2.0"), 0)'
bin/hello rpc '{:ok, _old_vsn, _} = :release_handler.install_release(~c"0.2.0")'
bin/hello rpc ':ok = :release_handler.make_permanent(~c"0.2.0")'
bin/hello rpc "Hello.Counter.value()" # new code answering on the SAME node
Under the hood release_handler unpacked the tarball into releases/,
executed the relup instructions (suspending processes, swapping code,
running your code_change/3), and switched the running version — identical
to the classic install_release flow you know from LYSE. One safety net to
appreciate: if the node crashes between install and make_permanent, boot
falls back to 0.1.0 automatically. Permanence is your explicit, deliberate act.
Honest guidance
flowchart LR
CHANGE["What changed between versions?"] --> M1["Module body only,<br/>same signatures"]
CHANGE --> M2["Process state shape<br/>changed"]
CHANGE --> M3["Supervision structure,<br/>deps, or boot changed"]
M1 --> W1["{load_module, M}<br/>zero downtime"]
M2 --> W2["{update, M, {advanced, X}}<br/>code_change/3 runs"]
M3 --> W3["{update, M, supervisor}<br/>{restart_application, App}<br/>or restart_new_emulator"]
- Most teams today ship immutable images and restart. Hot upgrades remain genuinely valuable for: telecom-grade uptime, edge devices (Nerves) where downtime costs physical access, and fleets too large to bounce at once.
- The discipline cost is real: every released version’s tarball must be kept, appups maintained per transition, and state migrations tested. Budget for it explicitly or don’t promise it.
- Escape hatch:
restart_new_emulatorin the relup upgrades by rebooting the emulator under release_handler’s control — warm restart semantics with none of the per-module bookkeeping.
Suspend → Swap → Resume: The Minute Inside {update, advanced}
Worth knowing precisely what happens between your install_release call
and the moment new code answers — each step is observable and each can
hang:
sequenceDiagram
participant RH as release_handler
participant P as GenServer running Mod
participant SYS as sys / proc_lib
RH->>RH: load_object_code + load (new beam ready)
RH->>P: sys:suspend(P)
Note over P: non-system messages queue up<br/>process keeps its state
RH->>SYS: change_code(P, Mod, OldVsn, Extra)
SYS->>P: Mod:code_change(OldVsn, State, Extra)
P->>SYS: {:ok, NewState}
RH->>P: sys:resume(P)
Note over P: resumes the loop on NEW code<br/>old incarnation now unused
Three consequences practitioners hit:
- Suspension is cooperative — the process must reach its receive loop for system messages. A process stuck in a long computation delays the whole relup; watch process states while installing.
- Unsuspended processes keep old code — anything not mentioned in
the relup runs the old incarnation until its next fully qualified
call. That two-version window is why
soft_purgeexists. code_changemust be total — raising there crashes the process into its supervisor mid-upgrade. Validate old state defensively and fall back to sane defaults rather than letting it throw.
An Appup Instruction Field Guide
The appup cookbook (linked below) lists them all; these cover daily practice:
| Instruction | Effect | Typical trigger |
|---|---|---|
{load_module, M} | swap body, no callbacks | pure functions changed |
{load_module, M, PrePurge, PostPurge, DepMods} | swap with explicit purge + dependents | as above, needs stragglers killed |
{update, M, {advanced, X}} | swap; code_change/3 runs | state shape changed |
{update, M, supervisor} | swap; supervisor children restarted | child specs changed |
{restart_application, App} | restart a whole OTP application | app-level config changed |
{apply, {M, F, A}, PrePurge, PostPurge, DepMods} | call M:F(A) at that point | ETS migration, cleanup |
restart_new_emulator | reboot under the new ERTS | NIF ABI changed |
Note there is no {restart, [M]} high-level instruction. Restarting a module’s
processes is expressed as {update, M, supervisor}, and restarting a whole
application as {restart_application, App}.
Downgrade entries mirror upgrades; if you provide none, make_relup
derives the reverse from symmetric instructions automatically — but state
migrations rarely reverse cleanly, so decide explicitly.
Practice Loops That Keep Relups Honest
- Script relup derivation and installation end to end — a relup you have never executed is a rumor, not a capability.
- Run the full install against production-shaped data in CI; assert on migrated state, not just exit codes.
- Keep every released tarball addressable by version;
install_releaseneeds the previous release present. - Rehearse failure: interrupt between unpack and permanent, confirm boot
rolls back, then clean the half-installed version out of
releases/.
From Erlang you know: this whole section is
systools:make_relup,release_handler:unpack/install_release, and.appupsemantics you may have lived through before. Mix changes the packaging and the wrapper script; the upgrade engine is the same battle-tested OTP machinery.
9.9 Step-by-Step Exercise
mix new opsbox --sup; add@max_workersmodule attribute and a supervised GenServer that stores the boot timestamp.- Write
mix opsbox.snapshotprinting the stored timestamp (@requirements ["app.start"]). - Move
:portand:greetingintoconfig/runtime.exs, read from env vars with defaults; prove they change per boot without rebuilding. MIX_ENV=prod mix release; rundaemon, thenrpca snapshot, thenstop. Confirmtmp/log/captured the run.- Bonus (the §9.8 muscle memory): bump to 0.2.0 adding one field to the
GenServer state; produce the
.appup, derive therelup, and install it into the still-running 0.1.0 daemon.
Checkpoint
- Which config file may safely call
System.fetch_env!/1, and when is it evaluated? - Why must libraries avoid reading app env in module attributes?
- What does
bin/hello evaldo differently frombin/hello rpc? - Which piece of a hot upgrade does Mix not generate, and why?
- What is the difference between
soft_purgeandbrutal_purge?
Answers
config/runtime.exs— evaluated at every VM boot, before applications start, so values come fresh from the environment.- Module attributes freeze the value at the library’s compile time;
consumers configuring afterwards see stale values. Read lazily via
Application.get_env/3instead. rpcconnects to an already-running node and evaluates there;evalboots a temporary throwaway node, evaluates, and exits — safe for migrations and cron-style jobs.- The
relupscript (and the.appupinputs to it) — only you know how your processes should migrate state;systools:make_relupderives the script from your appup plus the two.relfiles. Mix also ships noupgradewrapper command: you driverelease_handlerviarpc. soft_purgedelays the instruction until no process still executes the old code;brutal_purgekills any remaining old-code holders. Soft is safer, brutal always proceeds.
Explore More
- Mix.Release guide — Deployments, hot code upgrades, config providers — the authoritative reference this chapter follows
- OTP: Creating and Upgrading a Target System —
the machinery
release_handlerimplements; read after §9.8 - .appup cookbook — instruction recipes for every upgrade shape you’ll encounter
- Learn You Some Erlang, ch. “Upgrading” — the classic narrative walk
through relups and
code_change Config.Provider— load runtime config from vaults/JSON/K8s at boot- Experiment: set
RELEASE_MODE=interactivevs defaultembeddedand timebin/hello eval "1+1"cold-boot differences
Next: Chapter 10 — Phoenix & LiveView
Chapter 10 — Phoenix & LiveView
Phoenix is the flagship of the Web domain — and for Erlang developers it is the most natural fit in the ecosystem: its real-time model maps directly onto BEAM concepts you already use.
The chapter’s core claim, proven below: LiveView is a GenServer whose mailbox receives DOM events and whose “reply” is a diffed UI update.
10.1 The Architecture Is OTP
flowchart TD
PHX["Phoenix"] --> LV["LiveView"]
PHX --> CH["Channels"]
PHX --> PS["PubSub"]
LV --> P["BEAM processes"]
CH --> P
PS --> P
P --> S["Stateful"]
P --> C["Concurrent"]
P --> I["Isolated<br/>fault-tolerant"]
LiveView, Channels, and PubSub are thin layers over processes. The three properties at the bottom come from the runtime, not framework code.
Stateful
Each browser tab gets a dedicated LiveView process:
flowchart TD
B["Browser"] <-->|"WebSocket"| LVP["LiveView process"]
LVP --> ST["state (assigns)"]
LVP --> TM["timers (:timer.send_interval)"]
LVP --> SUB["subscriptions (Phoenix.PubSub)"]
LVP --> EV["UI events (handle_event)"]
You don’t reconstruct application state from every HTTP request. The state lives in the process — exactly like a GenServer’s loop data. Refresh the page and the process dies; that’s your “session” boundary, enforced by the VM rather than by cookies.
Concurrent
flowchart TD
BEAM["BEAM scheduler pool"] --> UA["User A → LiveView process"]
BEAM --> UB["User B → LiveView process"]
BEAM --> UC["User C → LiveView process"]
BEAM --> ROOM["Chat room → GenServer"]
BEAM --> PRESENCE["Presence → :pg / Phoenix.Presence"]
BEAM --> NOTIF["Notifications → GenServer"]
One process per connection. The scheduler spreads millions of them across all cores preemptively. No event loop that one slow handler can block — a slow user’s render cannot stall another user’s events, because they aren’t sharing a thread.
Fault Tolerant (Isolated)
flowchart LR
CRASH["process crashes"] --> EXIT["supervisor notices<br/>(:EXIT message)"]
EXIT --> RESTART["process restarted<br/>(per restart strategy)"]
RESTART --> OK["system continues<br/>— other users untouched"]
If one user’s connection crashes, only that process restarts under
Phoenix.Endpoint’s supervision — everyone else is untouched. This is your
let-it-crash philosophy with a browser attached.
Distributed
flowchart LR
NA["Node A"] <--> PUBSUB["Phoenix.PubSub<br/>(Erlang distribution)"]
NB["Node B"] <--> PUBSUB
NC["Node C"] <--> PUBSUB
Phoenix.PubSub broadcasts across nodes via standard Erlang distribution.
No Redis, no external message bus needed for cluster-wide real-time. Your
net_kernel knowledge transfers directly — same cookie, same connect calls.
Where the Processes Live
Two facts worth having on hand when something misbehaves:
- Your LiveView module runs in its own process, spawned per tab beneath the endpoint’s supervision. Crash it and the client reconnects and remounts fresh; the transport and every other user survive untouched.
- PubSub rides on
:pg— Erlang process groups, OTP 23+. Presence (§10.5) layers replica-consistent metadata on exactly that machinery.
The raw Erlang baseline shows what you stop maintaining. With
cowboy_websocket you own the registry, heartbeat, and fan-out yourself:
%% you track peers, pings, and broadcasts by hand:
websocket_handle({text, Msg}, State) ->
ring_broadcast(peers(), Msg), % your own registry walk
{ok, State}.
Phoenix hands you the registry (PubSub.subscribe/2), the heartbeat, the
diffing, and recovery — all as ordinary supervised processes you can find
in Observer.
10.2 Stateless Web vs LiveView
Traditional: every request pays deserialize → authorize → fetch state → compute → serialize, with state parked in DB/Redis/session store.
sequenceDiagram
participant Br as Browser
participant Ct as Controller (stateless)
participant St as DB / Cache / Redis
Br->>Ct: HTTP request
Ct->>St: fetch session/state
St-->>Ct: state
Ct-->>Br: response (state rebuilt every time)
LiveView: persistent connection; state lives with the process; events are messages; workers and other nodes are just more processes.
flowchart TD
BR["Browser"] <-->|"WebSocket (persistent)"| LVP["LiveView process<br/>assigns · timers · subscriptions · handle_event"]
LVP -->|"BEAM messages"| PS["PubSub<br/>other nodes"]
LVP -->|"BEAM messages"| WK["Workers<br/>background jobs"]
The performance consequence: after mount/3, event handling costs no HTTP
round trip and no state reconstruction — you’re just sending a message to a
process that already holds everything it needs.
Assigns Diffing: What Actually Crosses the Wire
After each event, LiveView re-renders your template against the new assigns and compares with the last result. Only changed fragments travel:
- HEEx compiles templates into static chunks (sent once per page load) and dynamic holes (functions of assigns).
- After
handle_event/3returns, the new render fills the holes; the runtime diffs hole-by-hole. - Only indices whose values changed serialize into the message — typically tens of bytes rather than an HTML document.
Rendering cost therefore lives in your process and scales with what
changed, not what the page contains. Two disciplines follow directly:
keep socket.assigns minimal (every assign participates in diffing), and
never park large blobs there — streams (§10.5) and external processes are
the right homes for collections and heavy data.
10.3 How Phoenix Generates HTML
Templates in Phoenix are not parsed at request time. Every
.html.heex file is compiled to an ordinary Elixir function at build
time — the same transformation your Erlang knowledge would predict for
any serious template system: partial evaluation into code that builds
iodata. (If you ever used erlydtl, which compiles Django templates to
Erlang modules, you already hold the mental model.)
The full path of a request’s HTML
flowchart LR
R["Plug router"] --> C["Controller action<br/>assigns data"]
C --> RD["render(conn, :show, ...)<br/>dispatches by format"]
RD --> T["Compiled template fn<br/>assigns → iodata"]
T --> L["Layout component<br/>wraps content"]
L --> P["Plug.Conn response<br/>iodata → socket"]
- The controller puts data into
conn.assigns. render/3looks up the compiled template for the format. Phoenix 1.7+ takes an atom (render(conn, :show, user: user)) and resolves the template module from the controller; the older string formrender(conn, "show.html")is pre-1.7 and you will not meet it in new Phoenix apps.- The template function takes the assigns and returns
iodata— nested lists of binaries, the same structure asio_lib:format/2output. - The layout wraps it;
Plug.Connsends the iodata straight to the socket without flattening.
EEx vs HEEx
EEx (.html.eex) | HEEx (.html.heex) | |
|---|---|---|
| What it is | Template literal with <%= %> holes | EEx + HTML-aware compiler |
| HTML validation | none — output is a string soup | tags/attributes validated at compile time |
| Components | partials via string rendering | function components <.my_component /> |
| Escaping | manual html_escape | automatic — values are escaped unless wrapped in raw/1 |
HEEx knows HTML syntax. That single fact buys three things: malformed
markup fails at compile time; every interpolated value is escaped by
default (XSS safety is the default, not a discipline); and tags can
compile to function components — any def component(assigns) in a
module becomes reusable markup invoked as <.component attr={value} />.
What a template compiles to
A template like this:
<section id={@id}>
<h1>{@title}</h1>
<p :for={item <- @items}>{item.name}</p>
</section>
compiles (conceptually — the real code is expanded by macros at compile time) into something shaped like:
def render(assigns) do
[
"<section id=\"",
Phoenix.HTML.safe_to_string(to_safe(assigns.id)),
"\">\n <h1>",
Phoenix.HTML.safe_to_string(to_safe(assigns.title)),
"</h1>\n",
Enum.map(assigns.items, fn item ->
["<p>", Phoenix.HTML.safe_to_string(to_safe(item.name)), "</p>"]
end),
"</section>"
]
end
Three properties fall out of this shape:
- Rendering is just building a list. No interpreter walks a DOM; the template is the code, and the BEAM compiles it like any other.
- Static parts are binaries evaluated once per call — which is what LiveView exploits for diffing (§10.2): the static chunks are shared, only the dynamic holes re-evaluate.
- Escaping is inline and unconditional — each hole passes through
Phoenix.HTMLsafe conversion, so injecting<script>in@titlerenders literal text.
From Erlang you know
| Erlang world | Phoenix world |
|---|---|
erlydtl compiling Django templates to modules | HEEx compiling templates to Elixir functions |
io_lib:format/2 → iodata | every render returns iodata |
xmerl structural checks | HEEx compile-time tag/attribute validation |
| manual escaping before output | automatic Phoenix.HTML safe conversion |
Where LiveView fits
render/1 in a LiveView uses the same HEEx compiler — the only
difference is the caller: a controller renders once per request, a
LiveView re-renders per event into the diffing pipeline of §10.2.
Components (<.component />) work identically in both, which is why the
generated mix phx.new --live app shares one CoreComponents module
between controller views and LiveViews.
10.4 The Minimal Mental Model
A LiveView is a GenServer whose “messages” include DOM events and whose “reply” is a diffed UI update:
# Conceptual model:
state = %{users_online: 42}
event = {:user_joined, "alice"}
case event do
{:user_joined, _user} -> %{state | users_online: state.users_online + 1}
end
# receive event → update state → render changes
Real LiveViews add handle_event/3, handle_info/2, and assign/3 — but
the loop shape is gen_server:handle_call with rendering attached. If you
can write the GenServer above from memory (you can), you understand LiveView.
The Lifecycle in Callback Terms
The full callback surface, mapped to what each message means:
| Callback | Fires when | GenServer analogue |
|---|---|---|
mount/3 | connection established; again on reconnect | init/1 |
render/1 | after any state change | reply, rendered |
handle_event/3 | DOM event arrives | handle_call from a browser |
handle_info/2 | any BEAM message | handle_info |
handle_params/3 | URL params change | handle_call variant |
terminate/2 | process exits | best-effort cleanup |
terminate/2 deserves the caution flag it gets in Ch 23: it is not
reliable unless the process has Process.flag(:trap_exit, true) set. A
LiveView killed by the supervisor’s brutal_kill, or any untrapped exit,
skips it entirely. Put anything that must happen on a schedule or in a
DynamicSupervisor, not in terminate/2.
One click, end to end:
sequenceDiagram
participant Br as Browser
participant LVP as LiveView process
Br->>LVP: phx-click="inc"
LVP->>LVP: handle_event → assign(count + 1)
LVP-->>Br: diff {count: 41} — changed holes only
Note over Br: DOM patched in place,<br/>no page reload
Note that mount/3 runs twice per tab: once during the initial HTTP render
(connected?(socket) is false) and once when the WebSocket connects. Timers
and subscriptions belong behind the connected?/1 check so static HTML
generation stays side-effect free.
10.5 Step-by-Step: First Real-Time App
mix phx.new realtime_demo --live # generates app + LiveView setup
cd realtime_demo
mix ecto.create && mix ecto.migrate # optional if you keep the DB (Ch 11)
mix phx.server # http://localhost:4000
The generated app is a textbook OTP release: RealtimeDemo.Application
starts Telemetry → PubSub → Endpoint under one supervisor. Open Observer
(:observer.start() in iex -S mix phx.server) and find the LiveView
process appear/disappear as you open and close browser tabs. Watching that
correlation once teaches more than any diagram.
Add a cluster-wide broadcast in two lines:
use YourAppWeb, :live_viewin any LiveView module.Phoenix.PubSub.subscribe(YourApp.PubSub, "room")inmount/3(behindconnected?/1).- Broadcast from anywhere:
Phoenix.PubSub.broadcast(YourApp.PubSub, "room", {:user_joined, user}). Every connected tab receives it inhandle_info/2.
That is PubSub — fire-and-forget, no state. When you also want who is
connected (counts, join/leave diffs, deduplicated rejoins), that is
Phoenix.Presence, which is a CRDT-backed wrapper on the same PubSub topic:
# application.ex — Presence must be supervised, after PubSub, before Endpoint
children = [
{Phoenix.PubSub, name: YourApp.PubSub},
YourAppWeb.Presence, # the `use Phoenix.Presence` module
YourAppWeb.Endpoint
]
# LiveView
def mount(_params, _session, socket) do
if connected?(socket) do
YourAppWeb.Presence.track(self(), "room", socket.id, %{online_at: System.system_time(:second)})
end
{:ok, assign(socket, :room, "room")}
end
def handle_info(%Phoenix.Socket.Broadcast{event: "presence_diff"}, socket) do
{:noreply, assign(socket, :users, YourAppWeb.Presence.list("room"))}
end
Distinguish the two directions before you build on them: push_event/3 goes
server → a specific browser’s JS (it is a client-side hook, not a cluster
message), while Phoenix.PubSub.broadcast/3 goes node → node and lands in
handle_info/2.
Background work from a LiveView uses supervised tasks — never bare spawn. The
Task.Supervisor has to be in the tree first:
# application.ex
children = [
RealtimeDemo.Repo,
{Task.Supervisor, name: RealtimeDemo.TaskSup}, # required
{Phoenix.PubSub, name: RealtimeDemo.PubSub},
RealtimeDemoWeb.Endpoint
]
Then, in the LiveView. Note the task receives a user_id, not
socket.assigns.user: the socket is LiveView-shaped state and has no business
crossing into a worker process.
def handle_event("export", %{"user_id" => user_id}, socket) do
task = Task.Supervisor.async_nolink(RealtimeDemo.TaskSup, fn ->
HeavyExport.run(user_id)
end)
{:noreply, assign(socket, :export_task, task)}
end
def handle_info({ref, :ok}, %{assigns: %{export_task: %Task{ref: ^ref}}} = socket) do
Process.demonitor(ref, [:flush]) # normal-task result arrives twice
{:noreply, put_flash(socket, :info, "Export finished")}
end
def handle_info({:DOWN, ref, :process, _, reason},
%{assigns: %{export_task: %Task{ref: ^ref}}} = socket) do
{:noreply, put_flash(socket, :error, "Export failed: #{inspect(reason)}")}
end
Two details that are load-bearing:
- The
:DOWNclause matches the ref againstsocket.assigns.export_task. A catch-alldef handle_info({:DOWN, _ref, ...}, socket)fires for every monitor this process happens to hold — including Phoenix’s own — and will report someone else’s crash as your export failing. async_nolinkmeans a crashing export does NOT crash the user’s LiveView; the crash arrives as a:DOWNmessage you choose how to handle.
No client framework, no separate websocket server — the supervision tree handles lifecycle.
Streams: Large Collections Without Assign Bloat
The old habit — stuffing thousands of rows into assigns — costs memory twice: in your process and in client-side bookkeeping. Streams fix both ends with per-item operations that bypass regular assigns entirely:
# Load a page, not the table. `stream/3` still materializes whatever you hand
# it, so 50_000 rows here would still be 50_000 rows in the LiveView process.
def mount(_params, _session, socket) do
{:ok, stream(socket, :logs, Logs.recent(200))}
end
def handle_info({:new_log, log}, socket) do
{:noreply, stream_insert(socket, :logs, log, at: 0)}
end
<tbody id="logs" phx-update="stream">
<tr :for={{id, log} <- @streams.logs} id={id}>
<td>{log.level}</td>
<td>{log.message}</td>
</tr>
</tbody>
(HEEx prefers {...} interpolation, but it is EEx-based and <%= ... %>
still compiles inside a .heex template; new code uses {}.)
(Stream items render as {id, item} pairs and each DOM node must carry
the matching id attribute — LiveView raises on a stream container whose
children lack ids.)
One lifecycle rule to internalize: a stream is rebuilt from scratch on every
mount. Navigate away and back, and your placeholder rows are gone until
mount/3 loads again. Any cursor, filter, or scroll position you want to
survive a remount has to be in the URL params or session and reapplied in
mount/3 — streams buy you efficient updates, not persistent state.
Properties worth internalizing:
- Streamed items never enter
socket.assigns— server memory stays O(batch), not O(collection). stream_insert/4withat: 0prepends; the client moves one DOM node instead of re-rendering the list.- Streams reset on remount. They are view state, not truth — reload from
source in
mount/3.
Rule of thumb: assigns for scalar and summary state; streams for collections the user scrolls.
10.6 Why This Wins for Real-Time Workloads
| Property | Why It Matters |
|---|---|
| Stateful | Connection state lives with the process |
| Concurrent | Connections naturally isolated |
| Fault tolerant | Supervisors restart failed components |
| Distributed | BEAM nodes coordinate across cluster |
| Real-time | WebSockets/Channels/PubSub first-class |
| Observable | Telemetry + process introspection |
| Composable | Plug/PubSub/behaviours assemble cleanly |
Natural fits: chat & messaging, collaborative docs/whiteboards, multiplayer, live dashboards (trading/sports), location tracking, notifications, IoT control planes.
Phoenix isn’t just a web framework that added WebSockets. It is a web architecture built on a runtime whose fundamental abstraction is already concurrent, stateful, isolated processes.
10.7 Telemetry: Watching the Machine Think
Phoenix emits :telemetry events at every interesting boundary — the same
instrumentation convention you know from OTP libraries that wrap logger:
| Event | What it measures |
|---|---|
[:phoenix, :endpoint, :stop] | full request duration |
[:phoenix, :live_view, :mount, :stop] | time to first render per tab |
[:phoenix, :live_view, :handle_event, :stop] | event handling latency |
(LiveView events are span-style: each has :start and :stop variants —
attach to the :stop event to read its duration measurement.)
Attaching a handler is plain function registration:
:telemetry.attach(
"lv-event-log",
[:phoenix, :live_view, :handle_event, :stop],
fn _event, measurements, metadata, _config ->
# duration is in NATIVE time units, not milliseconds. Log raw
# `measurements.duration` and it looks like a huge number.
ms = System.convert_time_unit(measurements.duration, :native, :microsecond)
Logger.debug("#{metadata.event} handled in #{ms}µs")
end,
%{}
)
That :native is a general telemetry fact, not a Phoenix quirk: every
duration in every :telemetry.span/3 is in native units until you convert.
Logging it raw is the single most common telemetry bug.
In production, Telemetry.Metrics aggregates the same events into console,
StatsD, or Prometheus reporters — metrics without an agent process invented
by you. Combined with Observer (§10.5) you get both micro views (one
process) and macro views (fleet-wide rates) on day one.
Phoenix 1.7–1.8 specifics an Erlang reader will trip on
Four things a 1.5-era tutorial would have taught you that are now different:
| Old | Current |
|---|---|
| Cowboy as the endpoint server | Bandit (1.7+ default) |
render(conn, "show.html") | render(conn, :show, assigns) |
| string paths for links | verified routes — ~p"/users/#{user}" |
| hand-rolled auth | mix phx.gen.auth |
Verified routes are the one worth adopting immediately: ~p returns a
*path* at compile time, so a renamed route is a compile error rather than a
404 in production. The compiler parses the sigil, so you get route existence
and path-param count checked at compile time; query strings are URL-encoded
and interpolated safely.
# verified
<%= link "Edit", to: ~p"/users/#{@user}/edit" %>
<.button navigate={~p"/users"}>All users</.button>
# unverified — still legal, still a runtime 404 if the route moved
<%= link "Edit", to: "/users/#{@user}/edit" %>
Auth is one command: mix phx.gen.auth Accounts User users generates
sign-up, log-in, log-out, password reset, and confirmation-email flows
against Accounts, plus a live_session block in the router that enforces
authentication in on_mount — which is the LiveView-native way to guard a
LiveView, and where Ch 27’s live_session explanation becomes load-bearing.
Explore More
- Phoenix guides — start with “Request lifecycle” then “Channels”
- LiveView docs — the assign/ handle_event lifecycle diagram is worth printing
- Presence guide — CRDT-based presence built on PubSub; zero extra infra
- Exercise idea: build the presence demo from §10.5, then kill a node
(
kill -9the daemon!) and watch Presence update across survivors — fault tolerance as a spectator sport
Checkpoint
- What plays the role of GenServer state in a LiveView?
- How does an event reach LiveViews on other nodes?
- What happens to other users when one user’s LiveView crashes?
- Why
Task.Supervisor.async_nolinkinstead of plainTask.asyncinsidehandle_event/3?
Answers
socket.assigns— updated viaassign/3; persisted across events for the connection’s lifetime.Phoenix.PubSub.broadcast/3over Erlang distribution; subscribers’handle_info/2fires locally on each node.- Only their own process restarts per the supervision strategy; others are unaffected.
Task.async/1links the task to the caller — a crash would take down the user’s whole LiveView.nolinkisolates failures while still delivering results/:DOWNmessages.
Next: Chapter 11 — Ecto: The Data Layer
Chapter 11 — Ecto: The Data Layer
Ecto is the persistence toolkit of the Elixir world — and for an Erlang developer it is refreshingly familiar in spirit: no hidden magic, no identity map tracking your objects behind your back. Ecto is explicit. Data goes in as plain structs, changes are validated through visible pipelines, and every query is a value you can build, inspect, and compose.
This chapter takes you from “what is a changeset?” to confidently designing a data layer the way Phoenix applications do.
11.1 Why Ecto Is Not an ORM
Classic ORMs tangle three concerns into one object: shape, validation, and persistence. Ecto splits them into three explicit pieces:
flowchart LR
subgraph ECTO["Ecto's explicit split"]
SC["Schema<br/>plain struct + fields<br/>knows nothing about the DB"]
CS["Changeset<br/>cast → validate → constrain<br/>a value you can inspect"]
RP["Repo<br/>the ONLY door to the DB<br/>every call is explicit"]
end
SC --> CS --> RP
| Piece | Role | Erlang analogue |
|---|---|---|
| Schema | Struct + field declarations | record definition (-record(user, {...})) |
| Changeset | Validation/casting pipeline | hand-written validate/1 functions |
| Repo | Boundary module to the database | your mnesia/odbc wrapper module |
Why this matters in practice:
- Your schema struct is just data. You can create one without a database, serialize it, pattern-match it, send it between processes — like any term.
- Validation never touches the DB implicitly. You decide when constraints are checked.
- Every DB call reads
Repo.something(...)at the call site. Grep your code forRepo.and you have found every place that talks to storage — the same audit propertymnesia:transactioncall sites give you.
From Erlang you know: if you have ever wrapped Mnesia access behind a module so callers couldn’t leak table names everywhere, you already think in contexts-and-repos. Ecto formalizes exactly that discipline.
11.2 Setting Up: The Repo Lives in Your Supervision Tree
The Repo is an OTP process (a pool of DB connections, actually). It belongs in your application’s supervision tree — which you can now read fluently after Ch 05:
defmodule Hello.Application do
use Application
@impl true
def start(_type, _args) do
children = [
Hello.Repo, # ← connection pool + query runner
{Phoenix.PubSub, name: Hello.PubSub}
# ...
]
Supervisor.start_link(children, strategy: :one_for_one, name: Hello.Supervisor)
end
end
Configuration points at the database through config/runtime.exs:
# config/runtime.exs
import Config
if config_env() == :prod do
config :hello, Hello.Repo,
url: System.fetch_env!("DATABASE_URL"), # postgres://user:pass@host/db
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
end
flowchart TD
APP["Hello.Application"] --> SUP["Hello.Supervisor"]
SUP --> REPO["Hello.Repo<br/>(DBConnection pool)"]
REPO --> C1["connection proc"]
REPO --> C2["connection proc"]
REPO --> C3["connection proc"]
C1 --> PG[("PostgreSQL")]
Each connection is its own supervised process — a network blip kills a connection, not your application; the pool restarts it while everything else keeps serving. This is Ch 01’s fault isolation applied to your data layer.
Adapters do the talking: PostgreSQL via postgrex, MySQL via myxql,
SQLite via exqlite. Your domain code stays identical across all of them.
Inside the Pool: DBConnection Checkout Mechanics
Hello.Repo delegates to DBConnection: a query waits for a free
connection from the pool, holds it for exactly one round trip, then returns
it. The mechanics explain the two errors you’ll meet in production:
** (DBConnection.ConnectionError) connection not available and request was
dropped from the queue after 5000ms
- Queue timeout: concurrent demand exceeded
pool_sizefor longer than:queue_target/:queue_intervalallow. Raisingpool_sizeonly helps if Postgres can take it; otherwise find the hot query. - Ownership error in tests: a process tried to use a connection checked out by another process (see §11.8).
Sizing rule of thumb: cores × 2, plus headroom for background work, capped
by Postgres max_connections minus room for other clients. The pool is
itself a supervised tree — inspect it with :sys.get_state(MyApp.Repo) or
watch checkouts live in Observer.
11.3 Schemas: Structs With Database Mapping
A schema is Ch 02’s struct plus a mapping to table columns:
defmodule MyApp.Accounts.User do
use Ecto.Schema # injects schema DSL + primary key handling
import Ecto.Changeset # the validation functions we'll use below
schema "users" do # ← table name ("users" in the DB)
field :name, :string # column :name, TEXT NOT NULL? no —
field :email, :string # nullability is YOUR choice below
field :age, :integer
has_many :posts, MyApp.Blog.Post # association: users.id = posts.user_id
timestamps() # inserted_at / updated_at columns
end
# The changeset function lives HERE, next to the shape it validates.
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email, :age]) # whitelist what may change
|> validate_required([:name, :email]) # must be present after cast
|> validate_format(:email, ~r/@/) # local checks run immediately…
|> validate_number(:age, greater_than: 0)
|> unique_constraint(:email) # …DB checks run at insert time
end
end
Reading guide, line by line:
use Ecto.Schemagives youschema/2, defines__schema__metadata, and makes%User{}a struct with a default primary key:idfielddeclares both the struct key and the column type — the type drives casting (see next section) and SQL generationvirtual: truefields exist on the struct but have no column — handy for form inputs like password confirmationhas_manydoes not load anything by itself. It only declares how to find related rows when you explicitly ask (§11.5 preloads)
You can also define schemas without a table (embedded_schema) — plain
validated structs for forms, API payloads, config. Same changeset machinery,
no database involved.
11.4 Changesets: Validation as a Visible Pipeline
The changeset is where Ecto differs most sharply from ORM habits. A
changeset is itself a value — a %Changeset{} struct accumulating
changes, errors, and metadata as it flows through pure functions:
flowchart TD
IN["attrs from outside<br/>(untrusted: params, JSON, forms)"] --> CAST
subgraph PIPE["one changeset pipeline"]
CAST["cast/3<br/>whitelist keys + type-coerce"] --> V1["validate_required/2"]
V1 --> V2["validate_format · validate_length · …<br/>instant, in-memory checks"]
V2 --> UC["unique_constraint/2<br/>DECLARED here…"]
end
UC --> REPO["Repo.insert/1"]
REPO --> DBCHK["…EXECUTED there:<br/>DB uniqueness check inside<br/>the same transaction"]
DBCHK -->|"ok"| OK["{:ok, %User{}}"]
DBCHK -->|"violation"| ERR["{:error, %Changeset{errors: [email: {#quot;has already been taken#quot;, ...}]}}"]
V2 -->|"invalid"| INVALID["{:error, %Changeset{}}<br/>never hits the DB"]
Watch one flow end-to-end in IEx:
iex> alias MyApp.Accounts.User
iex> cs = User.changeset(%User{}, %{name: "Ada", email: "not-an-email", age: -3})
iex> cs.valid?
false
iex> Keyword.get(cs.errors, :age)
{"must be greater than %{number}",
[validation: :number, kind: :greater_than, number: 0]}
# cast silently DROPPED unlisted keys — the whitelist is the security boundary:
iex> cs = User.changeset(%User{}, %{name: "Ada", admin: true})
iex> cs.changes
%{name: "Ada"} # ← `admin` was discarded, not stored
The two-phase validation rule (skill worth internalizing):
| Check type | Runs when | Examples |
|---|---|---|
| Validation | immediately, in memory | validate_required, validate_length, validate_format, validate_inclusion |
| Constraint | at the DB, inside the insert/update transaction | unique_constraint, foreign_key_constraint, check_constraint |
Anything the database knows better than your process (uniqueness, foreign keys, race conditions) belongs in a constraint. Anything you can check without the DB belongs in a validator. Mixing these up produces either TOCTOU bugs or pointless round-trips.
Composing Changeset Functions Like Any Pipeline
Because changesets are values, validation logic composes the way your
hand-written validate/1 chains do in Erlang — small named stages threaded
with |>:
defmodule MyApp.Accounts.User do
import Ecto.Changeset
def registration_changeset(user, attrs) do
user
|> cast(attrs, [:email, :password])
|> validate_required([:email, :password])
|> validate_length(:password, min: 12)
|> validate_confirmation(:password, required: true)
|> put_password_hash()
end
defp put_password_hash(cs) do
if cs.valid?,
do: put_change(cs, :password_hash,
Bcrypt.hash_pwd_salt(get_change(cs, :password))),
else: cs
end
end
(put_password_hash/1 only fires when every prior validator passed — and
Bcrypt.hash_pwd_salt/1 comes from bcrypt_elixir.)
The verification side has a security requirement that is easy to miss, because it looks like an optimization rather than a defense:
def valid_password?(%User{password_hash: hash}, password)
when is_binary(hash) and byte_size(password) > 0 do
Bcrypt.verify_pass(password, hash)
end
def valid_password?(_, _) do
# Runs the same bcrypt work against a dummy hash, so a missing user takes
# the same time as a wrong password — otherwise response latency
# enumerates your accounts.
Bcrypt.no_user_verify()
false
end
Without that second clause, “user not found” returns in microseconds and “wrong
password” takes ~100ms of bcrypt work. The timing difference is a
user-enumeration oracle, which is why no_user_verify/0 exists.
Custom rules are one-function validators: read the change, return the changeset or attach an error.
def validate_adult(changeset, field) do
case get_change(changeset, field) do
age when is_integer(age) and age < 18 ->
add_error(changeset, field, "must be 18 or older")
_ ->
changeset
end
end
# usage: |> validate_adult(:age)
#=> {:error, cs} with Keyword.get(cs.errors, :age)
#=> {"must be 18 or older", []}
For display, walk cs.errors yourself or use traverse_errors/2, which
recurses into nested association changesets — the shape Phoenix forms expect.
Why Uniqueness Lives at the Database: A Race Walkthrough
Two processes registering "ada@example.com" simultaneously:
- Both run
validate_formatetc. — pass; nothing is taken yet. - Both
SELECTfor an existing email — neither finds one. - Both
INSERT. Without a DB-level guarantee, both succeed.
unique_constraint(:email) makes step 3 the arbiter: the unique index
admits one insert, the loser’s transaction aborts with a constraint
violation, and Repo translates it into {:error, %Changeset{errors: [email: {"has already been taken", ...}]}}. Check and write share one
transaction — there is no window between “looked fine” and “written”.
11.5 Queries Are Values
Queries compose as ordinary data structures before ever touching a wire:
import Ecto.Query
# keyword syntax — reads like SQL, compiles to a query struct
base =
from u in User,
where: u.age >= 18,
select: {u.id, u.name}
# compose incrementally — each step returns a NEW query value
prefix = "ada"
adults_named = from u in base, where: ilike(u.name, ^"%#{prefix}%")
MyApp.Repo.all(adults_named)
Two portability notes: ilike/2 compiles on Postgres only — MySQL and
SQLite need like/2 with manual case folding. And never interpolate raw
user input into the pattern: "%#{prefix}%" lets a % or _ from the user
widen the match. Escape them:
prefix = prefix |> String.replace(["%", "_"], fn c -> "\\#{c}" end)
from u in User, where: ilike(u.name, ^"%#{prefix}%")
The ^ pin operator binds runtime values safely — parameterized under
the hood, immune to injection, exactly like prepared-statement placeholders
in odbc:
min = 18
from u in User, where: u.age >= ^min
# SELECT u.id, ... FROM users AS u WHERE u.age >= $1 [$1 = 18]
Macro syntax for dynamic composition — filters stack because queries are values:
def search(opts) do
User
|> where([u], u.age >= ^(opts[:min_age] || 0))
|> then(fn q -> if opts[:verified], do: where(q, [u], u.verified), else: q end)
|> limit(^(opts[:limit] || 20)) # ← the pin matters here
|> MyApp.Repo.all()
end
Every value crossing into the query needs ^. limit(opts[:limit] || 20)
without the pin is not “unpinned dynamic value” — it is an
Ecto.Query.CompileError at compile time, because the macro would otherwise
treat the map access as query AST rather than as a parameter.
Dynamic, Subqueries, and Window Functions
When even conditional composition gets unwieldy, build WHERE clauses at
runtime with Ecto.Dynamic:
filters =
Enum.reduce(opts, dynamic(true), fn
{:min_age, age}, dyn -> dynamic([u], u.age >= ^age and ^dyn)
{:verified, true}, dyn -> dynamic([u], u.verified and ^dyn)
_, dyn -> dyn
end)
MyApp.Repo.all(from u in User, where: ^filters)
Subqueries nest like values because they are values — pass one anywhere a queryable fits:
top_posts =
from p in Post,
select: %{id: p.id},
order_by: [desc: p.view_count],
limit: 10
MyApp.Repo.all(from p in Post, join: t in subquery(top_posts), on: p.id == t.id)
Window functions arrive via windows: plus over/2 — e.g. ranking users by
post count without leaving the DSL. And when SQL is genuinely clearer,
fragment/1 escapes raw SQL inline; ^ pins stay parameterized inside it.
Preloads and the N+1 Trap
Associations never load implicitly. This is deliberate — and it prevents the classic N+1 accident:
posts = Repo.all(Post) # 1 query
Enum.map(posts, & &1.author) # author NOT loaded — each access returns
# %Ecto.Association.NotLoaded{} (a marker
# struct, not data — and not an error yet)
# Explicit preload: 2 queries total, regardless of post count:
posts = Repo.all(from p in Post, preload: :author)
# Or join-based, single query:
Repo.all(from p in Post, join: a in assoc(p, :author), preload: [author: a])
flowchart LR
BAD["loop over 100 posts<br/>each calls fetch_author"] ===|">100 queries"| TRAP["N+1 trap<br/>(ORMs hide this;<br/>Ecto makes it impossible by default)"]
GOOD["preload: :author<br/>once"] ---|">exactly 2 queries"| OK["constant query count"]
Six More Calls You Will Need Immediately
These are the ones every Erlang dev reaches for and then has to look up:
# nested writes — insert/update parent and children in one transaction
Repo.transaction(fn ->
post = Repo.insert!(post_changeset)
Repo.insert_all!(Tag, tags_for(post))
end)
# cast_assoc vs put_assoc: cast_* takes user params through the changeset
# (validated); put_* takes already-built structs (trusted).
# cast_assoc(changeset, :comments, params) # validate
# put_assoc(changeset, :comments, [%Comment{}]) # insert as-is
# enum-typed field, validated against the DB's CREATE TYPE
field :status, Ecto.Enum, values: [:draft, :published, :archived]
# streaming a large table without holding it all in memory
Repo.transaction(fn ->
Repo.stream(query, max_rows: 10_000) |> Enum.each(&process/1)
end)
# row lock inside a transaction — SELECT ... FOR UPDATE
Repo.transaction(fn ->
{:ok, account} = Repo.one(from a in Account, where: a.id == ^id, lock: "FOR UPDATE")
Repo.update!(account_changeset)
end)
# ask the planner what it will actually do (Postgres/MySQL)
{result, _} = Repo.with_log(fn -> Repo.all(query) end)
Repo.transaction/1 is a function with a real transaction around it, so
Repo.stream and lock: only behave as documented inside one — outside, each
Repo.* call is its own implicit transaction on a pooled connection. That is
also why a stream outside a transaction can hand you two different
connection snapshots.
Many-to-Many with join_through
Posts ↔ tags is the canonical shape — and note you own the join schema:
defmodule MyApp.Blog.PostTag do
use Ecto.Schema
schema "posts_tags" do
belongs_to :post, MyApp.Blog.Post
belongs_to :tag, MyApp.Blog.Tag
timestamps()
end
end
defmodule MyApp.Blog.Post do
use Ecto.Schema
schema "posts" do
field :title, :string
many_to_many :tags, MyApp.Blog.Tag, join_through: MyApp.Blog.PostTag
timestamps()
end
end
Reading stays declarative — one extra batched query per hop:
MyApp.Repo.all(from p in Post, preload: [:author, :tags])
# SELECT ... FROM posts;
# SELECT ... FROM authors WHERE id IN (...);
# SELECT ... FROM tags JOIN posts_tags ON tags.id = posts_tags.tag_id
Writing associates through explicit join rows via put_assoc/2:
post
|> MyApp.Repo.preload(:tags)
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(:tags, [existing_tag, %Tag{name: "beam"}])
|> MyApp.Repo.update()
Mnesia veterans will recognize the discipline: no implicit link traversal — every hop across tables appears in the code.
Write-side helpers mirror read-side explicitness: Repo.insert(cs),
Repo.update(cs), Repo.delete(user), and Ecto.Multi for multi-step
transactions you compose and inspect like any pipeline (see Explore More).
11.6 Migrations Ship With Mix
Schema evolution is versioned, reviewable Elixir:
mix ecto.gen.migration add_users
# → priv/repo/migrations/20260825120000_add_users.exs
defmodule Hello.Repo.Migrations.AddUsers do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string, null: false
add :email, :string, null: false
add :age, :integer
timestamps()
end
create unique_index(:users, [:email]) # backs unique_constraint above!
end
end
mix ecto.create # create the database itself
mix ecto.migrate # apply pending migrations, tracked in schema_migrations
mix ecto.rollback # revert last migration (change/1 runs in reverse)
mix ecto.migrations # show applied/pending status
Note the pairing: unique_constraint(:email) in the changeset works only
because unique_index(:users, [:email]) exists in a migration. Declare the
constraint without the index and nothing fails loudly — duplicates simply
insert and your “uniqueness” silently protects nothing. The changeset
declaration is a translator for a database error; no index means no error
to translate.
Upserts: on_conflict
Insert-or-update races dissolve into one statement — SQL ON CONFLICT,
expressed as options:
# create-or-increment a counter row, atomically:
MyApp.Repo.insert!(
%Counter{slug: "hits", count: 1},
on_conflict: [inc: [count: 1]],
conflict_target: :slug
)
# simplest valid form — SET a column to a literal value:
MyApp.Repo.insert(changeset, on_conflict: [set: [name: "unknown"]],
conflict_target: :email)
# read-back variant — return the surviving row:
{:ok, user} =
MyApp.Repo.insert(changeset,
on_conflict: {:replace, [:name, :updated_at]},
conflict_target: :email,
returning: true
)
:on_conflict accepts :raise, :nothing, {:replace, fields}, a keyword
list of update instructions such as [set: …] or [inc: …], or an
Ecto.Query built with update:. The keyword form covers simple updates;
reach for the query form when the update needs more than a single
instruction. All of it executes in the same statement — the
compare-and-swap your Mnesia transactions did by hand, delegated to the
database where it belongs.
conflict_target must match a unique index (see unique_index/3 above).
Without one the database raises a constraint error rather than taking the
branch you intended.
Data Migrations Are Separate Beasts
Once tables settle, backfills get their own versioned modules — and their own reversibility decisions:
defmodule Hello.Repo.Migrations.BackfillUserSlugs do
use Ecto.Migration
def up do
execute """
UPDATE users
SET slug = lower(regexp_replace(name, '\\s', '-', 'g'))
WHERE slug IS NULL
"""
end
def down, do: :ok # backfills are usually irreversible by design
end
Rule of thumb: DDL goes in change/1 (auto-reversible), bulk data in
up/0/down/0. Large backfills belong in batches or Oban jobs (Ch 13) —
not one giant UPDATE holding locks for minutes.
Runnable note: want to try the full round-trip right now? In Livebook:
Mix.install([{:ecto_sql, "~> 3.12"}, {:exqlite, "~> 0.16"}])
Define a Repo and run a migration. The exqlite adapter takes a filename,
not a URL — ":memory:" is the whole value:
defmodule MyApp.Repo do use Ecto.Repo, otp_app: :my_app, adapter: Ecto.Adapters.SQLite3 end # config/config.exs (Livebook: Config.put/3 or a config.exs) config :my_app, MyApp.Repo, database: ":memory:" {:ok, pid} = MyApp.Repo.start_link() Ecto.Migrator.run(MyApp.Repo, [{1, "create users", fn repo -> Ecto.Adapters.SQL.query!(repo, "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)") end}], :up, all: true, log: false)That is the complete throwaway database: an adapter module, a config key, a started Repo, and a migration.
11.7 Contexts: The Public API of Your Domain
Phoenix’s architectural convention (and a good one even without Phoenix):
never call Repo or build queries outside context modules. Controllers,
LiveViews, workers — everyone talks to a context’s public functions:
defmodule MyApp.Accounts do
@moduledoc "Public API for user accounts."
alias MyApp.Accounts.User
alias MyApp.Repo
@doc "Registers a user; returns {:ok, user} or {:error, changeset}."
def register_user(attrs) do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
end
@doc "Fetches a verified user by email."
@spec get_verified_user_by_email(String.t()) :: {:ok, User.t()} | {:error, :not_found}
def get_verified_user_by_email(email) do
case Repo.one(from u in User, where: u.email == ^email and u.verified) do
nil -> {:error, :not_found}
user -> {:ok, user}
end
end
end
Benefits you’ll recognize from good Erlang module design:
- Callers depend on intent (
Accounts.register_user/1), not table shapes - Swapping storage details never ripples beyond the context
- The context is the natural seam for authorization, telemetry, caching
Ecto.Multi: Transactions You Can Inspect Before Running
Ecto.Multi is to transactions what pipelines are to data: a named,
ordered, inspectable value. Nothing executes until Repo.transaction:
alias Ecto.Multi
Multi.new()
|> Multi.insert(:user, User.changeset(%User{}, attrs))
|> Multi.run(:prefs, fn repo, %{user: user} ->
repo.insert(Preference.changeset(%Preference{}, %{user_id: user.id}))
end)
|> Multi.run(:audit, fn _repo, %{user: user} ->
# non-bang: a bang version raises, which aborts the caller's process and
# loses the {:error, step, value} naming that Multi exists to give you
AuditLog.record("signup", user.id)
end)
|> MyApp.Repo.transaction()
#=> {:ok, %{user: %User{}, prefs: %Preference{}, audit: %AuditLog{}}}
# any step failing rolls back everything and names the culprit:
#=> {:error, :prefs, %Ecto.Changeset{}, %{user: %User{}}}
Because a Multi is data, you can unit-test the steps dry, append steps
conditionally before execution, and log the exact plan — compositional
control your mnesia:transaction(fun) closures never had.
11.8 Testing: Sandbox Mode Explained
ExUnit + Ecto give transactional test isolation using the database’s own mechanism:
defmodule MyApp.AccountsTest do
use ExUnit.Case, async: true # tests run CONCURRENTLY
alias MyApp.{Accounts, Repo}
setup do
# Checks out a connection and opens a transaction for this test:
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Repo, shared: not is_nil(System.get_env("CI")))
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
:ok
end
test "registers with valid attrs" do
assert {:ok, %User{id: id}} = Accounts.register_user(%{
"name" => "Ada", "email" => "ada@example.com"
})
# No account is verified by registration, so this returns :not_found —
# which is the assertion you want. Flip it to {:ok, _} only after adding
# a verification step to the context.
assert {:error, :not_found} = Accounts.get_verified_user_by_email("ada@example.com")
assert {:ok, %User{id: ^id}} = Accounts.get_user_by_email("ada@example.com")
end
test "rejects duplicate email" do
attrs = %{"name" => "A", "email" => "dup@example.com"}
assert {:ok, _} = Accounts.register_user(attrs)
assert {:error, %Ecto.Changeset{}} = Accounts.register_user(attrs)
end
end
What actually happens:
sequenceDiagram
participant T as Test process
participant POOL as Repo pool
participant DB as PostgreSQL
T->>POOL: start_owner! (checkout connection)
POOL->>DB: BEGIN
Note over T,DB: test body — all inserts happen<br/>inside this transaction
T->>POOL: stop_owner (on_exit)
POOL->>DB: ROLLBACK
Note over DB: zero residue — other tests<br/>never saw this data
Because isolation comes from transactions (not truncation), tests are fast
and async: true scales across cores — BEAM concurrency applied to your
test suite. One caveat to respect: code that spawns unsupervised processes
inside tests must share ownership explicitly, which is why generated apps
enable pool: Ecto.Adapters.SQL.Sandbox in config/test.exs.
Ownership Deep Dive: Who May Touch Which Connection
The sandbox enforces one rule: only the owning process may use checked-out
connections. start_owner! checks out a connection, opens a transaction,
and returns an owner pid; processes in that test’s ancestry share it. The
classic failure modes map directly:
| Symptom | Cause | Fix |
|---|---|---|
cannot find ownership process | spawned Task hits the Repo | grant access with Sandbox.allow/3 |
| Passes alone, fails in suite | data leaked across async tests | unique emails per test |
| Nested Task hangs | child waits on parent’s connection | allow before spawning |
The signature is Sandbox.allow(repo, parent, allow, opts \\ []) — the
repo comes first, and allow is the pid being granted access:
# in the parent test process, BEFORE spawning:
Ecto.Adapters.SQL.Sandbox.allow(MyApp.Repo, self(), worker_pid)
allow/3 is allow/4 with an empty opts list; parent must already have
checked out a connection or you get :not_found. That ordering rule is the
whole reason for the “allow before spawning” row in the table — explicit
capability passing, familiar discipline from Erlang process bookkeeping.
Non-async suites skip all of this and call
Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, {:shared, self()}) in
test_helper.exs, sharing the owner with every process of that test.
11.9 From Erlang You Know: Ecto ↔ Mnesia
| Concern | Mnesia habit | Ecto equivalent |
|---|---|---|
| Schema definition | record + mnesia:create_table | schema + migration |
| Transaction | mnesia:transaction/1 | implicit per Repo.* call; Ecto.Multi for composed ones |
| Consistency checks | hand-written guards | changeset validators + DB constraints |
| Cross-node | distributed tables | rely on Postgres replication |
| Dirty reads | dirty_read/1 (fast, unsafe) | no direct equivalent — issue raw SQL, and understand you have left Ecto’s guarantees |
| Isolation levels | mnesia:activity/3 kind (transaction vs dirty) | Repo.transaction/2, isolation: :serializable etc. — set explicitly, same idea |
Mnesia stays available from Elixir (:mnesia...) — some systems pair both:
Mnesia for hot ephemeral state, Ecto/Postgres for durable relational data.
Explore More
- Ecto guides — the four-book series: Getting Started, Changesets, Querying, Multi
Ecto.Multi— compose transactions as inspectable pipelines; the answer to “how do I do several writes atomically”Ecto.QueryAPI — window functions, CTEs, fragments for the escape hatches- SQL Sandbox docs —
ownership modes explained (
shared, manual, auto) - Exercise idea: port one of your Mnesia tables to Ecto + SQLite in a Livebook, keeping the accessor signatures identical — feel where the changeset boundary adds value
Checkpoint
- Which Ecto piece validates input before it reaches your schema struct?
- Why does
cast/3dropping unknown keys matter for security? - What is the difference between
validate_required/2andunique_constraint/2in terms of when they run? - How many queries does
preload: :authorissue for 100 posts? - What makes sandbox-mode tests safe to run with
async: true?
Answers
- The changeset (
cast/3+ validators); the schema stays a plain struct. - Whitelisting means untrusted input cannot set privileged fields (like an
adminflag) no matter what keys attackers submit — mass-assignment is structurally impossible. - Validators run immediately in memory during the pipeline; constraints are declared in the changeset but executed by the database inside the insert/update transaction — catching races the validators can’t.
- Two: one for posts, one batched fetch of all referenced authors.
- Each test owns a connection running inside a transaction that is rolled back on exit, so concurrent tests see isolated snapshots of the DB.
Next: Chapter 12 — Ash: Declarative Domain Modeling
Chapter 12 — Ash: Declarative Domain Modeling
Ecto (Ch 11) gives you explicit building blocks: you write schemas, changesets, context functions, and authorization by hand. Ash raises the abstraction one level: you declare what your resources are and what actions exist on them; the interfaces, validations, authorization, and even API layers are generated from those declarations.
For an Erlang developer this is a familiar trade in new clothes — like moving
from hand-rolled gen_server boilerplate to use GenServer, but applied to
your entire domain model.
12.1 Declarative vs Imperative: Seeing the Difference
The same “register a user” feature, written twice:
Imperative (Ecto + context) — you write how:
defmodule MyApp.Accounts do
alias MyApp.Accounts.{User, Repo}
import Ecto.Changeset
def register(attrs) do
%User{}
|> cast(attrs, [:name, :email])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> unique_constraint(:email)
|> Repo.insert()
end
def get_user!(id), do: Repo.get!(User, id)
def list_users, do: Repo.all(User)
def delete_user(user), do: Repo.delete(user)
end
Declarative (Ash) — you declare what, Ash derives how:
defmodule MyApp.Accounts.User do
use Ash.Resource,
domain: MyApp.Accounts,
data_layer: Ash.DataLayer.Ets # storage is ONE LINE of config (§12.4)
attributes do
uuid_primary_key :id
attribute :name, :string, allow_nil?: false
attribute :email, :ci_string, allow_nil?: false # case-insensitive type!
timestamps()
end
actions do
defaults [:read, :destroy] # standard read/destroy derived for you
create :register do # a NAMED business action, not generic CRUD
accept [:name, :email]
validate attribute_does_not_equal(:name, "admin")
end
end
code_interface do # generates the public functions
define :register, args: [:name, :email]
define :by_id, action: :read, get_by: [:id] # → User.by_id(id), single record
end
end
Usage reads like calling a context function — because it generated one:
MyApp.Accounts.User.register!("Alice", "alice@example.com")
# → %MyApp.Accounts.User{id: "0b8f…", name: "Alice", email: "alice@example.com"}
# get_by actions return a tagged tuple. Non-bang → {:ok, record} or
# {:error, %Ash.Error.Query.NotFound{}}; bang → record, raising when absent.
{:ok, user} = MyApp.Accounts.User.by_id("0b8f…")
user = MyApp.Accounts.User.by_id!("0b8f…")
Not every generated function follows the bang convention: by_id/1 is
generated from get_by:, and its return shape is {:ok, record} or
{:error, %Ash.Error.Query.NotFound{}} rather than a bare record or nil.
That is a deliberate Ash design choice (every
action has an explicit success/error contract), but it is the thing that trips
Ecto developers moving over — Repo.get/2 returns a bare record or nil,
User.by_id/1 does not.
flowchart TD
subgraph IMP["Imperative stack (hand-written per resource)"]
direction TB
H1["changeset function"] --> H2["context functions"] --> H3["authorization checks"] --> H4["API serialization"]
end
subgraph DEC["Ash stack (written once, derived per declaration)"]
direction TB
D1["Resource declarations<br/>attributes · actions · policies"] --> E1["validations"]
D1 --> E2["code interface"]
D1 --> E3["policy enforcement"]
D1 --> E4["JSON:API / GraphQL / forms"]
end
The payoff compounds with scale: every additional resource reuses the machinery; every cross-cutting concern (auth, audit, pagination) is written once in the framework instead of once-per-resource in your contexts.
Naming note: this chapter reuses
MyApp.Accountsfrom Ch 11, where it was a hand-written Ecto context. It is a different design, not an evolution of the same module. Pick one per app — Ash domains and Ecto contexts are alternatives, not layers to stack. (Ch 12 §12.7 covers the legitimate hybrid: Ash for the core domain, raw Ecto queries for analytics.)
12.2 Anatomy of a Resource
Every Ash resource is built from four declaration blocks. Learn these four and you can read any Ash application:
Attributes — what the data looks like
attributes do
uuid_primary_key :id # auto-generated UUID v7 primary key
attribute :title, :string do
allow_nil? false
constraints [max_length: 200] # type-level constraints, validated for you
end
attribute :status, :atom do
constraints [one_of: [:draft, :published, :archived]]
default :draft
end
attribute :view_count, :integer, default: 0
timestamps()
end
Rich built-in types (:ci_string, :date, :decimal, NewType for your
own) replace whole categories of hand-written validators.
Actions — what you can do
Actions are named business operations, not generic CRUD:
actions do
defaults [:read, :destroy]
read :published do
filter expr(status == :published)
pagination keyset?: true, default_limit: 25
end
create :publish_draft do
accept [:title]
change set_attribute(:status, :published)
end
update :increment_views do
accept []
change atomic_update(:view_count, expr(view_count + 1)) # race-free at the DB
end
end
Note what disappeared compared to the imperative version: no manual changeset function, no context wrapper — accept lists, changes, and validations are data about the action, and Ash builds the pipeline from them.
Arguments, Preparations, and Change Modules
Actions accept typed arguments — inputs that need not map to columns:
create :sign_up do
accept [:email]
argument :display_name, :string, allow_nil?: false
change set_attribute(:name, expr(arg(:display_name)))
validate matching(:name, ~r/^[A-Z]/) # args validated too — via the
end # attribute they populate
Read-side shaping goes in prepare — a hook that runs before the data layer:
read :with_comments do
prepare build(load: [:comments], sort: [inserted_at: :desc])
end
When logic outgrows builtins, promote it to a module implementing the
Ash.Resource.Change behaviour — the same move as extracting a plug in
Phoenix:
defmodule MyApp.Changes.Titleize do
use Ash.Resource.Change
@impl true
def change(changeset, _opts, _ctx) do
case Ash.Changeset.fetch_change(changeset, :name) do
{:ok, name} ->
Ash.Changeset.force_change_attribute(
changeset,
:name,
String.capitalize(name)
)
:error ->
changeset
end
end
end
# attach with: change {MyApp.Changes.Titleize}
Error Shapes: Ash Errors vs Changesets
Action failures don’t return changesets — they return error class structs, stable across data layers:
# Actions run through a changeset. Two ways to invoke one:
#
# 1. Ash.create/3 directly — works for any resource, no code_interface needed
User
|> Ash.Changeset.for_create(:register, %{name: "Ada", email: "nope"})
|> Ash.create(domain: MyApp.Accounts)
# 2. the generated code_interface function (from `code_interface` above)
MyApp.Accounts.User.register("Ada", "nope")
case MyApp.Accounts.User.register("Ada", "nope") do
{:ok, user} ->
user
{:error, %Ash.Error.Invalid{errors: errors}} ->
Enum.map(errors, &Exception.message/1)
#=> ["attribute email is invalid"] (rendered human messages)
{:error, %Ash.Error.Forbidden{}} ->
raise "policy denied — see §12.5"
end
| Class | Meaning | Closest Ecto analogue |
|---|---|---|
Invalid | validation/constraint failed | {:error, changeset} |
Forbidden | a policy denied the request | hand-raised in context code |
Framework / Unknown | bugs, storage failures | raised exceptions |
Code that matched on %Ecto.Changeset{} must match on Ash.Error.*
instead; Exception.message/1 flattens the nested errors for display.
Relationships & calculations
relationships do
belongs_to :author, MyApp.Blog.Author
has_many :comments, MyApp.Blog.Comment
end
calculations do
calculate :comment_count, :integer, expr(count(comments))
calculate :summary, :string, expr(fragment("left(?, 80)", body))
end
Calculations are expressions the data layer executes — loaded on demand via
Ash.load!(post, :comment_count), never implicit queries.
Loading is explicit, like Ecto preloads (Ch 11 §11.5), but declarative:
require Ash.Query
[post] =
MyApp.Blog.Post
|> Ash.Query.load([:comment_count, author: [:profile]])
|> Ash.read!(domain: MyApp.Blog)
12.3 Domains: Grouping Resources Behind One Interface
Resources register themselves with a domain module — the boundary other code talks to:
defmodule MyApp.Accounts do
use Ash.Domain,
extensions: []
resources do
resource MyApp.Accounts.User
resource MyApp.Accounts.Token
end
end
Domains do not auto-generate generic create/2 or read/1 functions.
A domain is a registry plus config — otp_app, allowed resources, and the
Ash.Domain callbacks. The functions you call come from either the
resource’s code_interface:
# generated on the RESOURCE, not the domain:
MyApp.Accounts.User.register!("Ada", "ada@x.io")
# or Ash.create/3 / Ash.read!/2 with the domain named explicitly:
User
|> Ash.Changeset.for_create(:register, %{name: "Ada", email: "ada@x.io"})
|> Ash.create!(domain: MyApp.Accounts)
This is Ash’s answer to Phoenix’s context convention (Ch 11 §11.7): one
explicit door per bounded context — except the door is generated, so it
can’t drift out of sync with what resources actually support. Note the
module the functions land on: the resource, since code_interface is a
resource-level block.
12.4 Data Layers: Swap Storage Without Rewriting the Domain
The headline feature for Erlang developers. The resource above declared
data_layer: Ash.DataLayer.Ets. Every declaration-driven behavior works
identically when you switch:
| Data layer | Package | Storage | Use it for |
|---|---|---|---|
Ash.DataLayer.Ets | ash | in-memory ETS tables | tests, prototypes |
AshSqlite.DataLayer | ash_sqlite | SQLite | the useful stepping stone from ETS |
AshPostgres.DataLayer | ash_postgres | PostgreSQL | production durability |
Ash.DataLayer.Mnesia | ash | Mnesia (!) | documented as extremely unoptimized — fine for tests, not throughput |
AshCsv.DataLayer | ash_csv | CSV files | fixtures, tiny tools |
“Works identically” means your declarations do not change — not that every feature is equivalent. Capabilities differ per layer, and the ones that bite:
atomic_update(used by counter-style actions) needs a data layer that implements atomics — the ETS, SQLite and Postgres layers do; not all do.:ci_stringis backed by a realcitextcolumn only on Postgres; ETS stores it in memory asAsh.CiString. Case-insensitive query semantics differ per backend.- Keyset (cursor) pagination is not universally available.
- Filter pushdown and index usage are entirely the backend’s business.
The realistic path is ETS (fast tests, zero setup) → SQLite (real SQL semantics, real migrations, still trivial to run) → Postgres. Jumping straight from ETS to Postgres means your test suite never exercises the query dialect you deploy on.
flowchart LR
RES["MyApp.Accounts.User<br/>declarations unchanged"] --> IFACE["same actions,<br/>policies, interfaces"]
IFACE --> A["ETS<br/>(prototyping)"]
IFACE --> B["Mnesia<br/>(distributed dev)"]
IFACE --> C["Postgres<br/>(production)"]
IFACE --> D["CSV<br/>(fixtures)"]
Switching from prototype to production is literally changing one option plus adding migrations (for Postgres):
use Ash.Resource, domain: MyApp.Accounts, data_layer: AshPostgres.DataLayer
postgres do
table "users"
repo MyApp.Repo
end
Your actions, validations, policies, and code interfaces transfer untouched —
the domain logic never knew where rows lived, much like code that only ever
talked to your mnesia wrapper module.
12.5 Policies: Authorization as Declarations
Authorization lives on the resource, enforced on every action path — whether the caller came from HTTP, LiveView, or a background job:
policies do
policy action_type(:read) do
authorize_if always() # public reads
end
policy action_type(:create) do
forbid_unless actor_present()
end
policy action_type([:update, :destroy]) do
authorize_if relates_to_actor_via(:author) # only the author may edit/delete
end
end
require Ash.Query
MyApp.Accounts.User
|> Ash.Query.filter(email == ^email)
|> Ash.read!(authorize?: true, actor: current_user, domain: MyApp.Accounts)
Ash.Query.filter is itself a macro that takes an expression, so
require Ash.Query plus filter(email == ^email) is enough — the pin
interpolates the runtime value. Wrap an expression in expr/1 (from
Ash.Expr) only when you need to build it as a value, for example storing it
in a variable or passing it to a function that expects an Ash.Expr.
If you have ever written the same “is this user allowed?” check in three controllers and forgotten it in a fourth, this is the cure: the check is declared once, next to the thing being protected.
Reading Policy Logic: Allow, Forbid, Bypass
Policies evaluate top-down with three combinators:
- policy blocks are independent gates: if any authorizes, the request proceeds; if all refuse, it’s forbidden.
- forbid_if / forbid_unless inside a policy short-circuit that gate.
- bypass blocks are checked first; when one applies, remaining policies are skipped entirely.
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always() # admins sail through everything
end
policy action_type(:update) do
forbid_unless actor_present() # anonymous edits: hard no
authorize_if relates_to_actor_via(:author)
end
end
Two families of checks hide under those helpers. Simple checks answer
yes/no about the request itself (is there an actor?). Filter checks like
relates_to_actor_via/1 translate into extra WHERE conditions —
authorization becomes query planning, so a forbidden row simply never loads.
That property is what hand-written controller checks never gave you.
12.6 The Ash Ecosystem
| Package | Gives you |
|---|---|
ash_phoenix | forms & query building wired into Phoenix LiveView |
ash_authentication | registration/sessions/OAuth/magic-links as resources |
ash_postgres | the production-grade data layer + migration generators |
ash_json_api / ash_graphql | full JSON:API / GraphQL endpoints from declarations |
With ash_authentication, adding password sign-in is roughly: add the
extension, run its installer generator, and call the generated
sign_in_with_password action from your LiveView. Compare that to assembling
Comeonin + Plug session plumbing by hand.
12.7 Choosing: Ash vs Ecto + Contexts
Honest framing: Ash uses Ecto under the hood (types, casting). This is not either/or — it’s how much you want generated for you.
flowchart TD
Q{"Is your domain mostly<br/>CRUD over relational data<br/>with light validation?"} -->|yes| ECTO["Ecto + hand-written contexts<br/>(Ch 11)<br/>less framework, full control"]
Q -->|"no — many resources,<br/>shared auth/policies,<br/>API surface needed"| MORE{"Do multiple entry points<br/>(web, GraphQL, jobs)<br/>touch the same rules?"}
MORE -->|"yes"| ASH["Ash — declare once,<br/>enforce everywhere"]
MORE -->|"no"| ECTO2["Either works;<br/>Ash still saves boilerplate<br/>as resource count grows"]
| Signal | Lean toward |
|---|---|
| Few entities, bespoke SQL-heavy logic | Ecto directly |
| Team knows Rails/Django-style productivity | Ash |
| Authorization must be uniform across all paths | Ash (policies) |
| Need JSON:API/GraphQL fast | Ash (extensions generate both) |
| Deeply custom queries, CTEs, window fns | Ecto (or Ash fragments) |
| Prototyping storage-swappable domain models | Ash (ETS/Mnesia layers) |
Both approaches coexist in one application without friction — many teams use Ash for the core domain and raw Ecto queries inside reports/analytics.
When NOT to Reach for Ash
The honest disqualifiers, beyond the table above:
- Three resources and a weekend project — the DSL’s compile-time machinery outweighs the boilerplate it saves.
- Analytics-heavy cores dominated by hand-tuned SQL — Ecto’s query surface sits closer to the metal.
- Team fluency — an Ecto-native team ships faster than an Ash-learning-curve team. The gap closes with experience, but it’s real.
- Tight dependency budgets (embedded releases, audited stacks): Ash pulls a family of packages.
The reverse test: if you catch yourself writing the same context function shapes, authorization plumbing, and serialization glue for the fifth time, that repetition is exactly what Ash prices in.
12.8 Testing Ash Resources: Fast by Construction
The ETS data layer turns the Ch 11 sandbox story inside out: no connection, no transactions to roll back — start a fresh domain per test and its tables are brand new:
There is nothing to boot. A domain is not a supervisor — start_supervised!/1
on it would raise. ETS data layers create their tables at first use, and since
the tables are named global state, a sequential suite is the honest default:
defmodule MyApp.AccountsTest do
use ExUnit.Case, async: false # ETS tables are named, shared state
test "registration rejects reserved names" do
assert {:error, %Ash.Error.Invalid{}} =
MyApp.Accounts.User.register("admin", "admin@example.com")
end
test "registered users are readable" do
MyApp.Accounts.User.register!("Ada", "ada@example.com")
assert [%{name: "Ada"}] =
MyApp.Accounts.User
|> Ash.Query.sort(:inserted_at)
|> Ash.read!(domain: MyApp.Accounts)
end
end
The same suite runs unchanged against Postgres in CI — flip the data layer, generate migrations, and only startup differs:
mix ash_postgres.generate_migrations # write priv/repo/migrations from the resources
mix ash_postgres.migrate # apply them
That pair of commands is the whole cost of leaving ETS. Tests this cheap encourage declaring validation behavior first, then letting policies and actions accumulate around proven examples.
Two features worth knowing exist before you need them:
identities— an Ash-level declaration that uniqueness is identity, which upgrades a duplicate from anInvaliderror to a distinct error class callers can branch on. Better than matching error strings from a constraint.AshPhoenix.Form— a form struct with a changeset underneath, so a LiveView form for a nested resource is oneto_form/2call rather than hand-written assign plumbing.
Explore More
- Ash getting started and the Ash documentation — guides are genuinely excellent
AshPhoenix— Form objects that make nested LiveView forms almost trivialAshAuthentication— full auth stack walkthrough- AshAuthentication deep dive
- Exercise idea: rebuild Ch 11’s
Accountscontext as an Ash resource with ETS first, then flip to SQLite/Postgres — count the lines that changed
Checkpoint
- What does
code_interfacegenerate, and why does that matter for consistency? - How does switching
Ash.DataLayer.EtstoAshPostgres.DataLayeravoid rewriting domain logic? - Where do Ash policies live, and which callers do they cover?
- When would plain Ecto beat Ash?
Answers
- Public functions per declared action (
register!,by_id) — the API surface is derived from declarations, so docs, types, and behavior can’t drift apart. - Actions/validations/policies/interfaces are declarative metadata; only the data-layer option (plus migrations) is storage-specific.
- On the resource itself; they’re enforced on every path — HTTP, LiveView,
Oban worker, script — whenever
authorize?: trueflows through a domain. - Small domains dominated by bespoke SQL, when team expertise is already Ecto-native, or when minimal dependency surface outweighs generated convenience.
Next: Chapter 13 — Data, Jobs & Pipelines
Chapter 13 — Data, Jobs & Pipelines
Persistence and declarative modeling got their own chapters (Ch 11 Ecto, Ch 12 Ash). This chapter covers the rest of the Data domain: background work, backpressured dataflow, and dataframes. Every piece here is a composable library — the “pluggable” style from Ch 06 — each one an OTP application you start in your supervision tree.
13.1 Oban — Background Jobs as Supervised Processes
Where Erlang shops roll their own job queues on top of a table + poller, Oban provides it with OTP semantics built in:
- Jobs are rows in Postgres → durable, transactional with your data writes
- Workers are supervised processes → crash isolation per Ch 01
- Retries/backoff configured per worker — fault isolation applied to jobs
- No Redis required
flowchart LR
CODE["your write path"] -->|"same transaction"| INS["Oban.insert!<br/>job row = user row"]
INS --> PG[("Postgres<br/>oban_jobs table")]
PG -->|"poll / LISTEN"| P["Oban queue<br/>producers"]
P --> W["Worker process<br/>supervised"]
W -->|"crash!"| SUP["Supervisor<br/>restarts"]
P -->|"attempt 2, backoff ×2"| RET["retry per<br/>max_attempts"]
W --> OK[":ok → done"]
defmodule MyApp.Workers.SummaryWorker do
use Oban.Worker, queue: :default, max_attempts: 5
@impl true
def perform(%Oban.Job{args: %{"doc_id" => id}}) do
case Summaries.generate(id) do
{:ok, _} -> :ok # success → remove job
{:error, _} = e -> {:error, e} # error → retry with backoff
end
end
end
# enqueue — atomically with your business writes when inside Repo.transaction:
%{doc_id: 42}
|> MyApp.Workers.SummaryWorker.new()
|> Oban.insert()
String keys. You enqueued an atom-keyed map, but jobs are serialized to JSON before they hit the database — so
perform/1receives%{"doc_id" => 42}. That is why the pattern above matches"doc_id". Pick one convention deliberately: either match string keys in every worker (realistic), or enqueue with string keys (%{"doc_id" => 42}) so what you write is what you match.
From Erlang you know: the worker is an ordinary supervised process.
perform/1returning{:error, _}is just a structured way of letting the supervisor/retry machinery decide what happens next — let-it-crash with an audit trail in Postgres.
Install once in your supervision tree. Note repo: — Oban requires it and
will not boot without it:
# lib/my_app/application.ex
children = [
MyApp.Repo,
{Oban, repo: MyApp.Repo, queues: [default: 10, reports: 2]}
]
and yes, that option list is a keyword list like any other (Ch 02 §2.7).
Unique Jobs, Cron, and Scheduling
The knobs that replace hand-rolled dedup tables and crontabs:
defmodule MyApp.Workers.NightlyRollup do
use Oban.Worker,
queue: :reports,
max_attempts: 3,
# :infinity = duplicate-suppressed as long as the row exists;
# :all covers every state so a re-enqueue race can't slip through
unique: [period: :infinity, states: :all]
@impl true
def perform(_job), do: Reports.rollup_daily()
end
# schedule for later — a row with a future scheduled_at:
%{doc_id: id}
|> SummaryWorker.new(scheduled_at: DateTime.add(DateTime.utc_now(), 3600))
|> Oban.insert()
# recurring jobs come from the cron plugin, configured at startup:
{Oban, repo: MyApp.Repo, queues: [default: 10, reports: 2],
plugins: [{Oban.Plugins.Cron,
crontab: [{"0 2 * * *", MyApp.Workers.NightlyRollup}]}]}
unique: declares intent at the job level — same args + same queue within
the period inserts nothing new, closing the double-enqueue race of
hand-rolled queues. (Prefer the named groups like :all/:incomplete
over hand-listing states — partial explicit lists are deprecated and now
warn at compile time.) Oban.Testing makes workers deterministic in tests.
13.2 Broadway & GenStage — Backpressured Pipelines
GenStage is demand-driven producer/consumer flow control: consumers pull only what they can process, producers wait for credit. Broadway builds opinionated ingestion pipelines on top:
flowchart LR
K["Kafka /<br/>SQS / RabbitMQ"] --> PR["Producer(s)<br/>buffer events"]
PR -->|"demand-driven:<br/>consumers ask for N"| PROC["Processor stages<br/>concurrency × N<br/>per-message work"]
PROC --> BAT["Batcher<br/>size 100 / timeout 50ms"]
BAT --> SINK["Sink<br/>(DB bulk insert,<br/>API call, storage)"]
PROC -.->|"slow consumer ⇒<br/>producer holds back"| PR
Use when consuming Kafka/SQS/RabbitMQ or fanning out heavy processing. Your
message-passing instincts apply directly — demand is just credit-based pull
across processes, the same accounting you’d hand-write with gen_stage’s
Erlang port if there were one.
# deps: {:broadway_kafka, "~> 0.7"}
defmodule MyPipeline do
use Broadway
def start_link(_opts) do
Broadway.start_link(__MODULE__,
name: __MODULE__,
producer: [
module:
{BroadwayKafka.Producer,
hosts: [localhost: 9092], group_id: "demo", topics: ["events"]}
],
processors: [default: [concurrency: System.schedulers_online() * 2]],
batchers: [default: [batch_size: 100, batch_timeout: 50]]
)
end
@impl true
def handle_message(_processor, message, _ctx), do: message
@impl true
def handle_batch(_batcher, messages, _batch_info, _ctx) do
Enum.each(messages, &persist/1)
messages
end
end
Reading the options as architecture: processors parallelize per-message
work (validation, enrichment); batchers amortize expensive I/O over groups
(bulk inserts). Backpressure flows automatically — no manual accounting.
The other half of Broadway is the handle_failed/2 callback, and it is where
the broker differences bite:
@impl true
def handle_failed(messages, _ctx) do
# Called with the messages that failed; you must return them (possibly
# updated). Persist them here if you want to retry later — BroadwayKafka
# always commits offsets, so a failure it does not handle is gone.
Enum.each(messages, &persist_failure/1)
messages
end
The callback is optional, but without it a failed batch is only logged and
acknowledged. It must return the same list of messages it received; use
Broadway.Message.configure_ack/2 if you need to change how each one is
acknowledged. Design for the weakest broker guarantee you support.
Hand-Rolling GenStage: Demand Made Concrete
Writing one pair by hand makes the credit mechanics permanent knowledge:
defmodule Counter do
use GenStage
def start_link, do: GenStage.start_link(__MODULE__, 0, name: __MODULE__)
@impl true
def init(counter), do: {:producer, counter}
@impl true
def handle_demand(demand, counter) when demand > 0 do
events = Enum.to_list(counter..(counter + demand - 1))
{:noreply, events, counter + demand} # emit only what was asked for
end
end
defmodule Echo do
use GenStage
def start_link, do: GenStage.start_link(__MODULE__, :ok, name: __MODULE__)
@impl true
def init(:ok), do: {:consumer, :ok, subscribe_to: [{Counter, max_demand: 5}]}
@impl true
def handle_events(events, _from, state) do
Process.sleep(Enum.random(10..100)) # uneven work…
IO.inspect(length(events), label: "batch")
{:noreply, [], state} # consumers emit no events onward
end
end
Run it and batches like batch: 3, batch: 2, batch: 3 arrive, sized by
consumer appetite: slow consumers pull less, producers sit idle holding
events. max_demand/min_demand tune the credit window — the same knobs
Broadway sets under processors: [concurrency: n]. Flow control is the
message protocol itself.
Failure Strategies Across the Stack
| Concern | Oban | Broadway | Raw GenStage |
|---|---|---|---|
| Retry unit | whole job, N attempts | message (ack/nack) | yours to write |
| Backoff | exponential+jitter per worker | producer-defined | manual |
| Poison messages | failed job rows, inspectable | dead-letter config | manual |
| Ordering | per queue | partition_by groups related | stage topology |
Choose by ingestion shape: durable business work → Oban rows; continuous
external feeds → Broadway; internal inter-stage flow you fully control →
plain GenStage. Rate limiting differs accordingly — Oban throttles via
queue concurrency and priorities; Broadway adds
rate_limiting: [allowed_messages: n, interval: ms] on processors.
Ordering Guarantees: partition_by
Broadway’s concurrency destroys global ordering by design — twenty
processors means twenty messages in flight. When related events must be
processed in order (all state changes for one user), route them to the
same processor with partition_by:
# the processors option of Broadway.start_link/2
[
processors: [
default: [
concurrency: 20,
partition_by: fn message ->
message.data.user_id # shape depends on your producer
end
]
]
]
The routing key is hashed onto the processor indices (consistent hashing,
:erlang.phash2-style): every event for one user_id lands on one
processor and is handled serially in arrival order, while different users
still spread across all twenty lanes. Three properties worth knowing before
relying on it:
- Order holds per key, not globally — cross-user ordering is undefined; only events sharing a key are serialized.
- Hot keys create hot lanes — one chatty user throttles their own partition, but never anyone else’s. Pick keys that distribute traffic.
- Rescaling reshuffles keys — changing concurrency reassigns partitions; order guarantees hold within a running topology generation, which is why key design matters more than processor count.
You have written this pattern before by hand: hashing a key to pick one gen_server from a pool of registered workers. Broadway just made it a one-line option with the batching machinery already wired around it.
13.3 Explorer — DataFrames on the BEAM
Polars-backed DataFrames for Elixir. Fully runnable in Livebook with
Mix.install([{:explorer, "~> 0.12"}]):
iex> require Explorer.DataFrame, as: DF
iex> alias Explorer.Series, as: S
iex> df = DF.new(name: ["ada", "grace", "alan"], age: [36, 45, 41])
# filter + project — Series ops run vectorized in Rust, not row-by-row in Elixir
iex> df |> DF.filter(age > 40) |> DF.pull(:name)
#Explorer.Series<
Polars[2]
string ["grace", "alan"]
>
iex> df |> DF.summarise(mean_age: S.mean(age))
The query macros import the Explorer.Series operations, so inside
DF.filter/DF.summarise both mean(age) and S.mean(age) resolve age
to the column. Outside a query you hold a real series and call
S.mean(df["age"]) directly. Use col/1 for a column name that is not a
valid identifier:
df
|> DF.group_by(:city)
|> DF.summarise(mean_age: mean(col("age")))
Mental model: DataFrame/Series operations describe transformations;
Polars executes them columnar and lazy where possible. You get pandas-class
ergonomics with Rust-class throughput without leaving the notebook.
Explorer vs Enum: Choosing and Combining
The same aggregation in two worlds:
# Enum: element-wise over BEAM lists, a pass per transformation:
mean = rows |> Enum.map(& &1.age) |> Enum.sum() |> Kernel./(length(rows))
# Explorer: columnar, vectorized, fused by Polars — one pass, grouped:
df
|> DF.group_by(:city)
|> DF.summarise(mean_age: S.mean(age), n: S.count(age))
Decision guidance:
- Under ~100k rows, irregular shapes, one-off scripts → Enum; conversion overhead exceeds the vectorization gain.
- Tabular data at millions of rows, group/join/sort-heavy → Explorer; lists that size thrash memory long before Polars blinks.
- Mixed pipelines are normal: Explorer aggregates,
DF.to_rows/2hands off to ordinary Elixir for domain logic.
Both stay inside the VM — no NIF-bound copies out to Python, no serialization boundary crossed mid-analysis.
Pairs well with Livebook exploration (Ch 15) and Nx feature pipelines (Part IV).
13.4 Scholar — Traditional ML on Tensors
Explorer covers dataframes; Scholar covers the scikit-learn niche —
clustering, trees, preprocessing, metrics — implemented as defn functions,
so everything runs on the same backends as Nx (Ch 17–18):
Mix.install([{:scholar, "~> 0.4"}, {:nx, "~> 0.13"}])
# Three synthetic clusters:
key = Nx.Random.key(42)
{c1, key} = Nx.Random.normal(key, 0.0, 1.0, shape: {50, 2})
{c2, key} = Nx.Random.normal(key, 5.0, 1.0, shape: {50, 2})
{c3, _key} = Nx.Random.normal(key, 10.0, 1.0, shape: {50, 2})
x = Nx.concatenate([c1, c2, c3], axis: 0)
model = Scholar.Cluster.KMeans.fit(x, num_clusters: 3, key: Nx.Random.key(1))
labels = Scholar.Cluster.KMeans.predict(model, x)
| Module family | Gives you |
|---|---|
Scholar.Cluster | K-means, DBSCAN |
Scholar.Linear | linear/logistic regression |
Scholar.Metrics.Classification | accuracy, precision/recall/F1, ROC-AUC |
Scholar.Preprocessing | scalers, PCA, encoding |
Pin your Scholar version and check the module list before writing the call — coverage is narrower than scikit-learn’s (there is no decision-tree or random-forest module) and the mix is more spread out than the table suggests. Treat this table as “what families exist”, not “what functions exist”.
The One You Will Ask About: Flow
The most common question from Erlang developers choosing among these is
“what about in-VM parallelism without a broker?” That is
Flow, and it is a third answer to the same
question Oban and Broadway answer:
# Flow: data-parallel word count across cores, no broker
"big.log"
|> File.stream!()
|> Flow.from_enumerable()
|> Flow.partition(stages: System.schedulers_online())
|> Flow.map(&String.trim/1)
|> Flow.reduce(fn -> %{} end, fn line, acc ->
Map.update(acc, line, 1, &(&1 + 1))
end)
|> Enum.to_list()
| Oban | Broadway | Flow | |
|---|---|---|---|
| Moves work… | through Postgres | through a broker | through the VM |
| Durability | Postgres-backed | broker acks | none — crash loses it |
| Use when | jobs must survive restart | external producers/consumers | a batch fits in memory |
Flow has no persistence at all. It is the right tool for a nightly batch that can be re-run and the wrong tool for anything a user is waiting on.
The mental slot it fills: when a task is “classic ML” — tabular features,
a few thousand rows, a metric to report — you no longer reach for Python.
Same tensors, same backends, same supervision tree; results come back as
ordinary Nx.Tensors that pipe into Explorer summaries or Ecto persistence
without crossing any serialization boundary.
13.5 The Composable Stack
One application typically assembles these pieces side by side:
flowchart TD
APP["Your Application"] --> PLUG["Plug<br/>HTTP middleware"]
APP --> DATA["Ecto / Ash<br/>data access"]
APP --> JOBS["Oban<br/>background jobs"]
APP --> FLOW["Broadway / GenStage<br/>ingestion pipelines"]
APP --> MORE["domain-specific:<br/>Absinthe (GraphQL)<br/>Membrane (media)<br/>Reactor, Jido (Ch 14)"]
You compose libraries; you don’t inherit from a framework base class.
Ecosystem map at a glance:
| Domain | Libraries |
|---|---|
| Web | Phoenix, LiveView, Channels, Hologram |
| Data | Ecto (Ch 11), Ash (Ch 12), Broadway, Explorer |
| Background jobs | Oban, Quantum |
| Orchestration & agents | Reactor, Jido (Ch 14) |
| IoT / Edge | Nerves, AtomVM (Ch 16) |
| Mobile | Mob, Dala (emerging) |
| AI / Numerical | Nx, Axon, Scholar (Part IV) |
| Interactive dev | Livebook (Ch 15) |
| Media | Membrane |
From Erlang you know: each library above is an OTP application with a supervision tree. Start them in your child list, observe them in Observer, debug them like any process.
Explore More
- Oban guide — unique jobs, cron plugin,
priorities, and testing helpers (
Oban.Testing) - GenStage documentation — read the demand model explanation; it’s the best tutorial on credit-based flow
- Broadway guides — batching strategies, graceful shutdown, rate limiting, and Off-Broadway producers
- Explorer cheatsheet — DataFrame ops side-by-side with dplyr/pandas equivalents
- Exercise idea: build a mini pipeline — Oban enqueues synthetic events, a GenStage producer streams them into a Broadway batcher, and the sink writes into Explorer for a Livebook chart
Checkpoint
- Why does Oban not need Redis?
- What mechanism gives Broadway its backpressure?
- When would you pick Explorer over plain Enum pipelines?
- How do you keep all events for one user in order under Broadway’s concurrency?
- What does Scholar run on, and what comes back from a fit/predict call?
Answers
- Jobs live in your relational DB (Postgres), transactional with app data; workers are ordinary supervised processes.
- GenStage demand: consumers pull only what they can process, producers wait for credit — slow downstream automatically throttles upstream.
- When data is tabular/larger-than-memory or you want vectorized columnar performance — Enum works element-wise on lists in BEAM memory.
- Set a
partition_byon the processors — all messages sharing that key hash onto the same processor and run serially in arrival order. - It runs as
defnfunctions on the same Nx backends (BinaryBackend/ EXLA/EMLX);fit/3returns a model struct andpredict/2returns ordinary tensors — no boundary crossing to Python.
Next: Chapter 14 — High-Level Process Frameworks
Chapter 14 — High-Level Process Frameworks: Workflows & Agents
You already know the raw material: gen_server, gen_statem, supervisors,
registries. Chapters 10–13 showed Elixir libraries that arrange those parts
into web layers and pipelines. This chapter covers the frameworks one
abstraction higher still: they take recurring shapes of process
architecture — multi-step sagas with rollback, long-lived stateful actors
that react to events — and make the pattern itself the library.
The names you will hear most: Reactor (workflow/saga orchestration) and Jido (autonomous agents), beside Oban (durable jobs, Ch 13). None of them replaces OTP. Each compiles a pattern you could hand-write onto the primitives you already know.
14.1 The Abstraction Ladder
Place every tool on one ladder — from the metal up:
| Rung | Concern | Hand-written OTP shape | Reach for |
|---|---|---|---|
| 1 | One request-scoped conversation | a single gen_server / gen_statem | nothing — write it |
| 2 | Work that must survive restarts | table + poller + workers | Oban (Ch 13) |
| 3 | Continuous ingestion under load | producer/consumer credit accounting | Broadway / GenStage (Ch 13) |
| 4 | Multi-step consistency across services | task fan-out + hand-rolled undo log | Reactor |
| 5 | Long-lived event-driven actors | fleet of supervised gen_servers + registry | Jido |
flowchart TD
G["raw processes<br/>gen_server · gen_statem"] --> OB["Oban<br/>durable jobs"]
G --> BS["Broadway / GenStage<br/>backpressured flow"]
OB --> RE["Reactor<br/>sagas: DAG + undo"]
BS --> RE
RE --> JI["Jido<br/>agents: state + signals"]
From Erlang you know: this is the same trajectory as
proc_lib→gen_server→ OTP behaviours, repeated one level up. The framework does not remove the runtime semantics — restarts, mailboxes, linking still happen exactly as before — it removes the boilerplate of a pattern you have already written by hand.
Rule of thumb, especially coming from Erlang: drop down a rung whenever
the framework earns nothing. A three-line handle_call beats a workflow
engine. These libraries pay off when the pattern is the product: many
steps, real failure modes between them, or fleets of similar actors.
14.2 Reactor — Sagas as Dependency Graphs
A saga is a transaction you cannot wrap in try/after because its steps
live in different services. Reactor (from the Ash ecosystem — Ch 12) lets
you write one as steps wired by data dependencies:
- You declare what each step consumes (
result(:other_step)); Reactor builds the DAG and runs independent steps concurrently by default, on supervised tasks - A failed step runs its
compensate— retry it, substitute a fallback value, or accept failure - Successful steps that declared an
undoare rolled back in reverse order when a later failure survives compensation — the saga rollback
# An undoable step as a module — note the four-argument callbacks:
defmodule ChargeCard do
use Reactor.Step
@impl true
def run(%{order_id: id, reservation: r}, _ctx, _opts),
do: Payments.charge(id, r)
@impl true
def compensate(%Payments.Timeout{}, _a, _c, _o), do: :retry
def compensate(_reason, _a, _c, _o), do: :ok # decline → begin rollback
@impl true
def undo(payment, _args, _ctx, _opts) do
Payments.refund(payment)
:ok
end
end
defmodule FulfillOrder do
use Reactor
input :order_id
step :reserve_inventory do
argument :order_id, input(:order_id)
max_retries 2
run fn %{order_id: id}, _ctx ->
Inventory.reserve(id)
end
compensate fn _reason, _args, _ctx -> :retry end # holds are cheap to retry
end
step :charge_card, ChargeCard do # module step from above
argument :order_id, input(:order_id)
argument :reservation, result(:reserve_inventory)
end
step :ship do
argument :payment, result(:charge_card)
run fn %{payment: p}, _ctx -> Shipping.dispatch(p) end
end
return :ship
end
{:ok, shipment} = Reactor.run(FulfillOrder, %{order_id: 42})
Nothing here executes top-to-bottom. Input-only steps start immediately;
:charge_card waits for its argument; :ship waits for the payment. If
shipping fails and compensation cannot fix it, Reactor walks the undo stack:
flowchart LR
subgraph F["happy path"]
A["reserve_inventory"] --> B["charge_card"] --> C["ship"]
end
C -.->|"fails"| U1["undo ship"]
U1 --> U2["undo charge_card:<br/>refund"]
U2 --> U3["undo reserve:<br/>release hold"]
Compensation returns decide each step’s outcome: :retry (bounded by
max_retries — unlimited by default, so set it explicitly when retries
have a cost; an optional backoff callback delays attempts),
{:continue, value} (substitute a fallback and carry on), :ok (accept
the failure, proceed to rollback), or {:error, reason} (fail the whole
reactor).
Around the core: compose for sub-reactors, switch/map control-flow
steps, where/guard conditions, telemetry middleware out of the box, and
Mermaid export of the graph — this book’s diagrams, generated from your
code. Ash.Reactor extends the DSL so Ash resource actions (Ch 12) become
steps with transaction-aware undo.
Reactor vs Oban: Different Durability Stories
They answer different questions and combine cleanly:
- Reactor holds the run in memory — rich coordination, but a node crash abandons the saga mid-flight
- Oban (Ch 13) holds each unit as a Postgres row — survives crashes and retries across nodes, but each job is a straight line
- Combined: an Oban worker whose
perform/1callsReactor.run/2gives a crash-durable entry point into an in-memory saga; on error the job is retried per itsmax_attemptsand the DAG regenerates from scratch
14.3 Jido — Agents as Supervised Processes
Where Reactor orchestrates one run, Jido formalizes long-lived actors:
processes that hold state for days, react to events, choose among actions,
and coordinate with peers — agent-shaped systems, with or without LLMs
inside (AI arrives as a companion package, jido_ai, not a core
dependency).
Four concepts, each mapped to something you already operate:
| Jido concept | What it is | Erlang analogue |
|---|---|---|
| Agent | immutable state struct + one command function, cmd/2 | a gen_server’s state + callbacks |
| Action | validated unit of work: params in → state delta (+ effects) out | your handle_call body, minus boilerplate |
| Signal | typed message envelope (CloudEvents format) routing events between agents | a tagged message, standardized |
| Directive | an effect the runtime should perform: emit, spawn, schedule, stop | the sends/spawns your callbacks trigger implicitly |
# 1. The runtime supervisor — one child manages every live agent:
defmodule Support.Jido do
use Jido, otp_app: :support
end
# 2. An action: validated inputs, explicit outputs
defmodule Support.Actions.Triage do
use Jido.Action,
name: "triage",
description: "Sets priority and logs a triage note",
schema: [
priority: [type: :atom, required: true]
]
alias Jido.Agent.Directive
alias Jido.Signal
def run(%{priority: prio}, ctx) do
note = "triaged #{prio} at #{DateTime.utc_now()}"
signal =
Signal.new!("ticket.triaged",
%{ticket_id: ctx.state.ticket_id, priority: prio},
source: "/ticket-agent")
{:ok, %{status: :triaged, notes: [note | ctx.state.notes]},
%Directive.Emit{signal: signal}}
end
end
# 3. The agent: declares state shape, nothing else
defmodule Support.TicketAgent do
use Jido.Agent,
name: "ticket_agent",
schema: [
ticket_id: [type: :string, required: true],
status: [type: :atom, default: :new],
notes: [type: {:list, :string}, default: []]
]
end
Use it twice, at two different altitudes:
# As data — no process yet. Pure function over immutable state:
agent = Support.TicketAgent.new(%{ticket_id: "T-42"})
{agent, directives} =
Support.TicketAgent.cmd(agent, {Support.Actions.Triage, %{priority: :high}})
agent.state.status #=> :triaged — tested without any process running
# As a process — supervised, addressable, signal-driven:
{:ok, pid} = Support.Jido.start_agent(Support.TicketAgent, id: "T-42")
{:ok, agent} =
Jido.AgentServer.call(pid,
Jido.Signal.new!("triage", %{priority: :high}, source: "/dashboard"))
That split is the design’s point. Because cmd/2 is pure — state in,
state-plus-directives out — decision logic is unit-testable and replayable.
Because directives describe effects instead of performing them, the runtime
owns delivery, scheduling, spawning, and shutdown. Signal types a running
agent handles are declared in its signal_routes; execution strategies plug
in behind the same interface (Direct today; an FSM strategy when behavior
is a gen_statem-shaped lifecycle).
From Erlang you know: every running agent is an ordinary supervised process.
start_agentregisters it, Observer shows it, killing it exercises the supervisor — all the Ch 01 machinery applies unchanged. What Jido adds is discipline around the callback: validated inputs, explicit effects, and lookup that scales past a local name table.
When an Agent Framework Earns Its Keep
Honest thresholds, in the framework’s own terms:
- Yes: fleets of similar actors (per-user / per-ticket / per-device), event-driven behavior with many entry points, multi-agent coordination, or agentic AI loops (paired with Ch 28)
- No: a handful of singleton processes with two call sites — that is a
gen_server, and you should write thegen_server
14.4 Choosing: The Decision in One Table
| Symptom in your design | Correct rung |
|---|---|
| “If step 3 fails I must undo steps 1–2” | Reactor saga |
| “Overnight work must survive deploys and node loss” | Oban (Ch 13) |
| “10k events/sec from Kafka; slow downstream must throttle us” | Broadway (Ch 13) |
| “A thing with state that many clients poke via events, forever” | Jido agent — or a hand-written gen_server if there are only a few |
| “One request, one conversation, done in microseconds” | a plain function or gen_server |
The frameworks also stack: a webhook hits a Jido agent, an action returns a directive, the app enqueues an Oban job for the durable part, and that job runs a Reactor saga for the multi-service transaction. Each layer stays simple because the layer below absorbs its failure modes.
From Erlang you know: you have already made every one of these decisions by hand. The ladder is not new technology — it is your own
gen_serverdiscipline, priced and packaged.
Explore More
- Reactor guides — start with Your First Reactor, then Error Handling with Compensation and Undo; the cheatsheet covers DSL syntax
- Jido documentation — agents, actions, signals, and directives guides; jido_action details the schema/validation contract
- Exercise idea: take Ch 13’s Oban worker and convert its body into a
two-step Reactor saga (charge + notify) with an
undorefund — then kill the node mid-run and observe what survives - Exercise idea: drive a Jido agent from a Livebook cell (Ch 15) —
cmd/2it as pure data first, thenstart_agent/2and send it signals
Checkpoint
- What does Reactor give you that a linear function pipeline does not?
- A Reactor step failed and its compensation returned
:ok. What happens to the steps that succeeded before it? - In Jido, why does an action return a directive instead of emitting the signal itself?
- When is plain OTP still the right answer despite these frameworks?
- How do Oban and Reactor complement each other?
Answers
- Dependency-driven execution (independent steps run concurrently) plus per-step compensation and LIFO undo of successful steps — saga rollback across services.
- Each is undone in reverse completion order — but only steps that defined
an
undo; others are left as-is. - So effects belong to the runtime, not the decision logic:
cmd/2stays pure (testable/replayable as data), and the runtime owns delivery, scheduling, spawning, and shutdown uniformly. - When the pattern is small: few processes, few steps, no cross-service rollback. The framework’s vocabulary must cost less than the boilerplate it removes.
- Oban contributes durability (Postgres rows survive crashes, retries, scheduling); Reactor contributes in-memory coordination (concurrent DAG, compensation, undo). Wrap the reactor in a worker to get both.
Next: Chapter 15 — Livebook
Chapter 15 — Livebook
Livebook is the Jupyter-like environment for Elixir — notebooks + docs + executable code + data + ML, all backed by a live BEAM runtime. For an Erlang developer it doubles as something more interesting: a remote control for running production nodes.
15.1 Setup
# macOS
brew install livebook
# Or via mix
mix escript.install hex livebook
livebook server # open http://localhost:8080
New notebooks start blank; open any existing .livemd via “Open” → file,
or “Open from URL” with a raw GitHub link — many ecosystem projects ship
notebooks you can load straight from their repositories this way.
15.2 Basics in Two Minutes
- Cells — markdown cells and Elixir cells. Evaluate with ▶ or
Shift+Enter. - Run in order — later cells depend on earlier ones (
Mix.install, variables, loaded models). - First cell is
Mix.install/2— downloads and compiles dependencies into the notebook’s own environment. First evaluation is slowest.
Mix.install([
{:nx, "~> 0.13"},
{:kino, "~> 0.19"}
])
- Evaluate all — one button, top to bottom.
- Restart — needed after switching backends or dependency conflicts.
| Action | How |
|---|---|
| Evaluate cell | Click ▶ or Shift+Enter |
| Evaluate all | “Evaluate all” (top-right) |
| Insert cell | Hover between cells → + |
| Add text cell | + → Markdown |
| Notebook info | Ctrl/Cmd+J |
The Session Is One Dependency Graph
All cells in a notebook evaluate in one BEAM session, top to bottom:
Mix.install/1 pins dependencies, bindings persist, module definitions
overwrite. Out-of-order evaluation is real — a cell can run against stale
bindings until you re-run its ancestors. Sections are visual groupings, not
isolation boundaries; when experiments fork, prefer a second session or a
duplicated notebook over clever cell ordering.
Smart Cells: GUI In, Source Code Out
Smart cells are point-and-click generators — database connections, charts, forms — and clicking the </> icon reveals the Elixir they emitted. Nothing is hidden: the result is ordinary code you edit afterward. They double as teaching devices: the fastest way to learn the idiomatic incantation for a library you haven’t memorized yet.
15.3 Four Modes in One Tool
flowchart TD
LB["Livebook"] --> LEARN["Learn<br/>Elixir · OTP · Phoenix"]
LB --> EXPLORE["Explore<br/>data · SQL · APIs"]
LB --> BUILD["Build<br/>Nx · models"]
LB --> OPERATE["Operate<br/>attach to live nodes"]
style OPERATE fill:#e8f5e9
- Learn — mix Markdown, Mermaid/GraphViz diagrams, and runnable code; an increasing share of ecosystem documentation ships as Livebooks for exactly this reason.
- Explore — datasets, tensors, APIs, VegaLite charts, Kino tables.
- Build — prototype Nx/Axon/Bumblebee workflows before promoting them into Mix projects.
- Operate — connect to running BEAM systems and inspect them live.
15.4 Kino: Rich Outputs
# Tables
Kino.DataTable.new([
%{name: "Phoenix", domain: "Web", maturity: "Production"},
%{name: "Nerves", domain: "Edge/IoT", maturity: "Production"},
%{name: "Nx", domain: "AI/ML", maturity: "Active"}
])
# Charts
alias VegaLite, as: Vl
Vl.new(width: 400, height: 300)
|> Vl.data_from_values(x: 1..10, y: Enum.map(1..10, &(&1 * &1)))
|> Vl.mark(:line)
|> Vl.encode_field(:x, "x", type: :quantitative)
|> Vl.encode_field(:y, "y", type: :quantitative)
# Process inspection
# Kino.Process.render supervisor tree / app graph
Kino.Process.render_sup_tree(MyApp.Supervisor) draws what Ch 05 taught
you to read, straight from the live node — supervision trees as diagrams,
not :sys.get_state dumps.
Note the chart pipeline returns a spec; the last step must hand it to
Kino.VegaLite.new/1 (or Kino.VegaLite.window/1) for anything to display.
And data_from_values needs real lists — a 1..10 range is not enumerable
data here:
xs = Enum.to_list(1..10)
Vl.new(width: 400, height: 300)
|> Vl.data_from_values(x: xs, y: Enum.map(xs, &(&1 * &1)))
|> Vl.mark(:line)
|> Vl.encode_field(:x, "x", type: :quantitative)
|> Vl.encode_field(:y, "y", type: :quantitative)
|> Kino.VegaLite.new()
15.5 The Killer Feature for Erlang Devs: Operate Mode
Livebook can attach to a running node (same cookie):
- Start your release with the distribution port enabled.
- In Livebook: “Connect to an existing node” → enter
app@host. - Every notebook cell now evaluates on production, supervised by your app:
# Running against prod:
Process.whereis(MyApp.Repo) |> :sys.get_state()
Kino.Process.render_sup_tree(App.Supervisor) # supervision tree as a diagram
:sys.get_state(MyApp.Worker) # any process's state, rendered
Not :observer.start() here — Observer is a desktop GUI, and running it via
this path tries to open it on the server, which is usually headless. The
notebook-native equivalents are the Kino calls above; for the real Observer,
start it on your workstation and Node.connect/1 from there (Ch 27 covers
:observer_cli and :etop for terminals).
This replaces a whole category of remote-shell debugging sessions with shareable, re-runnable runbooks. A crash investigation becomes a saved notebook.
Connection Mechanics: Cookies and Distribution
“Connect to an existing node” performs ordinary Erlang distribution —
Node.connect/1 under the hood, gated by the cookie:
%% the handshake Livebook performs, from an Erlang shell:
erlang:set_cookie(node(), mysecret).
net_adm:ping('app@10.0.0.7'). %% => pong | pang
Production hygiene transfers unchanged: distinct cookie per environment, distribution ports firewalled or tunneled (Livebook over an SSH tunnel is the standard remote pattern). And remember every cell executes with production privileges — treat notebooks like deploy scripts: reviewed, versioned, never ad-hoc.
Secrets: Credentials Without Commits
The notebook sidebar stores secrets (API keys, DB URLs) per user; cells
read them as LB_-prefixed environment variables:
token = System.fetch_env!("LB_GITHUB_TOKEN")
Secrets never appear in notebook text, so .livemd files stay commit-safe —
the same discipline as runtime.exs env lookups (Ch 09), one level down.
15.6 Executable Knowledge
Markdown + Code + Data + Visualization + Runtime = executable knowledge
The intended learning loop: read a chapter here, prototype its ideas in a scratch notebook, tweak cells until the concepts click, then keep your annotated copy. Notebooks you save after an incident become the next engineer’s debugging runbook — institutional memory that actually executes.
A Runbook in Five Lines
Kino controls turn notebooks into interactive ops tools — inputs, buttons, and outputs wired to whatever the incident needs:
threshold = Kino.Input.number("Queue depth threshold", default: 500)
run = Kino.Control.button("Audit queues")
Kino.listen(run, fn _event ->
for {queue, len} <- MyApp.Oban.audit(),
len > Kino.Input.read(threshold) do
IO.puts("#{queue}: #{len} pending — investigating")
end
end)
Click the button during an incident; the notebook remembers the parameters afterward. Compare with scrolling a shell history nobody can rerun.
15.7 Livebook Apps: The Reason Teams Keep It
A notebook you run is a debugging tool. A notebook with inputs and
buttons, deployed as a small internal app, is a tool other people use without
knowing Elixir. From the File menu: “Deploy as App” turns the current
notebook into a standalone web app — form inputs, buttons, rendered outputs,
no Livebook UI. Commit the .livemd beside your code and the “app” is
reviewable in a pull request like anything else.
The pattern that pays off operationally:
# inputs cell — typed parameters the user fills in
range = Kino.Input.select("window", ["1h", "24h", "7d"], default: "24h")
# button cell — runs the real code path, no notebook required to read it
Kino.Control.button("Run report")
|> Kino.listen(fn _event ->
case Reports.generate(Kino.Input.read(range)) do
{:ok, path} -> Kino.Markdown.new("Wrote `#{path}`")
{:error, e} -> Kino.Markdown.new("**Failed:** #{Exception.message(e)}")
end
end)
The result is a deployable internal tool: run a backfill, regenerate a
report, trigger a reindex — by someone who has never opened IEx. That
progression (script → notebook → deployed app) is the argument for Livebook
in a team, and it is the reason to keep .livemd files in version control
rather than in a personal scratch directory.
Explore More
- Livebook docs — including desktop app and Teams features for shared deployments
- Kino docs — every widget: tables, terminals, forms, process diagrams
- Smart cells — no-code cells that generate Elixir for DB connections, charts, and more
- Exercise idea: attach a Livebook to
iex --sname devon your machine, runKino.Process.render_sup_tree(MyApp.Supervisor), and keep the notebook as your first ops runbook
Checkpoint
- What does
Mix.install/2do and why does the first cell matter? - How do you point Livebook at a production node safely?
- What are the four modes?
Answers
- Installs+compiles deps into the notebook’s isolated Mix env; everything downstream depends on it, so it must evaluate first.
- Set matching Erlang cookie on both sides, use “connect to existing node”; treat connected sessions as privileged operations (they execute on prod).
- Learn, Explore, Build, Operate.
Next: Chapter 16 — Edge, IoT & Mobile
Chapter 16 — Edge, IoT & Mobile
OTP is not limited to servers. Three stacks push BEAM toward hardware — each keeps the same process/supervision model at different scales.
16.1 Mental Model First
- Nerves = BEAM on Linux (full OS)
- AtomVM = BEAM on microcontrollers (no OS)
- LiveView Native = server-driven LiveView rendered as real native views
- Mob / Dala = BEAM running on the phone, offline-first
That third line is the one most readers have not heard of, and it is the one
you probably want: LiveView Native (LVN) renders your existing
LiveViews through SwiftUI and Jetpack Compose components. Same .heex, same
handle_event, real native widgets — but it needs a server, because the
LiveView runs there. Mob runs the BEAM on the device, so it works offline.
Pick by that single question:
| Requirement | Choice | Why |
|---|---|---|
| Must work offline / no server | Mob (experimental — evaluate per app) | BEAM on the phone, ~4MB runtime |
| Native UI, server always reachable | LiveView Native | share LiveViews with your web app |
| Own the whole device | Nerves | full Linux + supervision tree |
flowchart TD
SRC["Elixir / Erlang source"]
SRC --> NERVES["Nerves<br/>(Buildroot Linux)"]
SRC --> ATOM["AtomVM<br/>(compact BEAM)"]
SRC --> MOB["Mob<br/>(BEAM on device)"]
SRC --> LVN["LiveView Native<br/>(server LiveViews)"]
NERVES --> LINUX["Linux device<br/>RPi · BeagleBone · custom boards"]
ATOM --> MCU["MCU<br/>ESP32 · STM32 · RP2040"]
MOB --> MOBILE["iOS / Android<br/>native UI, offline"]
LVN --> MOBILE2["iOS / Android<br/>native UI, online"]
16.2 Nerves — Embedded Linux Firmware
Nerves cross-compiles your Elixir app + BEAM + a minimal Linux (Buildroot) into a firmware image. Boots straight into your supervision tree in ~3 seconds.
flowchart TD
EX["Elixir"] --> NR["Nerves<br/>Buildroot + tooling"]
NR --> DEV["Linux device"]
DEV --> HW["GPIO · Sensors ·<br/>Network · Storage"]
Key libraries:
| Package | Role |
|---|---|
nerves_runtime | firmware info, hardware access |
vintage_net | network configuration |
circuits_gpio / circuits_i2c / circuits_spi | hardware buses |
nerves_pack / ring_logger | networking defaults, ring logging |
Step-by-step first firmware:
mix archive.install hex nerves_bootstrap
mix nerves.new my_device
cd my_device
export MIX_TARGET=rpi4 # Raspberry Pi 4 target
mix deps.get
mix firmware # produces .fw image
mix burn <sd-card-device> # write to SD card, boot the device
Great fits: industrial gateways, robotics, edge nodes, kiosks, device telemetry.
Targets, Toolchains, and What’s in a .fw
Each MIX_TARGET pulls a prebuilt system — Buildroot Linux + BEAM for
that board — plus a cross-toolchain, cached under ~/.nerves and
versioned in mix.exs. Your app cross-compiles against them and fwup
assembles the .fw image:
| Target | Board class | Notes |
|---|---|---|
rpi0_2, rpi3, rpi4, rpi5 | Raspberry Pi family | the usual starters |
mangopi_mq_pro | Orange Pi | cheap SBCs |
bbb | BeagleBone Black | industrial I/O heritage |
grisp2 | GRiSP2 | purpose-built Erlang hardware, niche |
x86_64 | generic PC/VM | kiosks, laptop dev |
Check the Nerves supported-targets page for the exact list for your nerves
version; target names have changed across releases (rpi0 became rpi0_2).
Inside the image: a minimal read-only rootfs, your release, and fwup slots — A/B partitions enabling atomic upgrades and rollback, which is what the update story below leans on.
Network Config and Reaching the Device
vintage_net models interfaces as supervised processes — each NIC is a
child whose configuration is a plain map:
# config/target.exs (evaluated on-device)
config :vintage_net,
regulatory_domain: "US",
config: [
{"eth0", %{type: VintageNetEthernet, ipv4: %{method: :dhcp}}},
{"wlan0",
%{
type: VintageNetWiFi,
vintage_net_wifi: %{
networks: [%{key_mgmt: :wpa_psk, ssid: "shop-floor", psk: "..."}]
},
ipv4: %{method: :dhcp}
}}
]
Inspect at runtime like any process state:
VintageNet.get_by_prefix(["interface"]). Once booted, the device is just a
BEAM node on your LAN:
ssh nerves.local # drops straight into IEx on the device
iex> Nerves.Runtime.KV.get_all_active() # firmware provenance
(mix upload over SSH needs nerves_ssh in the firmware and your
public key in the device’s authorized_keys; without it you are back to
nerves.local login or a serial console.) No adb, no serial-console ritual
(though UART remains the rescue hatch) — it’s remsh with a power plug.
Fleet Management: NervesHub
The line above is the single-device story. A fleet needs more, and the standard answer is NervesHub — open source, and what most teams use instead of hand-rolling OTA:
# config/target.exs — connect the device to NervesHub
# deps: {:nerves_hub_link, "~> 2.2"}
config :nerves_hub_link,
host: "your.nerveshub.host",
shared_secret: [
product_key: System.get_env("NERVESHUB_PRODUCT_KEY"),
product_secret: System.get_env("NERVESHUB_PRODUCT_SECRET")
]
nerves_hub_link supervises itself and handles the whole update loop —
announcement, download, signature verification, staged rollout, progress
reporting — so you do not write it. The parts you do own:
- Channel structure —
prodvsstaging, and per-device or per-group targeting, so you can stage a rollout before it reaches the fleet. - Signing — sign firmware so devices refuse unsigned images.
- A/B firmware slots —
fwupwrites the new image to the inactive slot and flips a bootloader flag, so a failed flash rolls back on next boot rather than bricking the device. This is a hardware/fwup property, not something you code.
If you skip NervesHub you are writing all three yourself. Do not skip it.
16.3 AtomVM — Microcontrollers, No OS
AtomVM is a compact BEAM implementation (~200KB flash, ~100KB RAM) running directly on ESP32, STM32, RP2040:
- Preemptive scheduler, GenServers, supervisors — yes, really
- Native modules written in C for hardware access (Rust is possible via NIF experiments, not the documented path — plan on C)
- No operating system; boots to OTP semantics on bare metal
flowchart TD
SRC["Elixir / Erlang"] --> AVM["AtomVM<br/>compact BEAM"]
AVM --> MCU["Microcontroller<br/>ESP32 / STM32 / RP2040"]
MCU --> IO["Sensors · Actuators ·<br/>BLE · WiFi"]
Use when Linux is too heavy: battery sensors, small actuators, BLE devices.
Constraints vs the Full BEAM
AtomVM is a reimplementation, not a port — plan around the deltas:
| Capability | Full BEAM (Nerves) | AtomVM |
|---|---|---|
| Processes, supervisors, GenServer | yes | yes |
| Binary/term semantics | complete | core subset |
Distribution (net_kernel) | yes | no — raw sockets instead |
| OTP breadth (crypto, ssl, …) | extensive | selective per platform |
| RAM floor | tens of MB (Linux) | ~100 KB class |
Hardware access follows the Erlang tradition of thin native edges: C/Rust native modules compiled into the VM image, reached from ordinary Elixir calls. The architectural pattern from servers holds here too — keep native code dumb and narrow, model the device as a supervised process (§16.5), and let restarts absorb flaky buses. When a sensor fleet outgrows MCU limits the escape hatch is architectural, not linguistic: AtomVM nodes report to a Nerves gateway, which reports to your cluster.
16.4 Mobile — Three Options, One Question
LiveView Native is the production answer and gets a full section below. Mob and Dala are the experimental branch: both embed BEAM inside native iOS/Android apps with real native UI (not web views), which means genuine offline capability — at the cost of stability.
| Mob | Dala | |
|---|---|---|
| Approach | BEAM/OTP inside the app | Rust-powered native layer + BEAM + Edge AI |
| UI | SwiftUI / Jetpack Compose | SwiftUI / Jetpack Compose |
| Status | Active experiment, descended from Elixir Desktop | Emerging, Rust-based |
| Integration | NIFs for platform APIs | Rust NIFs, unified layer |
Read both as research directions, not as dependencies you can rely on. Both have moved through 0.x with breaking changes and neither offers the ecosystem depth of Phoenix; evaluate per app against the Elixir Forum threads before committing. Dala in particular markets “Edge AI” without a documented API surface — if that capability is the reason you are considering it, verify it exists before designing around it.
Pipelines:
flowchart LR
subgraph MOBPIPE["Mob"]
E1["Elixir → OTP/BEAM"] --> M1["Mob"] --> U1["Native UI<br/>iOS / Android"]
end
subgraph DALAPIPE["Dala"]
E2["Elixir/OTP → BEAM"] --> R2["Rust native layer"] --> U2["Native UI<br/>iOS / Android"]
end
Your OTP skills apply directly: offline state machines, background sync, and fault-tolerant local services inside the app.
16.4.1 LiveView Native — Your Existing LiveViews, Natively Rendered
The mainstream option, and the one to reach for first. LiveView Native takes
a .heex template plus SwiftUI/Jetpack Compose component implementations and
renders it with real native widgets. The LiveView still runs on your server;
the phone is a thin native client speaking the LiveView wire protocol.
# mix.exs — server side
def deps do
[{:live_view_native, "~> 0.3"}]
end
# lib/my_app_web/live/hello_live.ex — one template, two renderers
defmodule MyAppWeb.HelloLive do
use MyAppWeb, :live_view
@impl true
def render(assigns) do
~LVN"""
<VStack spacing={10}>
<Text>{@title}</Text>
<Button phx-click="inc">Count: {@count}</Button>
</VStack>
"""
end
# handle_event/3 is unchanged from the web LiveView
@impl true
def handle_event("inc", _params, socket) do
{:noreply, update(socket, :count, &(&1 + 1))}
end
end
The ~LVN sigil marks the template for the LVN compiler; <VStack>,
<Text>, <Button> are SwiftUI/Compose components you implement on the
client side. Everything Ch 10 taught — assign/3, handle_event/3, streams,
the diffing protocol — is unchanged.
What you get: real native accessibility, native lists and pickers (via components), and one server codebase serving web and both platforms. What you give up: it is not offline. If the server is unreachable, the LiveView has nothing to render — that requirement points at Mob instead.
16.5 The Same OTP Model Represents a Device
The pattern that transfers: a peripheral is a process.
defmodule TemperatureSensor do
use GenServer
def start_link(opts \\ []),
do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
def read, do: GenServer.call(__MODULE__, :read)
@impl true
def init(_opts) do
# On real hardware: {:ok, ref} = Circuits.GPIO.open(pin, :input)
Process.send_after(self(), :tick, 1000) # self-scheduling: no external kick
{:ok, %{value: 23.5, unit: :celsius}}
end
@impl true
def handle_call(:read, _from, state), do: {:reply, state.value, state}
@impl true
def handle_info(:tick, state) do
new_value = state.value + Enum.random(-5..5) / 10 # drift ±0.5°
Process.send_after(self(), :tick, 1000)
{:noreply, %{state | value: new_value}}
end
end
{:ok, _pid} = TemperatureSensor.start_link()
TemperatureSensor.read() #=> 23.5 (then watch it drift via :sys.get_state/1)
- Fully runnable in IEx or a Livebook cell — and note the process schedules its
own first tick from
init/1, so nothing external has to kick it. That matters on firmware: the external `Process.send_after(TemperatureSensor, - tick, 1000)` from the previous version only worked because IEx happened to send it. A device that boots and then waits forever is a bug that no test catches.
Enum.random/1 picks from the range — :rand.uniform/1 only accepts a
positive integer bound, so :rand.uniform(-5..5) would crash. On real
hardware the state represents a sensor, actuator, connection, or device
controller — all supervised, fault-tolerant, distributable.
16.6 Supervision Tree for a Device
flowchart TD
APP["Device Application"] --> SUP["Device.Supervisor"]
SUP --> TS["TemperatureSensor<br/>GenServer"]
SUP --> HS["HumiditySensor<br/>GenServer"]
SUP --> MOTOR["MotorController<br/>GenServer"]
SUP --> MQTT["MQTTClient → Cloud"]
SUP --> OTA["OTAUpdater → firmware"]
SUP --> WD["Watchdog<br/>hardware watchdog"]
APP --> RUNTIME["Nerves.Runtime<br/>firmware · network · hw"]
Two different things wear the name “watchdog” — keep them apart:
- The supervision strategy decides what BEAM does when a process dies.
:one_for_onerestarts only the crashed sensor, which is what you want. - The hardware watchdog is a separate SoC-level timer. If it is not fed within its window, the board resets regardless of what the BEAM believes. That is what recovers from a wedged VM — a supervisor cannot restart a runtime that is no longer scheduling.
No special embedded framework is required for either. The tree you’ve drawn a hundred times for servers is the firmware architecture.
Firmware Updates: burn, Upload, OTA
Three escalation levels, all fwup underneath:
mix burn <sd-card-device> # factory install — SD card in hand
mix upload nerves.local # push over SSH: build, stream, swap slot;
# device reboots into the new slot atomically
True OTA swaps only the transport, not the mechanism — and you should not be
writing that transport. NervesHub (§16.2) gives you update announcement,
download, signature verification, staged rollout, and progress reporting as
a supervised process you drop into your tree. The device polls a firmware
server (or receives an MQTT announcement), downloads the .fw, and fwup
validates signatures before touching slots. A failed upgrade falls back to
the previous slot — the supervisor’s crash-recovery instinct, applied to
images. Because slots make upgrades atomic you ship often; because the BEAM
is there, you can also hot-patch inside a running slot when a restart
would drop live connections.
Three Tools Every Nerves Session Needs
Small libraries, all in the firmware’s deps, none optional once you start debugging on real hardware:
# 1. Log to a ring buffer instead of the console — survives a crash,
# readable later with RingLogger.next()/tail()/get()
{:ring_logger, "~> 0.11"} # + config :logger, backends: [RingLogger]
# 2. Keep the VM alive when an OTP application crashes, and control start order
{:shoehorn, "~> 0.9"} # + steps: [&Shoehorn.Release.init/1, :assemble]
# 3. IEx helpers for the device — top, cmd, ping, tree, and more
{:toolshed, "~> 0.4"} # then `use Toolshed` at the IEx prompt
Without RingLogger a panic takes the only diagnostic with it, because stdout went to a console you cannot scroll back. Add it before you need it.
Checkpoint
- Which stack would you pick for a $2 microcontroller? A gateway box?
- What replaces “driver code” in the AtomVM world?
- How does a crashed sensor process recover?
Answers
- AtomVM for bare-metal MCUs; Nerves for Linux-class devices/gateways.
- Native modules written in C, loaded by the AtomVM packer and called from Elixir as ordinary functions.
- Its supervisor restarts it per strategy; siblings continue untouched.
Explore More
- Nerves getting started — install the toolchain, blink an LED, burn real firmware
- Nerves projects list — hardware targets, community firmware examples
- AtomVM docs — ESP32 port guides and the Erlang/Elixir API subset supported
- vintage_net docs — network configuration you’ll configure on every real device
- Exercise idea: take Ch 09’s release workflow knowledge to hardware —
mix firmwareismix releasewith a Buildroot rootfs; diff the two trees
Next: Chapter 17 — Nx Fundamentals
Chapter 17 — Nx Fundamentals
Nx (Numerical Elixir) brings the computational model of NumPy/JAX/PyTorch to the BEAM while keeping functional semantics. It is the foundation for everything in Part IV.
What if Elixir could describe numerical computation while specialized backends decide how to execute it?
17.1 The Four Abstractions
| Abstraction | Purpose | Implementations / instances |
|---|---|---|
Nx.Tensor | Immutable multi-dimensional array | struct wrapping backend-specific data |
Nx.Defn | Numerical definition (macro) | Elixir subset compiled to backend IR |
Nx.Backend | Storage + op dispatch behaviour | Nx.BinaryBackend, EXLA.Backend, EMLX.Backend, Torchx.Backend |
Nx.Container | Protocol: what defn can traverse | tuples, maps, @derive {Nx.Container, containers: [:params]} structs |
Nx.Container is the one that confuses newcomers, because the name suggests
storage. It is not: storage is Nx.Backend. Nx.Container is the protocol
that teaches defn how to walk a data structure holding tensors — a tuple of
(weights, bias), a map of named params, a struct. Auto-derived so Axon
can pass parameter containers through functions:
defmodule MyParams do
@derive {Nx.Container, containers: [:w, :b]}
defstruct w: nil, b: nil
end
Types: tensors carry shape {dims...} and type
{:f | :s | :u, bits} — u2/u4/u8…u64, s2/s4…s64, f8/f16/f32/f64,
bf16, c64/c128. Shapes can have dynamic (nil) dims for batch
size.
Memory model: tensors are immutable; operations return new tensors. The Elixir GC handles tensor structs; the backend manages device memory.
Tensors Are Refc Binaries
Under Nx.BinaryBackend a tensor’s payload is an Erlang binary — a refc
binary once it exceeds ~64 bytes. Your Erlang binary instincts carry over:
| Erlang concept | Nx equivalent (BinaryBackend) |
|---|---|
<<1.5:32/float>> | Nx.from_binary(bin, {:f, 32}) |
binary_part/3 | Nx.slice/3 |
byte_size/1 | Nx.byte_size/1 |
Consequences worth internalizing:
- No mutation, ever.
Nx.add(a, b)reads both payloads and allocates a third — the same aliasing-free discipline as Erlang binaries, scaled to multidimensional data. - Refc GC frees large payloads when the last tensor struct referencing them drops out of scope. Long-lived process state holding tensors holds their bytes — budget process memory accordingly.
- Zero-copy bridges.
Nx.to_binary/1andNx.from_binary/2move between BEAM terms and typed tensors without transcoding; this is how Scidata and Ch 21’s persistence layer feed Nx.
17.2 Setup
Everything in this chapter runs in a Livebook cell (or iex after
Mix.install has executed once per session):
Mix.install([
{:nx, "~> 0.13"},
{:exla, "~> 0.13"}
# {:emlx, "~> 0.4"} # Apple Silicon alternative to EXLA — see note
])
First evaluation compiles dependencies (slow); later cells are instant. If
you skip a native backend entirely, plain {:nx, "~> 0.13"} alone works
everywhere on Nx.BinaryBackend.
Add emlx only on Apple Silicon. Pulling it into a Linux CI job
downloads a whole MLX toolchain you will never invoke there, since EXLA
covers CPU on every platform (Ch 18).
17.3 Tensor Basics
iex> Nx.tensor([1, 2, 3])
#Nx.Tensor<
s64[3]
[1, 2, 3]
>
iex> key = Nx.Random.key(42)
iex> {rand, _new_key} = Nx.Random.uniform(key, shape: {2, 3})
iex> Nx.shape(rand)
{2, 3}
Properties:
iex> x = Nx.tensor([[1, 2, 3], [4, 5, 6]])
iex> Nx.shape(x) # {2, 3}
iex> Nx.rank(x) # 2
iex> Nx.type(x) # {:s, 64}
iex> Nx.size(x) # 6
Element-wise & broadcasting (NumPy rules — align trailing dims):
a = Nx.tensor([1, 2, 3])
b = Nx.tensor([4, 5, 6])
Nx.add(a, b) # [5, 7, 9]
Nx.max(a, b)
Nx.exp(a)
matrix = Nx.tensor([[1, 2, 3], [4, 5, 6]])
vector = Nx.tensor([10, 20, 30])
Nx.add(matrix, vector) # vector broadcast across rows
Nx.add(matrix, 100) # scalar broadcast
The rule, made concrete: dimensions align from the right; missing or size-1 dims stretch to match; a mismatch where neither side is 1 is an error. Think of broadcasting as the vectorized replacement for the nested list comprehensions you would otherwise write:
# {2, 3} + {3} → {2, 3} row vector onto every row
# {2, 3} + {2, 1} → {2, 3} column vector onto every column
# {4, 1, 3} + {2, 3} → {4, 2, 3} the size-1 dim stretches…
# {4, 3} + {2, 3} → error …but 4 vs 2 with no 1 anywhere fails
iex> col = Nx.tensor([[10], [20]]) # shape {2, 1}
iex> Nx.shape(Nx.add(Nx.iota({2, 3}), col))
{2, 3}
Reductions and axes:
x = Nx.tensor([[1, 2, 3], [4, 5, 6]])
Nx.sum(x) # 21
Nx.sum(x, axes: [0]) # [5, 7, 9] (collapse rows)
Nx.sum(x, axes: [1]) # [6, 15] (collapse cols)
Nx.mean(x)
Nx.reduce_max(x)
axes: semantics trip everyone once: the listed axes are collapsed.
Summing axes: [0] removes the row dimension; keep_axes: true retains it
as size 1, keeping the output broadcast-compatible with the input.
Type Promotion
Mixed-dtype operations promote the weaker side — floats beat integers, wider beats narrower:
| Expression | Result type | Watch out |
|---|---|---|
| s64 + f32 | f32 | ints lose precision past 2^53 |
| u8 + u8 (element-wise) | u8 | silent wraparound on overflow |
| f32 + bf16 | f32 | bf16 rounds up to f32 |
| int tensor + float scalar | float | scalar adopts tensor family |
iex> a = Nx.tensor([200], type: {:u, 8})
iex> Nx.add(a, a)
#=> #Nx.Tensor<u8[1] [144]> element-wise ops wrap mod 256!
iex> Nx.sum(Nx.tensor([200, 200], type: {:u, 8}))
#=> #Nx.Tensor<u32 400> but reductions PROMOTE instead — no wrap
Linear algebra:
Nx.dot(a, b) # matrix multiply
Nx.transpose(a)
Nx.LinAlg.solve(a, b) # a·x = b without inverse
Nx.LinAlg.svd(a)
Reshape/slice:
x = Nx.iota({2, 3, 4})
Nx.reshape(x, {6, 4})
Nx.slice(x, [0, 0, 0], [1, 2, 4])
x[[0, 1..2, 0]] # access syntax: int = index, range = slice
Nx.concatenate([t1, t2], axis: 0)
Nx.stack([t1, t2]) # adds new axis
17.4 defn — Compilable Numerical Functions
defn restricts Elixir to a tensor-safe subset that can be JIT-compiled,
differentiated, and inspected:
defmodule MathOps do
import Nx.Defn
defn relu(x), do: Nx.max(x, 0)
defn linear(x, w, b), do: Nx.dot(x, w) + b
defn mlp(x, params) do
x
|> linear(params.w1, params.b1)
|> relu()
|> linear(params.w2, params.b2)
end
defn leaky_relu(x, alpha \\ 0.01), do: Nx.select(x > 0, x, x * alpha)
end
Execution flow:
flowchart LR
CALL["defn call<br/>f(x, params)"] --> SEEN{"shape/dtype<br/>seen before?"}
SEEN -->|"no"| TRACE["trace with concrete shapes<br/>→ computation graph"]
TRACE --> COMP["compile via backend<br/>XLA / MLX / Evaluator"]
COMP --> CACHE["cache kernel"]
CACHE --> RUN["run"]
SEEN -->|"yes"| RUN
RUN --> NEW["new shape later?<br/>→ recompile (specialized)"]
- First call: Nx traces the function with concrete shapes/types → builds computation graph → compiles to backend → caches kernel.
- Subsequent calls: reuse the cached kernel (dispatch by shapes/types).
- New shape → recompile (shape-specialized).
This is the JIT contract you know from BEAM hot paths, applied to numerics: first hit pays compilation; steady-state dispatch is a cache lookup keyed by shape/type signature.
Compilers: EXLA (production CPU/GPU), EMLX (Apple Silicon),
Nx.Defn.Evaluator (pure-Elixir debugging interpreter), Nx.Defn.Debug.
Why a Restricted Language Pays
Tracing a closed subset means the backend sees the whole computation as a graph before executing any of it — the precondition for what makes numerics fast:
- Kernel fusion: element-wise chains lower into a single pass;
intermediates between
linearandrelunever touch memory. - Mechanical autodiff: gradients derive from the graph itself (§17.5).
- Portability: one expression lowers to XLA, MLX, or the interpreter.
The price: inside defn there is no Enum, no pattern matching on tensor
values, no message passing. Branching is Nx.select (elementwise) or
Nx.cond (graph-level); loops are Nx.while. When you miss imperative
control flow, suspect a vectorized formulation exists — unlearning the
recursive-accumulator reflex is most of the migration effort here.
Observability survives compilation via hooks — the io:format of
tensor programs, callable even under EXLA. (hook/2 comes from
Nx.Defn.Kernel, already in scope via import Nx.Defn; the data passes
through unchanged):
defn inspected(x) do
x
|> hook(fn t -> IO.inspect(Nx.shape(t), label: "post-linear") end)
|> relu()
end
Note the anonymous fn: the callback’s return value is ignored and x
passes through unchanged. Writing &IO.inspect(Nx.shape(&1), ...) looks
equivalent but returns a shape tuple, which reads as if the tensor were
being replaced by its shape. It isn’t — but the code misleads every reader
including its author.
17.5 Automatic Differentiation
Reverse-mode autodiff over parameter containers (tuples/maps/lists):
defmodule Gradients do
import Nx.Defn
defn mse_loss(w, b, x, y) do
y_pred = Nx.dot(x, w) + b
Nx.mean((y_pred - y) ** 2)
end
defn grad_mse(w, b, x, y) do
Nx.Defn.grad({w, b}, fn {w, b} -> mse_loss(w, b, x, y) end)
end
end
- First arg of
grad/2: container holding params — gradients come back in the same structure. - Second arg: primal function returning a scalar loss.
value_and_grad/2returns{loss, grads}together — useful for logging.
Minimal autodiff demo:
defmodule MathDemo do
import Nx.Defn
defn f(x), do: Nx.sum(x * x)
end
x = Nx.tensor([1.0, 2.0, 3.0])
Nx.Defn.grad(&MathDemo.f/1).(x)
#=> #Nx.Tensor<[f32[3]] [2.0, 4.0, 6.0]> (df/dx = 2x)
Loss-plus-gradient in one graph traversal — the primitive every custom
training loop builds on (compare Ch 19’s CustomTrainer.train_step/5):
loss_and_grad = Nx.Defn.value_and_grad(&MathDemo.f/1)
{loss, grad} = loss_and_grad.(x)
Computing them separately would run the forward pass twice.
Stability: Subtract Before You Exponentiate
Naive Nx.exp(logits) / sum(...) overflows f32 near logit 89 — exp(88.7)
is the ceiling of f32. The fix is algebraic, not a bigger dtype:
softmax(x) = exp(x - max(x)) / sum(exp(x - max(x)))
logsumexp(x) = max(x) + log(sum(exp(x - max(x))))
defn stable_log_softmax(x) do
Nx.subtract(x, Nx.logsumexp(x, axes: [-1], keep_axes: true))
end
You will rarely write this yourself — Axon losses embed the trick — but recognizing a max-subtraction in library code tells you it is overflow armor, not style.
For per-example maps over a batch, Nx.vectorize/2 is the tool:
defn per_example_loss(t) do
Nx.vectorize(t, :batch)
end
You rarely need vmap/jacobian because Nx ops are naturally batched — an
mlp/2 already runs across a batch dimension, and Axon handles gradients
for you.
17.6 Performance Tips
| Tip | Why |
|---|---|
Use defn | JIT to XLA/MLX — 10–100x vs pure Elixir |
| Pick the right backend | BinaryBackend to debug; EXLA/EMLX for speed (Ch 18) |
| Batch operations | GPU utilization; avoid scalar loops |
| Keep data on device | Don’t Nx.to_flat_list in hot paths |
| Use bf16 | Half memory, faster on modern GPUs / Apple Silicon |
| Compile with fixed shapes | a Nx.template/2 lets XLA specialize per shape |
| Read the fused graph | print_expr/1 from Nx.Defn.Kernel, inside a defn |
Specializing on shape is what defn’s JIT cache keys on, and it is the layer
below Bumblebee’s compile: / Nx.Serving options — those keys specialize
on a batch key, not on a raw shape:
# raw defn: specialize on templates for EVERY argument, then compile once
x_t = Nx.template({32, 784}, :f32)
w1_t = Nx.template({784, 256}, :f32)
b1_t = Nx.template({256}, :f32)
w2_t = Nx.template({256, 10}, :f32)
b2_t = Nx.template({10}, :f32)
compiled =
Nx.Defn.compile(&MathOps.mlp/2, [x_t, %{w1: w1_t, b1: b1_t, w2: w2_t, b2: b2_t}],
compiler: EXLA)
compiled.(real_x, real_params) # a callable, cached by shape
Note the params argument is a map — mlp/2 reads params.w1 etc, and a map
is an Nx.Container, so the whole structure is part of the specialization
key. A compile/3 list must cover every argument, or the resulting closure
raises when called with the missing one.
And to see the graph the compiler will build, print the expression from
inside the defn. import Nx.Defn injects Nx.Defn.Kernel into the
body, so print_expr/1 is available bare and takes an already-built
expression — not a capture plus templates:
defmodule MathOps do
import Nx.Defn
defn traced(x) do
y = Nx.multiply(x, 2)
print_expr(y) # prints #Nx.Tensor< Nx.Defn.Expr ... >
Nx.add(y, 1)
end
end
Verified output shape:
#Nx.Tensor<
f32[2]
Nx.Defn.Expr
parameter a:0 f32[2]
b = multiply 2, a f32[2]
>
Two things that do not work: passing a capture plus templates to
print_expr (print_expr/2’s second argument is IO.inspect options,
not a template list), and Nx.Defn.Debug as a debugging entry point
(@moduledoc false; it is a private compiler shim).
If a benchmark varies shapes, you are timing the compiler — see the harness in Ch 18 §18.8.
17.7 Serialization and Named Axes
Persistence reduces to binaries plus metadata. Nx.serialize/1 is the
reference implementation — simple, not fast; fine for configs and tests:
serialized = Nx.serialize(tensor)
restored = Nx.deserialize(serialized) #=> identical tensor
Hot paths prefer the raw triple — Nx.to_binary/1, Nx.type/1,
Nx.shape/1 — which round-trips through files and network with zero
framing overhead. Ch 21’s ML.Persistence builds on exactly that.
Inside defn, named axes replace positional bookkeeping, so “is axis 1 the
head or the sequence?” stops being a bug class:
defn mean_over_batch(t) do
t
|> Nx.rename([batch: 0, features: 1]) # rename/2 takes a LIST of names
|> Nx.mean(axes: [:batch]) # keyword instead of position 0
end
Names must be set before you use them — Nx.rename/2 on an unnamed tensor
assigns, it does not require.
Adopt them for models with three-plus dimensions; skip for throwaway scripts where positions are obvious.
Explore More
- Nx guides — start with “Tensor basics,” then “Nx.Defn,” then “Compiling functions”
Nx.Defndocs — compiler options, custom transforms, hooks for mid-graph inspection- Autodiff explainer in the Axon book — reverse-mode differentiation with Nx examples (free PDF)
- Practice Lab: Lab 1 — Nx Optimization — gradient ascent, container gradients, and a backend benchmark on an all-new solar-tracker example
- Exercise idea: implement softmax twice — once with plain Elixir lists, once
as
defn— and benchmark on 1M elements to internalize why backends matter
Checkpoint
- Why does
Nx.Randomreturn{tensor, new_key}? - What triggers recompilation in
defn? - What is a “container” in
grad/2?
Answers
- Functional RNG: no global state, reproducible, parallelizable — same key always yields the same sequence.
- A call with input shapes/dtypes not seen before.
- Any structure (tuple/map/list) wrapping trainable parameters; gradients are returned in the identical structure.
Next: Chapter 18 — Backends: EXLA, EMLX & Hardware
Chapter 18 — Backends: EXLA, EMLX & Hardware
The single most important architectural idea in Numerical Elixir:
The Nx API describes the computation (what). The backend decides how it is executed (how).
18.1 The Layered Architecture
flowchart TD
EL["Elixir"] --> NX["Nx"]
NX --> T["Nx.Tensor<br/>data container"]
T --> D["Nx.Defn<br/>compilation hook"]
D --> CB["Compiler / Backend"]
CB --> EXLA["EXLA → XLA<br/>CPU / GPU / TPU"]
CB --> EM["EMLX → MLX<br/>Apple GPU"]
CB --> OTH["Other backends"]
Application logic never knows which backend runs. Swap hardware by swapping configuration.
x = Nx.tensor([1, 2, 3, 4])
Nx.sum(x * x) #=> 30
# Same high-level op, different possible engines:
# - Default backend: pure Elixir loop
# - EXLA: XLA JIT → CPU/GPU kernel
# - EMLX: MLX → Apple Silicon GPU
Two distinctions sharpen this for BEAM developers.
Backend vs compiler. A backend owns tensor storage and op dispatch; a
compiler optimizes a whole traced expression as one unit. BinaryBackend
interprets each op separately — correct and readable, but blind to cross-op
structure. EXLA couples storage with compilation: tensors live in XLA
buffers and your entire defn becomes one fused program. The unit of
optimization, not the language, is where the 10–100x comes from.
Process model. Compiled kernels run as dirty NIFs on dirty schedulers — never blocking normal schedulers, never yielding mid-kernel. XLA brings its own intra-op thread pools beneath that. Your processes stay responsive while native threads burn underneath: the Port/NIF discipline, applied to accelerators.
18.2 Backend Comparison
| Backend | Target | Status | Best For |
|---|---|---|---|
Nx.BinaryBackend (default) | CPU, pure Elixir | Stable | Prototyping, small tensors, CI |
EXLA | XLA → CPU/GPU/TPU | Stable | Production ML, large models |
EMLX | MLX → Apple Silicon GPU | Active | Mac development |
Torchx | LibTorch → CPU/CUDA | Stable | PyTorch interop, CUDA where EXLA is awkward |
TorchScript is not an Nx backend — it is PyTorch’s serialization format,
so it appears nowhere in this table. The LibTorch backend is Torchx
(hex torchx, configured via LIBTORCH_TARGET).
For ONNX models inherited from a Python team, the answer is neither of
these: use Ortex to run the ONNX graph plus Nx.Serving to batch it
(Ch 21). That combination is the practical path for an Erlang shop taking
delivery of ONNX artifacts.
Speed: BinaryBackend is the ~1x baseline; EXLA/EMLX typically deliver 10–100x on real workloads.
Choose deliberately, not by hype:
| Situation | Reach for |
|---|---|
| Debugging numerics, exact intermediate values | BinaryBackend |
| CI without native deps or downloads | BinaryBackend |
| Steady-state training/inference loops | EXLA |
| Apple Silicon dev box, pure Nx/defn work | EMLX |
| GPU production (CUDA/ROCm) | EXLA with the matching client |
The interpreter re-traces on every call — slow, but intermediates survive exactly where a compiler would fuse them away. Prototype there; compile once the numbers look right.
18.3 Configuration
Four setters, and picking the wrong one is the classic “works in iex, fails
in Livebook / fails in the release” bug. They differ in scope:
| Call | Scope | Use for |
|---|---|---|
Nx.default_backend(EXLA.Backend) | this process only | quick per-process demos |
Nx.global_default_backend(EXLA.Backend) | global VM state | Livebooks and IEx |
Nx.Defn.default_options(compiler: EXLA) | this process | setting a compiler without a backend |
config :nx, :default_backend, EXLA.Backend | release config | production |
A GenServer calling Nx.default_backend/1 in its init/1 sets the backend
for that process only — every other process, including Nx.Serving
partitions and Tasks, is unaffected. This is the single most important row
in the table; Ch 21 revisits it where it bites in production.
# Livebook / IEx — global, so other spawned processes inherit it
Nx.global_default_backend(EXLA.Backend)
# Per tensor
x = Nx.tensor([1, 2, 3], backend: EXLA.Backend)
# JIT-compile a defn for a specific compiler (cached)
fun = Nx.Defn.jit(&MyModule.my_fn/1, compiler: EXLA)
# Pre-compile against a fixed template — for a hot loop called repeatedly
compiled = Nx.Defn.compile(&MyModule.my_fn/1, [Nx.template({3}, :s64)], compiler: EXLA)
# Default compiler options, process-wide
Nx.Defn.default_options(compiler: EXLA, client: :host) # :cuda on NVIDIA boxes
Confirm the machine actually has the device you expect, before debugging
anything else. EXLA.Client.get_supported_platforms/0 lists the platforms
XLA registered, and probing by allocating confirms a client initializes:
# does a CUDA client even initialize?
t = Nx.tensor([1.0, 2.0], backend: {EXLA.Backend, client: :cuda})
On a host-only build this raises, and the error names the problem exactly:
Could not find registered platform with name: "cuda".
Available platform names are: Host
That message is the diagnostic — it tells you the build lacks a GPU runtime,
so nothing in your Elixir code will fix it. EXLA.Client.get_supported_platforms/0
returns the same platform list without allocating a tensor.
Clients map names to platforms/devices and are declared up front:
Nx.Defn.jit(&MyModule.my_fn/1, compiler: EXLA, client: :cuda)
Environment variables tune the native runtime rather than Elixir code:
XLA_TARGET=cuda selects a GPU-enabled runtime at dependency-compile
time — set it before mix deps.compile, not just before mix compile. In
Docker that means an ARG/ENV in the build stage, and you must also bake
the downloaded XLA archive into the final image. XLA_FLAGS passes raw XLA
flags through. Both belong in Dockerfiles and CI scripts more than in
Livebooks.
18.4 EXLA — XLA Under the BEAM
EXLA wraps XLA (Accelerated Linear Algebra — Google’s compiler behind TensorFlow/JAX):
flowchart LR
A["Elixir"] --> B["Nx"] --> C["Nx.Defn"] --> D["EXLA"] --> E["XLA"] --> F["CPU / GPU / TPU"]
XLA performs kernel fusion, layout optimization, and memory planning — all invisible to your code. First call compiles; later calls hit the cached executable.
Conceptual run:
defmodule DemoMath do
import Nx.Defn
defn forward(x, params) do
x
|> linear_layer(params.w1, params.b1)
|> relu()
|> linear_layer(params.w2, params.b2)
end
defn linear_layer(x, w, b), do: Nx.dot(x, w) + b
defn relu(x), do: Nx.max(x, 0)
end
Nx.default_backend(EXLA.Backend)
key = Nx.Random.key(42)
x = Nx.Random.uniform(key, shape: {32, 784})
params = %{
w1: Nx.Random.normal(key, shape: {784, 256}),
b1: Nx.broadcast(Nx.tensor(0.0), {256}),
w2: Nx.Random.normal(key, shape: {256, 10}),
b2: Nx.broadcast(Nx.tensor(0.0), {10})
}
DemoMath.forward(x, params) # JIT-compiled via XLA
Production notes:
- Batching: accumulate requests → one batched kernel launch
- Caching: compile once per shape signature
- Memory: XLA manages device memory; BEAM manages host memory
- Requires the
exladep; the XLA runtime downloads automatically from Hex
Two advanced terms you will meet in XLA documentation, defined briefly:
- Buffer assignment / memory planning: allocation and free points are scheduled at compile time via liveness analysis — device memory usage is planned up front, not malloc-as-you-go.
- SPMD sharding: one program compiled to run partitioned across many devices. Nx exposes early sharding support; park it until a single accelerator genuinely limits you.
18.5 EMLX — Apple Silicon via MLX
EMLX targets Apple’s MLX framework, built around unified memory (no copying between CPU and GPU):
flowchart LR
A["Elixir"] --> B["Nx"] --> C["EMLX"] --> D["MLX"] --> E["Apple Silicon<br/>CPU / GPU / Neural Engine"]
Nx.default_backend(EMLX.Backend)
x = Nx.tensor([1.0, 2.0, 3.0, 4.0])
Nx.sum(x * x) #=> 30.0 — running on Metal
Relevant if you develop on MacBook M1–M4, Mac Studio/Pro.
Unified memory is the headline: on discrete-GPU setups every batch crosses the bus twice per pass (upload inputs, download outputs), while MLX arrays share pages between CPU and GPU. Fewer copies, faster dev-loop iteration — at the cost of a runtime that only exists on Apple Silicon, so keep the deploy target independent of the dev box.
18.6 Compatibility Warnings (Read Before Mixing)
Verified 2026-08 against nx 0.13.1 / emlx 0.4.1 / bumblebee 0.7.1. This combination is a moving target — re-check before you hit it.
emlx 0.4.xwas incompatible withnx 0.13+bumblebee: Bumblebee passes abatch_keysoption EMLX did not support, and running a serving raised** (ArgumentError) ... batch_keys. Diagnosis: the error namesbatch_keys, and it appears only under EMLX — swap toEXLA.Backend(which works on macOS, CPU by default). Plain Nx/defnon Apple Silicon → EMLX is fine.
Rule of thumb:
- Bumblebee /
Nx.Servingworkloads → EXLA - Plain Nx/defn exploration on Apple Silicon → EMLX fine
- Deterministic debugging/CI → BinaryBackend
18.7 The Architectural Payoff
flowchart TD
APP["Application logic (Elixir)"] --> NUM["Numerical expression<br/>Nx.Defn / Axon"]
NUM --> BE["Execution backend<br/>EXLA / EMLX / …"]
BE --> HW["Native hardware<br/>CPU / GPU / TPU"]
Elixir can orchestrate. Specialized native runtimes can optimize.
This is the same boundary discipline as calling into a Port/NIF from Erlang — now applied to accelerators.
18.8 A Benchmarking Harness
Opinions about backends deserve measurements. Benchee makes the comparison one command deep:
Mix.install([{:nx, "~> 0.13"}, {:exla, "~> 0.13"}, {:benchee, "~> 1.4"}])
defmodule Bench do
import Nx.Defn
defn softmax(x) do
max = Nx.reduce_max(x, axes: [-1], keep_axes: true)
exp = Nx.exp(x - max)
exp / Nx.sum(exp, axes: [-1], keep_axes: true)
end
end
input = Nx.Random.normal(Nx.Random.key(1), shape: {1024, 1024})
jit = Nx.Defn.jit(&Bench.softmax/1, compiler: EXLA) # compile ONCE, outside the loop
# Move the input onto the device first. Otherwise the "exla" closure JITs
# over a Binary tensor and every call pays a host→device copy — you are
# measuring the transfer, not the kernel.
exla_input = Nx.backend_transfer(input, EXLA.Backend)
# warm up: the first call of a JITed closure includes compilation
Bench.softmax(input)
jit.(exla_input)
Benchee.run(
%{
"binary" => fn -> Bench.softmax(input) end,
"exla" => fn -> jit.(exla_input) end
},
time: 5,
memory_time: 2
)
Reading the report with Erlang eyes:
- The binary backend’s memory column materializes every intermediate; EXLA allocates once.
memory_timemeasures BEAM heap, not device memory. It says nothing about GPU VRAM. For VRAM, useEXLAclient statistics or your accelerator’s own profiler.- Warm up before measuring, and pin shapes — a benchmark that varies shapes benchmarks the compiler, not the kernel.
Explore More
- EXLA docs — compiler options, client/device configuration, GPU setup notes
- EMLX repo — Apple Silicon MLX bindings, unified-memory explanations
- Nx backends guide — write your own toy backend; the best way to learn the behaviour contract
- XLA docs — what fusion/layout optimization actually do under §18.4
- Exercise idea: run the §18.4 demo with
Nx.Defn.Evaluator, then EXLA, and compare timings on{32, 784}×{784, 256}— then change batch size and watch the recompile happen in the logs - Practice Lab: Lab 1 — Nx Optimization — BinaryBackend vs EXLA benchmarked with Benchee on new examples
Checkpoint
- What does the default backend execute on?
- When does XLA recompile an executable?
- Which backend must Bumblebee notebooks use today?
Answers
- Pure Elixir loops (
Nx.BinaryBackend) over CPU binaries. - On first call per shape/dtype signature; results are cached thereafter.
EXLA.Backend(works everywhere incl. macOS CPU).
Next: Chapter 19 — Training Models with Axon
Chapter 19 — Training Models with Axon
Axon builds neural networks as composable Nx.Defn functions. Models are
data — an init function plus a predict function — not mutable objects.
# Model = {init_fn, predict_fn}
{init_fn, predict_fn} = Axon.build(model, compiler: EXLA)
flowchart LR
SPEC["Axon model spec<br/>(composable data)"] --> BUILD["Axon.build"]
BUILD --> INIT["init_fn<br/>shape → params"]
BUILD --> PRED["predict_fn<br/>params + input → output"]
INIT --> LOOP["Axon.Loop.trainer<br/>grad → optimizer step<br/>per batch · per epoch"]
PRED --> LOOP
LOOP --> STATE["trained_state<br/>params + optimizer_state"]
STATE -->|"resume anytime"| LOOP
PRED --> EVAL["Axon.Loop.evaluator<br/>no gradients"]
If you’ve written gen_server state loops, this shape is familiar: pure
functions threaded through an explicit state value — no hidden training
session object, no side effects between steps.
19.0 Setup
Every example in this chapter needs these. In a Livebook cell, or in
mix.exs for a project:
Mix.install([
{:axon, "~> 0.8"},
{:nx, "~> 0.13"},
{:exla, "~> 0.13"},
{:scidata, "~> 0.1"}, # MNIST downloads (§19.1)
{:polaris, "~> 0.1"}, # optimizers and schedules (§19.1)
{:vega_lite, "~> 0.1"} # loss curves (§19.5)
# {:bumblebee, "~> 0.7"} # §19.4 fine-tuning only
])
Axon.Loop.run/4 requires a real compiler — passing Nx.BinaryBackend as
the compiler raises expected compiler callback __jit__/5 is missing. Use
EXLA, or drop compiler: and let the default apply.
19.1 MNIST End-to-End (The Canonical Walkthrough)
Step 1 — Data
# Livebook/IEx: global, so Tasks and spawned processes inherit it.
# In a Mix project use `config :nx, :default_backend, EXLA.Backend` instead.
Nx.global_default_backend(EXLA.Backend)
{images, labels} = Scidata.MNIST.download() # 60k 28x28 grayscale digits
{image_data, image_type, _shape} = images
{label_data, label_type, label_shape} = labels
images =
image_data
|> Nx.from_binary(image_type)
|> Nx.divide(255) # normalize to [0,1]
|> Nx.as_type(:f32) # u8→f32 explicitly; loss fns expect floats
|> Nx.reshape({60000, 784}) # flatten 28x28 → 784
labels = # one-hot: {60000, 10}
label_data
|> Nx.from_binary(label_type)
|> Nx.reshape(label_shape)
|> Nx.new_axis(-1)
|> Nx.equal(Nx.tensor(Enum.to_list(0..9)))
|> Nx.as_type(:f32) # comparison yields u8 — cast it
Why each step matters:
Nx.from_binary/2turns raw bytes into a typed tensor./255normalization helps gradient descent converge.- One-hot via a broadcast
Nx.equal/2producing{60000, 10}of0.0/1.0. - The two
as_type(:f32)calls are not decoration:/255on au8tensor yieldsf32already, butNx.equal/2returnsu8(0/1). Loss functions want floats, and an implicit promotion there is exactly the silent step Erlang developers distrust. (Nx.iota({1, 10})also works, but the explicit tensor reads closer to Scidata’s own README.)
Scidata deserves a nod for Erlang veterans: it downloads, verifies, and
decodes the dataset into raw binaries — the “fetch bytes, parse once, share
everywhere” pattern as file:read_file plus a cached table, except the
cache is the tensor itself. Normalization is not cosmetic: inputs in [0, 1]
keep gradients well-scaled; raw 0–255 magnitudes make SGD oscillate before
it learns anything.
Step 2 — Split & batch lazily
# Scidata.MNIST.download() returns the 60k TRAIN set only. The canonical
# 10k test set is a separate call: Scidata.MNIST.download_test().
#
# The manual split below stays self-contained (one download, and it exercises
# slice_along_axis) at the cost of not being the official split — fine for a
# first run, wrong for a number you intend to publish.
train_images = Nx.slice_along_axis(images, 0, 50_000)
train_labels = Nx.slice_along_axis(labels, 0, 50_000)
test_images = Nx.slice_along_axis(images, 50_000, 10_000)
test_labels = Nx.slice_along_axis(labels, 50_000, 10_000)
batch_size = 64
train_data =
train_images
|> Nx.to_batched(batch_size, leftover: :discard) # lazy Stream of batches
|> Stream.zip(Nx.to_batched(train_labels, batch_size, leftover: :discard))
test_data =
test_images
|> Nx.to_batched(batch_size, leftover: :discard)
|> Stream.zip(Nx.to_batched(test_labels, batch_size, leftover: :discard))
Stream.zip yields {image_batch, label_batch} tuples; only one batch is in
memory at a time.
Peek at the mechanics, because they shape everything downstream.
Nx.to_batched/3 takes a :leftover option:
# default: leftover: :repeat — a short final batch is padded up to full size
Nx.to_batched(t, 64)
# :discard — drop the tail instead, so every batch is exactly 64
Nx.to_batched(t, 64, leftover: :discard)
There is no discard: true option — keyword! rejects it with
unknown key :discard. That distinction decides whether your training loop
recompiles: with the default padding you get constant shapes, so the kernel
compiled for batch one serves every batch and you recompile zero times
mid-epoch. Be explicit either way rather than relying on the default.
Peak activation memory is batch_size × 784 × 4 bytes, not dataset-sized;
the lazy stream is the whole reason.
Step 3 — Model
mnist_model =
Axon.input("input", shape: {nil, 784}) # nil = dynamic batch dim
|> Axon.dense(128, activation: :relu)
|> Axon.dropout(rate: 0.2)
|> Axon.dense(64, activation: :relu)
|> Axon.dropout(rate: 0.2)
|> Axon.dense(10, activation: :softmax)
template = Nx.template({1, 784}, :f32)
Axon.Display.as_graph(mnist_model, template) # Mermaid graph in Livebook
| Layer | Purpose |
|---|---|
Axon.input/2 | Input spec with dynamic batch |
Axon.dense/3 | activation(x @ W + b) |
Axon.dropout/2 | Regularization during training |
Parameter counting is a useful literacy exercise — multiply connected dims, add biases:
dense 784→128: 784 × 128 + 128 = 100,480
dense 128→64: 128 × 64 + 64 = 8,256
dense 64→10: 64 × 10 + 10 = 650
--------
total 109,386
Roughly 109k trainable floats ≈ 437KB in f32 — small enough to train on a
laptop CPU, which is why MNIST remains the canonical first run. Dropout
zeroes a random fraction (rate) of activations per training step — noise
that discourages co-adaptation — and disables itself at inference time.
Step 4 — Train & evaluate with Axon.Loop
trained_state =
mnist_model
|> Axon.Loop.trainer(:categorical_cross_entropy, :sgd)
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(train_data, %{}, epochs: 10, compiler: EXLA)
mnist_model
|> Axon.Loop.evaluator() # no gradients, no optimizer state
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(test_data, trained_state, compiler: EXLA)
The builder pipeline reads top-down, and each stage is just data:
trainer/3fixes loss + optimizer and installs the gradient step.metric/3accumulates named statistics per iteration.run/4drives the loop: batch → forward → grad → update → report.
Nothing hides in macro magic — the loop is a reduction over your stream with a state struct threaded through. That is why you can inject callbacks anywhere (§19.5) or abandon it for §19.2’s manual version.
Two contract details worth pinning down:
-
run/4returns an%Axon.ModelState{}— params, trainable state, and the data/telemetry counters — not anAxon.Loop.State. The struct has no:step_statefield. Passing that return value straight back intoevaluator |> run(data, ...)is correct, and the evaluator needs exactly this: a container the model can use as its parameters. -
Passing
%{}asinitis deprecated — you will seepassing parameter map to initialization is deprecated, use %Axon.ModelState{} instead. There is noModelState.init/1. To build one from a parameter map, useAxon.ModelState.new/1:# resuming: you already HAVE a ModelState from a previous run/4 trained_state = Axon.Loop.run(loop, data, previous_state, epochs: 5) # building from raw params: new/1 takes a map of tensors, not the model state = Axon.ModelState.new(%{"dense_0" => %{kernel: w, bias: b}})For a from-scratch run
%{}still works; for code you intend to keep, thread theModelStatereturned byrun/4.
Because run/4 hands back the model state directly, trained_state can be
passed into run/4 again to resume training later.
Optimizers beyond SGD come from Polaris:
Polaris.Optimizers.adam(learning_rate: 0.001).
Defaults before dogma:
| Problem shape | Loss | Optimizer starting point |
|---|---|---|
| Multi-class classification | categorical cross entropy | Adam @ 1e-3 |
| Binary / sigmoid output | binary cross entropy | SGD + momentum @ 1e-2 |
| Regression | mean squared error | Adam @ 1e-3 |
| Fine-tuning pre-trained | task loss | AdamW @ 1e-5–1e-4 |
Adam converges with little tuning; SGD rewards schedules and momentum with slightly better generalization. On MNIST-scale problems either clears 95% quickly — the engineering margin lives in data handling, metrics, and serving (Ch 21), not in optimizer micro-choice.
Step 5 — Single-image inference
{_, predict_fn} = Axon.build(mnist_model, compiler: EXLA)
{test_batch, _} = Enum.at(test_data, 0)
test_image = Nx.slice_along_axis(test_batch, 0, 1) # keep batch dim {1, 784}
test_image
|> predict_fn.(trained_state) # params first, then input
|> Nx.argmax()
#=> 7 (predicted digit)
predict_fn/2 takes (params, input) — no then/2 needed, and no pipe
required. Models always expect batched input, which is why the slice keeps
the {1, 784} dimension rather than flattening it to {784}.
19.2 Custom Training Loop With defn + grad
When you need non-standard losses or full control over the update:
defmodule CustomTrainer do
import Nx.Defn
defn train_step(x, y, w, b, lr) do
{w, b} =
grad({w, b}, fn {w, b} ->
y_pred = Nx.dot(x, w) + b
Nx.mean(Nx.pow(y_pred - y, 2))
end)
|> then(fn {grad_w, grad_b} -> {w - lr * grad_w, b - lr * grad_b} end)
{w, b}
end
end
key = Nx.Random.key(42)
{x, key} = Nx.Random.normal(key, 0.0, 1.0, shape: {128, 3})
{y, _key} = Nx.Random.normal(key, 0.0, 1.0, shape: {128})
w = Nx.broadcast(0.0, {3})
b = Nx.tensor(0.0)
lr = Nx.tensor(0.01)
# thread the parameters through the loop — a `for` body rebinds only
# within its own iteration, so plain `for` would train ONE step 100 times:
{w, b} =
Enum.reduce(1..100, {w, b}, fn _, {w, b} ->
CustomTrainer.train_step(x, y, w, b, lr)
end)
Three details repay attention. The update is pure: parameters in, new
parameters out — the reduce threads them explicitly, nothing mutates. The
learning rate is a
tensor, not a float, so it joins the compiled graph instead of forcing
a host round-trip per step. And the whole step compiles as one kernel
chain: gradient, scale, and subtract fuse under EXLA exactly as written.
When to use which:
Axon.Loop→ standard supervised learning (batching, metrics, callbacks)defn + grad→ custom losses, gradient surgery, RL, research experiments
19.3 CNNs for Spatial Data
cnn_model =
Axon.input("images", shape: {nil, 28, 28, 1})
|> Axon.conv(32, kernel_size: {3, 3}, activation: :relu)
|> Axon.max_pool(kernel_size: {2, 2})
|> Axon.conv(64, kernel_size: {3, 3}, activation: :relu)
|> Axon.max_pool(kernel_size: {2, 2})
|> Axon.flatten()
|> Axon.dense(128, activation: :relu)
|> Axon.dropout(rate: 0.5)
|> Axon.dense(10, activation: :softmax)
Shape flow (NHWC):
| Layer | In | Out |
|---|---|---|
| input | {? ,28,28,1} | same |
| conv 32×3×3 (valid pad) | {? ,28,28,1} | {? ,26,26,32} |
| max_pool 2×2 | {? ,26,26,32} | {? ,13,13,32} |
| conv 64×3×3 | {? ,13,13,32} | {? ,11,11,64} |
| max_pool 2×2 | {? ,11,11,64} | {? ,5,5,64} |
| flatten | {? ,5,5,64} | {? ,1600} |
| dense 128 / dropout / dense 10 | {? ,1600} | {? ,10} |
Reshape flat data first: Nx.reshape(train_images, {50000, 28, 28, 1}).
Train exactly as in Step 4 with the reshaped data.
Two rules regenerate the whole shape table: valid convolution subtracts
kernel − 1 from each spatial dim (28 → 26, 13 → 11), and pooling
floors a division by the stride (26 → 13, 11 → 5). Channel count moves
only where conv declares it. Walk any architecture through those numbers
before compiling — shape errors surface at trace time, and reading such
tables fluently turns cryptic messages into ten-second fixes.
Why convolutions beat dense on images: flattening destroys locality, forcing a dense layer to relearn that neighboring pixels correlate. Convolutions hard-code local receptive fields with few weights (3×3×channels) and pool for shift tolerance — one function applied across positions, the same reuse-over-copy instinct as good Erlang.
19.4 Transfer Learning With Bumblebee Weights
Ch 20 is the full Bumblebee tour; here it appears only as a source of
pre-trained weights. The data pipeline must be rewired — §19.1’s MNIST
stream yields {images {B, 784}, one_hot_labels}, and a ViT expects
{B, 224, 224, 3} with integer class labels. Reusing train_data here fails
on shape before it ever reaches the loss.
num_classes = 2
# 1. Load spec with a classification head, set your label count.
# id_to_label drives Bumblebee's own postprocessing — an empty map yields
# "LABEL_0"/"LABEL_1" placeholders.
{:ok, spec} =
Bumblebee.load_spec({:hf, "google/vit-base-patch16-224"},
architecture: :for_image_classification
)
spec = Bumblebee.configure(spec, num_labels: num_classes,
id_to_label: %{0 => "cat", 1 => "dog"})
# 2. Load pre-trained weights; head is freshly initialized
{:ok, model_info} =
Bumblebee.load_model({:hf, "google/vit-base-patch16-224"}, spec: spec)
%{model: vit_model, params: params} = model_info
# 3. Extract logits output
logits_model = Axon.nx(vit_model, & &1.logits)
# 4. Train with Axon.Loop.
# sparse: true expects INTEGER labels {B}, not one-hot {B, C}. If your stream
# yields one-hot, drop sparse: and pass the dense matrix instead.
loss = &Axon.Losses.categorical_cross_entropy(&1, &2,
reduction: :mean, from_logits: true, sparse: true)
optimizer = Polaris.Optimizers.adam(learning_rate: 5.0e-5)
loop =
logits_model
|> Axon.Loop.trainer(loss, optimizer, log: 1)
|> Axon.Loop.metric(:accuracy)
# train_data here is a NEW stream yielding {images {B,224,224,3} f32, labels {B} s32}
# — not §19.1's MNIST stream.
Axon.Loop.run(loop, image_data, params, epochs: 3, compiler: EXLA)
strict?: false is off by default; leaving it on means the loop raises on any
JIT cache miss. Keep it on unless you are deliberately tolerating per-shape
recompiles.
Backbone stays pre-trained; only the new head learns — the standard fine-tuning entry point.
Fine-tune in phases: a freshly initialized head emits large gradients that would wreck pre-trained backbone weights on contact.
- Warm up the head. Train a few epochs with the backbone effectively frozen — a tiny learning rate on the whole state, or per-parameter updates that skip backbone tensors.
- Unfreeze gently. Continue full-state training at a much lower rate (1e-5 territory) so pre-trained representations drift, not jump.
Head-only training solves most adaptation tasks; escalate to phase two only when validation accuracy plateaus below target. Every epoch spent relearning general features is an epoch wasted.
19.5 Watching Training: Metrics History
alias VegaLite, as: Vl
{:ok, history_agent} = Agent.start_link(fn -> [] end)
trained_state =
mnist_model
|> Axon.Loop.trainer(:categorical_cross_entropy, :sgd)
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.handle_event(:iteration_completed, fn state ->
Agent.update(history_agent, &[state.metrics | &1])
{:continue, state}
end)
|> Axon.Loop.run(train_data, %{}, epochs: 10)
history = Agent.get(history_agent, & &1) |> Enum.reverse()
# `state.metrics` is a string-keyed map of *tensors* — convert before plotting,
# or VegaLite receives `%Nx.Tensor{}` structs it cannot serialize.
losses = Enum.map(history, &Nx.to_number(&1["loss"]))
accuracies = Enum.map(history, &Nx.to_number(&1["accuracy"]))
Plot with VegaLite’s fold trick (wide → long format):
Vl.new(title: "Training Metrics", width: 600, height: 300)
|> Vl.data_from_values(
epoch: Enum.to_list(1..length(losses)), # one entry per recorded metric
loss: losses,
accuracy: accuracies
)
|> Vl.transform(fold: ["loss", "accuracy"], as: ["metric", "value"])
|> Vl.mark(:line, point: true)
|> Vl.encode_field(:x, "epoch", type: :quantitative)
|> Vl.encode_field(:y, "value", type: :quantitative)
|> Vl.encode_field(:color, "metric", type: :nominal)
|> Kino.VegaLite.new()
In Livebook, Axon.Loop.kino_vega_lite_plot/4 pushes each iteration’s metric
to a Kino.VegaLite plot in one call — worth using instead of the
hand-rolled history agent when you only want a curve. Keep the manual version
when you need the history for something else (checkpoint decisions, exports).
Reading a Confusion Matrix
Loss curves say how much the model is learning; a confusion matrix says
what it confuses. Collect {true, predicted} pairs on the test set and
plot counts as a heatmap:
labels = Enum.map(0..9, &Integer.to_string/1)
counts = [
[972, 0, 1, 0, 0, 2, 3, 1, 1, 0],
[ 0,1121, 3, 2, 0, 1, 2, 2, 4, 0],
[ 1, 2, 986, 6, 2, 1, 3, 6, 3, 0],
# … rows = true digit, columns = predicted digit
]
rows =
for {row, i} <- Enum.with_index(counts),
{v, j} <- Enum.with_index(row),
v > 0 do
%{actual: Enum.at(labels, i), predicted: Enum.at(labels, j), count: v}
end
Vl.new(width: 400, height: 300)
|> Vl.data_from_values(rows)
|> Vl.mark(:rect)
|> Vl.encode_field(:x, "predicted", type: :nominal)
|> Vl.encode_field(:y, "actual", type: :nominal)
|> Vl.encode_field(:color, "count", type: :quantitative)
|> Vl.config(view: [stroke: nil])
The bright diagonal is correct predictions; off-diagonal mass is the error budget. A dark cell at (true 4, predicted 9) points at specific data (4s that look like 9s) rather than generic underfitting — which tells you whether the fix is more data for that pair, augmentation, or capacity.
Overfitting: Signs and Remedies
Train accuracy climbing while test accuracy stalls or falls is the signature of memorization. Remedies, ordered by usual payoff: more or more diverse data, then regularization (dropout, weight decay), then a smaller model, then stopping earlier. Read the plotted gap: widening means memorizing; both curves low means underfitting — the answer there is capacity or training time, not regularization.
When NOT to Use Axon: Scholar and the Manual Loop
Axon is for neural networks. For classical ML — logistic regression,
decision trees, k-means, a tabular model with a few thousand rows — the
right tool is Scholar, which implements scikit-learn’s algorithms as
defn functions on the same backends (Ch 13 §13.4, lab LAB2):
model = Scholar.Linear.LogisticRegression.fit(x, y, num_classes: 2)
Reach for Axon when the architecture is what you are designing (convolutions, attention, embeddings). Reach for Scholar when the algorithm is the thing and the architecture is a row of coefficients.
Validation Split and Early Stopping
Axon.Loop.validate/3 evaluates the model on held-out data after each
epoch, emitting validation_* metrics:
{:ok, best} = Agent.start_link(fn -> %{loss: :infinity, epoch: 0} end)
trained_state =
mnist_model
|> Axon.Loop.trainer(:categorical_cross_entropy, :sgd)
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.validate(mnist_model, val_data)
|> Axon.Loop.handle_event(:epoch_completed, fn state ->
val_loss = state.metrics["validation_loss"]
if val_loss < Agent.get(best, & &1.loss) do
Agent.update(best, fn _ -> %{loss: val_loss, epoch: state.epoch} end)
persist_checkpoint(state) # your save call — see §19.7
end
{:continue, state}
end)
|> Axon.Loop.run(train_data, %{}, epochs: 30)
Keep the best-seen ModelState (not merely its loss) and restore it after
the run — late epochs often regress past the optimum.
Halt atoms. An event handler must return {status, state} where status
is one of exactly three atoms:
:continue # continue this epoch and keep looping
:halt_epoch # end this epoch, start the next
:halt_loop # stop entirely
There is no {:halt, state} — {:halt, state} is not a valid return and
will not stop the loop. {:halt_loop, state} is the hard stop you want.
And you probably should not hand-roll it: Axon ships both of these, and they handle the metric comparison and patience bookkeeping correctly.
mnist_model
|> Axon.Loop.trainer(:categorical_cross_entropy, :sgd)
|> Axon.Loop.validate(mnist_model, val_data)
|> Axon.Loop.early_stop("validation_loss", mode: :min, patience: 3)
|> Axon.Loop.checkpoint(criteria: "validation_loss",
path: "checkpoints",
mode: :min, patience: 5)
|> Axon.Loop.run(train_data, %{}, epochs: 30)
Axon.Loop.checkpoint/2 is also the right answer to “how do I persist the
best model” — see §19.7.
19.6 Custom Layers
gelu_plus_act = fn x, _key -> Axon.Activations.gelu(x) end
dense_with_bias = fn x, w, b, _key -> Nx.add(Nx.dot(x, w), b) end
input = Axon.input("input", shape: {nil, 128})
w = Axon.param("w", {128, 64}, initializer: :glorot_uniform)
b = Axon.param("b", {64})
model =
input
|> then(&Axon.layer(gelu_plus_act, [&1])) # input only
|> then(&Axon.layer(dense_with_bias, [&1, w, b])) # input + params
|> Axon.dense(10, activation: :softmax)
Rules: layer functions receive inputs plus a trailing random key;
Axon.param/2 declares learnable parameters (initializers: :glorot_uniform,
:he_normal, :zeros, …). Use for novel activations, attention variants,
or wrapping raw Nx ops.
19.7 Saving and Loading Trained Models
An Axon.ModelState is tensors plus the model spec, so persistence reduces
to serialization — with one non-negotiable step. You must copy every tensor
to Nx.BinaryBackend first. Axon.ModelState derives Nx.Container, so
the built-in copy walks the whole parameter tree for you (verified on
axon 0.8.1 / nx 0.13.1):
host_state = Nx.backend_copy(trained_state, Nx.BinaryBackend)
File.write!("mnist_state.term", :erlang.term_to_binary(host_state))
restored = "mnist_state.term" |> File.read!() |> :erlang.binary_to_term()
Skip the copy and it appears to work — term_to_binary succeeds, the file
has bytes, and the reload produces a struct. Then the first inference raises:
** (RuntimeError) Invalid buffer passed to Execute() ... Buffer has been deleted or donated.
Because the serialized payload was an EXLA device reference, not data.
Nx.backend_copy/2 and Nx.backend_transfer/2 both recurse through
Nx.Container structs, maps, and tuples, so the single call above reaches
every nested parameter (Nx.Container is the protocol for exactly this job).
Prefer Axon’s own facility when you can — it handles the serialization for you:
|> Axon.Loop.checkpoint(criteria: "validation_loss", path: "checkpoints", mode: :min)
Caveats separating toys from production:
- Tensor payloads survive
term_to_binaryas plain binaries (stable across OTP releases), but treat the wrapper as a BEAM-internal format. - Ch 21’s
ML.Persistencegoes further with explicit type+shape encoding so loads are backend-agnostic. - Store the model spec alongside the parameters; parameters without their
graph are opaque bytes. Pair saved model blobs with JSON metadata
(
saved_at, shapes, training config) — Ch 21’s blueprint shows the pattern.
For cross-language interop, export raw tensors (Nx.to_binary/1 per
parameter plus a manifest) rather than hoping for framework-level formats.
Explore More
- Axon docs — the API reference is unusually readable; each layer doc shows its shape math
- Polaris — the optimizer library (Adam, AdamW, schedulers, gradient clipping)
- Machine Learning in Elixir (Moriarity) — chapters 4–7 cover this chapter’s material in book depth
- Exercise idea: train §19.1’s MLP to >95%, then retrain with dropout removed and compare test accuracy — regularization you can measure
- Practice Labs: Lab 3 — Two Spirals, Lab 4 — Fashion-MNIST CNN, and Lab 5 — Character-Level LSTM — all-new datasets, training discipline, and sequence modeling
Checkpoint
- What two functions does
Axon.build/2return? - Why keep the batch dimension when predicting on one image?
- Where does the classification head’s initial weight come from in transfer learning?
Answers
{init_fn, predict_fn}— parameter initialization and pure forward pass.- Compiled graphs are shape-specialized for batched inputs;
{1, 784}preserves the expected rank. - It doesn’t — it is randomly initialized (
spec:load keeps only backbone weights); you train it on your labels.
Next: Chapter 20 — Bumblebee: Pre-trained Models
Chapter 20 — Bumblebee: Pre-trained Models
Bumblebee runs Hugging Face models directly in Elixir — zero Python, zero conversion. Models download on first run (~6MB–2GB) and cache locally.
20.1 Setup & Backend Rule
Mix.install([
{:bumblebee, "~> 0.7"},
{:axon, "~> 0.8"},
{:nx, "~> 0.13"},
{:exla, "~> 0.13"},
{:stb_image, "~> 0.6"},
{:req, "~> 0.7"}
])
# EXLA, always (see the compatibility note below)
Nx.global_default_backend(EXLA.Backend)
Compatibility, verified 2026-08 against nx 0.13.1 / emlx 0.4.1 / bumblebee 0.7.1 — re-check before trusting it.
emlx 0.4.xwas incompatible with Bumblebee on Nx 0.13: running a serving raised** (ArgumentError) ... batch_keys, because Bumblebee passes abatch_keysoption EMLX did not support. Diagnosis: an error namingbatch_keys, under EMLX only. Fallback:EXLA.Backend, which works on macOS CPU by default. Plain Nx/defnon Apple Silicon → EMLX is fine; this restriction is about Bumblebee’s serving path only.
Use global_default_backend/1 here, not Nx.default_backend/1: Bumblebee
loads and runs models in processes it starts itself, and a process-local
setting would not reach them (Ch 18 §18.3 spells out the four scopes).
What happens under the hood for every recipe below:
flowchart TD
HF["Hugging Face Hub"] --> LOAD["Bumblebee.load_model/1<br/>downloads config + weights (.safetensors)"]
LOAD --> PRE["Preprocessing<br/>tokenizer / featurizer"]
PRE --> JIT["Nx.Defn compilation (EXLA)<br/>→ optimized kernel"]
JIT --> FWD["Model forward pass"]
FWD --> POST["Postprocessing<br/>softmax / normalize / labels"]
POST --> OUT["plain Elixir data structures"]
The Load Triple
Every task below assembles the same three pieces — learn it once, read any recipe forever:
| Piece | Loader | Role |
|---|---|---|
| Model | Bumblebee.load_model/2 | weights + config, the compiled network |
| Tokenizer / Featurizer | load_tokenizer/2, load_featurizer/2 | raw input → ids/pixels/spectrograms |
| Task binding | Bumblebee.Text.*, .Vision.*, .Audio.* | model + pre/post → Nx.Serving |
Boundaries are explicit, in the Erlang tradition: strings never enter the network. They become token ids whose vocabulary, casing, and special tokens must match those the weights were trained against — mismatched pairs degrade silently, no exception raised.
Downloads cache under the OS user-cache directory (~/.cache/bumblebee on
Linux; override with BUMBLEBEE_CACHE_DIR). First load fetches
and verifies; later loads reuse. Deployments point the cache at a mounted
volume and pre-warm it during image build so nodes start inference-ready.
Budget the disk. Realistic cache sizes, so you size a volume instead of
discovering it at deploy time: bart-large-mnli 1.6GB, a ViT 330MB,
whisper-small 466MB, Stable Diffusion 4GB+. Mount, don’t layer.
Gated models (Llama, Mistral and friends) need a token:
{:ok, info} = Bumblebee.load_model({:hf, "meta-llama/Llama-3.2-1B",
auth_token: System.fetch_env!("HF_TOKEN")})
Pass it explicitly, as above — Bumblebee does not read a token from the environment itself. Without one you get a 401 with no useful map — that is the tell.
Two load options worth knowing before you hit VRAM limits:
{:ok, info} = Bumblebee.load_model({:hf, repo}, type: :bf16) # halve memory
{:ok, info} = Bumblebee.load_model({:hf, repo}, backend: EXLA.Backend)
type: :bf16 trades a little precision for roughly half the weights in
memory — usually the right move for a single-GPU box.
What Bumblebee does not do: no text-to-speech, and no training (that is Ch 19/Axon). It is an inference library with a very wide model zoo.
20.2 Text Classification (BERT)
{:ok, model_info} =
Bumblebee.load_model({:hf, "distilbert-base-uncased-finetuned-sst-2-english"})
# The fine-tuned repo lacks a Rust-compatible tokenizer.json;
# load the tokenizer from the base model (same tokenizer architecture).
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "distilbert-base-uncased"})
serving = Bumblebee.Text.text_classification(model_info, tokenizer)
Nx.Serving.run(serving, "This movie was absolutely amazing!")
#=> %{predictions: [%{label: "POSITIVE", score: 0.999}]}
Tokenizer gotcha repeats across repos (NER, QA): when a fine-tuned repo
has no tokenizer.json, pull the tokenizer from its base model. How to
detect it: Bumblebee.load_tokenizer/1 on the fine-tuned repo raises while
loading the tokenizer (or you see an empty/garbled vocabulary). The base
repo ships the same WordPiece/SentencePiece architecture, so swapping the
repo id fixes it. Check the repo’s file listing on the HF Hub first — it is
one page load versus a confusing runtime error.
Mechanically, text_classification/3 compiles tokenize → DistilBERT forward
pass → softmax over the sentiment head. Treat scores as confidence, not
truth: argmax decides, but route sub-threshold scores to human review —
guard clauses for uncertainty. Lists batch naturally,
Nx.Serving.run(serving, [text1, text2]); handy in notebooks, while traffic
at scale belongs behind a supervised serving process (Ch 21).
20.3 Zero-Shot Classification
Classify into arbitrary labels without task-specific training (NLI-based: premise vs “This text is about {label}”, entailment scoring):
{:ok, model_info} = Bumblebee.load_model({:hf, "facebook/bart-large-mnli"})
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "facebook/bart-large-mnli"})
labels = ["New booking", "Update booking", "Cancel booking", "Refund", "Complaint", "delay"]
serving = Bumblebee.Text.zero_shot_classification(model_info, tokenizer, labels)
Nx.Serving.run(serving, "I need a room with two beds for tomorrow")
#=> %{predictions: [%{label: "New booking", score: ...}, ...]}
The NLI framing costs one forward pass per label but makes labels data rather than weights: revise the taxonomy by editing the list, no retraining. Expect softer score distributions than from fine-tuned classifiers — calibrate thresholds on your own texts before trusting absolute numbers.
20.4 Text Generation (GPT-2)
{:ok, model_info} = Bumblebee.load_model({:hf, "openai-community/gpt2"})
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai-community/gpt2"})
{:ok, gen_config} = Bumblebee.load_generation_config({:hf, "openai-community/gpt2"})
# Generation controls live on the generation config, not serving opts
gen_config =
Bumblebee.configure(gen_config,
max_new_tokens: 100,
temperature: 0.7,
strategy: %{type: :multinomial_sampling, top_k: 50}
)
serving =
Bumblebee.Text.generation(model_info, tokenizer, gen_config,
defn_options: [compiler: EXLA]
)
Nx.Serving.run(serving, "The future of Elixir and the BEAM is")
| Parameter | Default | Meaning |
|---|---|---|
max_new_tokens | 20 | Generation length |
temperature | nil | Sampling temperature (sampling only) |
strategy | %{type: :greedy_search} | Decoding method |
no_repeat_ngram_length | nil | Ban repeated n-grams |
Why config-not-opts: decoding strategy is part of the compiled autoregressive
loop (for step in 1..max_new_tokens: logits → filter → sample → append).
Strategies live in the strategy map:
- Greedy (
%{type: :greedy_search}, the default): argmax per step — deterministic, loop-prone;no_repeat_ngram_lengthbreaks the loops. - Sampling (
%{type: :multinomial_sampling, top_k: ..., top_p: ...}):temperaturesharpens or flattens the distribution;top_ktruncates to the k likeliest tokens;top_pkeeps the smallest prefix set whose probabilities sum past p. Temperature 0.7 + top_p 0.9 is a common baseline. - Contrastive search (
%{type: :contrastive_search, top_k: 4, alpha: 0.6}): deterministic and higher quality at a few times the compute. Bumblebee has no beam-search strategy.
In interactive settings perceived latency dominates user judgment, which is why streaming (next) usually matters more than decoding refinements.
Streaming for LiveView
serving =
Bumblebee.Text.generation(model_info, tokenizer, gen_config,
stream: true,
# client: is EXLA's device selector (Ch 18 §18.3) — :cuda on a GPU box.
# Same knob as Nx.Defn.default_options(client: ...)
defn_options: [compiler: EXLA, client: :host]
)
# run/2 now returns a lazy Stream — one chunk per token/step,
# each carrying the cumulative text so far:
stream_result = Nx.Serving.run(serving, prompt)
# look at ONE chunk before wiring anything to a browser — this confirms
# whether you receive cumulative text or deltas, and the exact key set:
IO.inspect(hd(Enum.take(stream_result, 1)))
Enum.each(stream_result, fn chunk ->
[%{text: partial}] = chunk.results
IO.write(partial)
end)
Consume chunks in handle_info and push deltas to the browser.
Chunks carry cumulative text, so the client renders the latest chunk as-is — no assembly logic. Pipe deltas through PubSub: serving → broadcast → LiveView → browser, while the serving process keeps admitting other requests the whole time.
20.5 Vision: Image Classification & Embeddings
# Classification with ViT (~86M params, ImageNet)
{:ok, model_info} = Bumblebee.load_model({:hf, "google/vit-base-patch16-224"})
{:ok, featurizer} = Bumblebee.load_featurizer({:hf, "google/vit-base-patch16-224"})
serving =
Bumblebee.Vision.image_classification(model_info, featurizer,
top_k: 5,
compile: [batch_size: 1],
defn_options: [compiler: EXLA, client: :host]
)
image_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png"
{:ok, %Req.Response{body: image_data}} = Req.get(image_url)
image = StbImage.read_binary!(image_data)
Nx.Serving.run(serving, image)
#=> %{predictions: [%{label: "beignet", score: 0.98}, ...]}
Featurizer pipeline: resize to 224×224 → normalize → patchify into 16×16 patches.
# CLIP image embeddings — note the explicit vision module selector
{:ok, clip_info} =
Bumblebee.load_model({:hf, "openai/clip-vit-base-patch32"},
module: Bumblebee.Vision.ClipVision # repo has both encoders!
)
{:ok, featurizer} = Bumblebee.load_featurizer({:hf, "openai/clip-vit-base-patch32"})
serving =
Bumblebee.Vision.image_embedding(clip_info, featurizer,
compile: [batch_size: 1],
defn_options: [compiler: EXLA, client: :host]
)
%{embedding: emb} = Nx.Serving.run(serving, image) # L2-normalized vector
Use embeddings for similarity search (dot product ≈ cosine), clustering, zero-shot classification against text embeddings.
Sizing intuition: ViT-base is ~86M params ≈ 330MB in f32 (halved in bf16);
CLIP ships two towers, so load only the encoder you call. Compiled
executables pin shapes — compile: [batch_size: 1] trades batching
flexibility for steady single-request latency, the right trade until volume
proves otherwise.
20.6 NER and Question Answering
# Named Entity Recognition
{:ok, ner_info} = Bumblebee.load_model({:hf, "dslim/bert-base-NER"})
{:ok, ner_tok} = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-cased"})
serving = Bumblebee.Text.token_classification(ner_info, ner_tok, aggregation: :same)
Nx.Serving.run(serving, "Apple Inc. is based in Cupertino, California.")
#=> %{entities: [%{label: "ORG", phrase: "Apple Inc.", score: 0.99}, ...
# %{label: "LOC", phrase: "Cupertino"}, ...]}
Aggregation strategies: nil (per-token), :same (merge consecutive
same-label subwords — the usual NER choice), plus :word_first,
:word_average, :word_max.
Why aggregation exists: WordPiece splits “Cupertino” into subword tokens,
each scored independently. :same stitches consecutive same-label subwords
back into phrases — the difference between a bag of token scores and the
clean entity list shown above.
# Extractive QA
{:ok, qa_info} = Bumblebee.load_model({:hf, "deepset/roberta-base-squad2"})
{:ok, qa_tok} = Bumblebee.load_tokenizer({:hf, "FacebookAI/roberta-base"})
serving = Bumblebee.Text.question_answering(qa_info, qa_tok)
Nx.Serving.run(serving, %{
question: "What does Elixir run on?",
context: "Elixir runs on the BEAM VM, which provides massive concurrency."
})
#=> %{results: [%{text: "the BEAM VM", score: 0.95, start: 11, end: 20}]}
20.7 Text Embeddings for Semantic Search
{:ok, model_info} =
Bumblebee.load_model({:hf, "sentence-transformers/all-MiniLM-L6-v2"})
{:ok, tokenizer} =
Bumblebee.load_tokenizer({:hf, "sentence-transformers/all-MiniLM-L6-v2"})
serving =
Bumblebee.Text.text_embedding(model_info, tokenizer,
output_attribute: :hidden_state, # select token-level output...
output_pool: :mean_pooling, # ...then pool tokens...
embedding_processor: :l2_norm # ...then normalize
)
texts = [
"Elixir is a functional programming language",
"The BEAM provides massive concurrency",
"Phoenix is a web framework for Elixir"
]
results = Nx.Serving.run(serving, texts) # 384-dim each
embeddings = Nx.stack(Enum.map(results, & &1.embedding)) # {3, 384}
[%{embedding: query_emb}] = Nx.Serving.run(serving, ["How does Elixir handle concurrency?"])
scores = Nx.dot(embeddings, query_emb) |> Nx.to_flat_list() #=> {3}
# pick argmax — L2-normalized so dot product == cosine similarity
Note the shape on that dot: embeddings is {3, 384} and query_emb is
{384}, so Nx.dot/2 contracts the last axis against the first and yields
{3} — one score per document. Nx.transpose/1 on a rank-1 tensor is the
identity, so wrapping query_emb in it would look meaningful and change
nothing.
(output_attribute: :hidden_state is needed because the default pooled state
is already rank-2; you must pool from rank-3 token states.)
A ranking helper, boring on purpose:
defmodule SemanticSearch do
def top_k(query_embedding, doc_embeddings, k \\ 3) do
doc_embeddings
|> Nx.dot(query_embedding) # {n, dim} · {dim} → {n}
|> Nx.to_flat_list()
|> Enum.with_index()
|> Enum.sort(:desc)
|> Enum.take(k)
end
end
L2-normalized vectors make dot product equal cosine similarity, bounded in
[-1, 1]. Brute-force ranking stays snappy into the tens of thousands of
documents; graduate to pgvector/HNSW only when measurement says so.
Calibrate “similar” thresholds per model and corpus — 0.3+ often relates for
MiniLM-class encoders, but trust your data over folklore.
20.8 Stable Diffusion (GPU Recommended)
Multi-component load; bfloat16 halves memory (~4GB VRAM for SD 1.5):
# NOTE: the original "runwayml/stable-diffusion-v1-5" repo was taken down;
# the community mirror lives under the stable-diffusion-v1-5 org:
repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
opts = [type: :bf16]
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai/clip-vit-large-patch14"})
{:ok, text_encoder} = Bumblebee.load_model({:hf, repo_id, subdir: "text_encoder"}, opts)
{:ok, unet} = Bumblebee.load_model({:hf, repo_id, subdir: "unet"}, opts)
{:ok, vae} = Bumblebee.load_model({:hf, repo_id, subdir: "vae"}, [architecture: :decoder] ++ opts)
{:ok, scheduler} = Bumblebee.load_scheduler({:hf, repo_id, subdir: "scheduler"})
{:ok, safety_checker} = Bumblebee.load_model({:hf, repo_id, subdir: "safety_checker"}, opts)
{:ok, featurizer} = Bumblebee.load_featurizer({:hf, repo_id, subdir: "feature_extractor"})
serving =
Bumblebee.Diffusion.StableDiffusion.text_to_image(
text_encoder, unet, vae, tokenizer, scheduler,
num_steps: 20,
guidance_scale: 7.5,
num_images_per_prompt: 2,
safety_checker: safety_checker,
safety_checker_featurizer: featurizer,
compile: [batch_size: 1, sequence_length: 77],
defn_options: [compiler: EXLA]
)
Kino.start_child({Nx.Serving, name: :stable_diffusion, serving: serving})
output =
Nx.Serving.batched_run(:stable_diffusion, %{
prompt: "A futuristic Elixir logo, glowing purple, cyberpunk style",
negative_prompt: "blurry, low quality"
})
Tuning: num_steps 20–50 (quality vs speed), guidance_scale ~7.5 (prompt
adherence), bf16 on Ampere+/Apple Silicon.
The negative prompt is guidance, not filtering: classifier-free guidance
computes a conditional and an unconditional direction each step and pushes
away from the latter — substituting your negative prompt’s embeddings for
the unconditional branch steers composition. Keep num_images_per_prompt
consistent with compile: [batch_size: ...], or shape specialization will
recompile per mismatch.
20.9 Model Selection Cheat Sheet
| Task | Model | Size |
|---|---|---|
| Sentiment | distilbert-base-uncased-finetuned-sst-2-english | 250MB |
| Zero-shot | facebook/bart-large-mnli | 1.6GB |
| Generation | openai-community/gpt2-medium | 1.5GB |
| Chat generation | a small instruct model your provider serves (HF_TOKEN + {:hf, repo, auth_token: ...}) | varies |
| Image class | microsoft/resnet-50 | 100MB |
| Image class | google/vit-base-patch16-224 | 330MB |
| Image embed | openai/clip-vit-base-patch32 | 330MB |
| Image embed | google/siglip-base-patch16-224 | 330MB |
| Speech→text | openai/whisper-tiny → -base → -small | 39/142/466MB |
| Text embed | sentence-transformers/all-MiniLM-L6-v2 | 90MB |
| Text embed | sentence-transformers/all-mpnet-base-v2 | 420MB |
| Text embed (retrieval-tuned) | intfloat/e5-small-v2, Qwen/Qwen3-Embedding-0.6B | 130MB+ |
| Text-to-image | stable-diffusion-v1-5/stable-diffusion-v1-5 | 4GB+ |
Browse more: https://huggingface.co/models?library=bumblebee
Selection heuristics: pick the smallest model clearing your quality bar — download size, RAM footprint, and latency scale together, and a tiny variant serving today beats a large variant arriving next sprint. Latency-sensitive paths want distilled checkpoints (DistilBERT, MiniLM); offline quality-maximal jobs can afford bart-large. Read each model card’s license before shipping.
20.10 Speech-to-Text With Whisper
Same triple, audio edition: the featurizer turns PCM samples into log-mel spectrograms; the decoder emits text tokens autoregressively.
{:ok, model_info} = Bumblebee.load_model({:hf, "openai/whisper-tiny"})
{:ok, featurizer} = Bumblebee.load_featurizer({:hf, "openai/whisper-tiny"})
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai/whisper-tiny"})
{:ok, generation_config} = Bumblebee.load_generation_config({:hf, "openai/whisper-tiny"})
generation_config =
Bumblebee.configure(generation_config, max_new_tokens: 100)
serving =
Bumblebee.Audio.speech_to_text_whisper(model_info, featurizer, tokenizer, generation_config,
# `compile:` accepts only `:batch_size` for Whisper. The featurizer sizes
# each chunk to 30s of audio (`encoder_max_positions` is 1500, doubled by
# Whisper's 2× conv frontend), and longer input is chunked internally.
# There is no per-chunk `sequence_length` knob to raise.
compile: [batch_size: 1]
)
Input is a map of raw PCM data plus its sample rate — decode and resample
to 16kHz yourself (FFmpeg, or Kino.Input.audio/1 in Livebook):
Nx.Serving.run(serving, %{"data" => pcm_binary, "sampling_rate" => 16000})
#=> %{chunks: [%{text: "transcribed speech appears here", ...}]}
Practice notes:
- Start with
whisper-tiny(39MB) and upgrade on evidence —-base,-smallbuy accuracy with download size and latency. - Long recordings are chunked internally; tiny/base transcribe near real-time on laptop CPUs.
- Multilingual out of the box; language and task (transcribe vs translate) come from the model config.
Explore More
- Bumblebee docs — every supported architecture and task, with runnable examples per task module
- Bumblebee examples folder — Livebooks for SD, Whisper speech-to-text, and more
- Hugging Face Hub — filter by
bumblebeelibrary tag; model cards list required featurizer/tokenizer companions - Exercise idea: build a tiny semantic search over your own notes using §20.7’s embedding serving plus a brute-force dot-product ranking — then swap in pgvector once it works
- Practice Labs: Lab 6 — Semantic Search and Lab 5 — Character-Level LSTM — new E5/cross-encoder/NER and generation examples
Checkpoint
- Why load a tokenizer from the base model sometimes?
- Where do
top_k/temperaturego — serving options or generation config? - What makes CLIP loading different from ViT?
Answers
- Fine-tuned repos often lack a Rust-compatible
tokenizer.json; the base repo ships the same tokenizer architecture. - The generation config — they parameterize the compiled decoding loop.
- The repo contains both vision and text encoders, so pass
module: Bumblebee.Vision.ClipVisionto select the encoder.
Next: Chapter 21 — Production Inference: Nx.Serving
Chapter 21 — Production Inference: Nx.Serving
Nx.Serving provides batched, concurrent inference — and it is a plain OTP
process tree, so everything you know about supervision applies. This chapter
covers the API, then assembles a complete production blueprint — an MNIST
serving Phoenix app — module by module.
21.1 Why Batching Matters
flowchart TD
R1["Request 1"] --> W["batching window<br/>wait up to batch_timeout ms<br/>OR until batch_size reached"]
R2["Request 2"] --> W
R3["Request 3"] --> W
RN["…Request N"] --> W
W --> STACK["stack into one batch tensor<br/>{N, C, H, W}"]
STACK --> PASS["single forward pass<br/>on the accelerator"]
PASS --> SPLIT["split results<br/>each caller gets its answer"]
On GPU this is routinely 10–100x higher throughput than sequential calls.
Work one concrete example — assume a forward pass costs ~20ms whether the batch holds 1 or 32 items (true until the accelerator saturates):
| Config | Added worst-case latency | Throughput ceiling |
|---|---|---|
| size 1, timeout 0ms | none | 50 req/s — one pass per request |
| size 32, timeout 5ms | ~5ms wait | 1,600 req/s |
| size 64, timeout 20ms | ~20ms wait | 3,200 req/s |
batch_timeout bounds only the wait for the first arrival: under load,
batches fill instantly and the timeout never binds; idle systems pay the
full window per request. Practical calibration — timeout at a fraction of
your latency budget, size near observed concurrency, raise size only while
telemetry (§21.2) shows batches filling early. And batching is not always
a win: rare, latency-bound calls (a nightly cron job) gain nothing from
waiting for company.
21.2 The API
Wrap any function as a serving:
{init_fn, predict_fn} = Axon.build(mnist_model)
# Keep captured params on the binary backend so Nx can inline them into JIT
params =
init_fn.(Nx.template({32, 784}, :f32), Axon.ModelState.empty())
|> Nx.backend_copy(Nx.BinaryBackend)
serving = Nx.Serving.jit(fn batch -> predict_fn.(params, batch) end)
Start it supervised:
{:ok, _pid} =
Nx.Serving.start_link(
name: :mnist_classifier,
serving: serving,
batch_size: 32, # max requests per batch
batch_timeout: 5 # max ms to wait filling a batch
)
Call it:
# simple (executes inline in the calling process — wrap input in a batch):
Nx.Serving.run(serving, Nx.Batch.concatenate([image]))
# through the named, batching process (joins other concurrent callers):
Nx.Serving.batched_run(:mnist_classifier, Nx.Batch.concatenate([image]))
Client-side streaming decouples submitting work from consuming results —
wrap a serving and run/2 returns a lazy stream of {:batch, output, metadata} events. (Hook messages, when enabled, appear as
{hook_name, payload} in the same stream, so match those separately.)
streaming = Nx.Serving.streaming(serving)
stream = Nx.Serving.run(streaming, Nx.Batch.concatenate([image]))
for {:batch, output, _metadata} <- stream do
send(self(), {:chunk, output})
end
The stream is consumed in the calling process — nothing polls in the
background. If you hand it to a Task and drop the reply, nothing renders
the output.
Built for token-by-token LLM output (Ch 20’s stream: true) and any
generation long enough that partial results keep callers alive.
| Option | Meaning |
|---|---|
name | registered name for batched_run/2 |
serving | %Nx.Serving{} from jit/2 or Bumblebee |
batch_size / batch_timeout | batching window knobs |
Lifecycle is pure OTP. The supervised serving process receives batched_run/2
calls synchronously: while it executes a batch, later callers wait in its
mailbox. There is no hidden worker pool to tune; scale by adding named
servings (per model variant or tenant) and let routing spread load. Shutdown
honors supervisor semantics — give the child a sensible shutdown value so
in-flight batches drain on deploy.
An unbounded mailbox is buffering, not admission control. Callers queue,
they are not rejected; under a burst the queue grows until the BEAM runs out
of memory, and GenServer.call’s timeout becomes your only backpressure —
which surfaces to users as a 500, not a 503. Bound concurrency at the
caller, where you can still do something about it:
# in the controller — batched_run/3 has no timeout option; bound the wait here
task = Task.async(fn -> Nx.Serving.batched_run(:mnist_classifier, batch) end)
case Task.yield(task, 2_000) || Task.shutdown(task, :brutal_kill) do
{:ok, results} -> json(conn, %{prediction: results})
nil -> conn |> put_status(:service_unavailable) |> json(%{error: "busy"})
end
A semaphore in front of the serving (Ch 26’s pattern) bounds the in-flight count; the caller-side timeout above plus a 503 is the honest alternative. Pick one deliberately — the queue depth is not a policy.
Telemetry: [:nx, :serving, :execute], [:nx, :serving, :preprocessing],
[:nx, :serving, :postprocessing] — span events with :start/:stop
variants carrying duration (in native units). Attach to the :stop
events:
:telemetry.attach_many(
"mnist-serving",
[
[:nx, :serving, :execute, :stop],
[:nx, :serving, :preprocessing, :stop],
[:nx, :serving, :postprocessing, :stop]
],
fn event, measurements, _metadata, _config ->
ms = System.convert_time_unit(measurements.duration, :native, :microsecond)
Logger.info("#{inspect(event)} #{ms}µs")
end,
nil
)
There is no [:nx, :serving, :latency] event — if you want a latency chart,
derive one from :execute, :stop with a Telemetry.Metrics.summary.
Two scaling options this section has not covered yet, both relevant on real fleets:
partitions: truespreads a serving across multiple devices, andNx.Serving.batched_run/3can route to whichever node in the cluster holds the serving — every node must run the same Nx version.- Scale horizontally behind a load balancer: one serving per node, sticky or hash-routed, with weights pinned per node (Ch 09 §9.6 covers rolling weights out).
21.3 Case Study: A Production MNIST Serving App
The blueprint: a Phoenix app that trains an Axon MLP via a mix task,
persists weights, and serves predictions through a supervised Nx.Serving.
Assemble it from parts you already know:
mix phx.new mnist_phoenix --live
cd mnist_phoenix
# add deps: {:axon, "~> 0.8"}, {:exla, "~> 0.13"}, {:scidata, "~> 0.1"}
Four ML modules carry the entire design — ML.Model is Ch 19 in module
form; the other three apply §21.2 to real lifecycle concerns. Once running,
the interfaces look like this:
mix mnist.train --epochs 10 # trains + saves weights to priv/models/
# mix mnist.retrain --epochs 5 # continue from the saved model
mix phx.server # http://localhost:4000 → draw a digit
curl -X POST http://localhost:4000/api/predict \
-H 'content-type: application/json' \
-d '{"image":"<base64-encoded-784-byte-image>"}'
The supervision tree
def start(_type, _args) do
children = [
MnistPhoenixWeb.Telemetry,
{DNSCluster, query: ...},
{Phoenix.PubSub, name: MnistPhoenix.PubSub},
MnistPhoenix.ML.ServingManager, # ← ML lifecycle as a GenServer
MnistPhoenixWeb.Endpoint # web last, as usual
]
Supervisor.start_link(children, strategy: :one_for_one, name: MnistPhoenix.Supervisor)
end
The ML stack is just more children in the tree you already understand:
flowchart TD
SUP["MnistPhoenix.Supervisor"] --> TEL["Telemetry"]
SUP --> DNS["DNSCluster"]
SUP --> PS["PubSub"]
SUP --> SM["ML.ServingManager<br/>GenServer — model lifecycle"]
SM --> SERVE[":mnist_classifier<br/>Nx.Serving — batched inference"]
SUP --> EP["Web.Endpoint<br/>HTTP last, as usual"]
Layer by layer
ML.Model — pure model definition & data prep (Axon.input → dense → dropout → dense → softmax; MNIST download/normalize/one-hot; train,
evaluate, build_predict_fn). Same content as Ch 19, in module form.
ML.Persistence — saves Axon.ModelState to priv/models/ via
:erlang.term_to_binary, with explicit encode/decode for tensors:
defp encode_term(%Nx.Tensor{} = tensor),
do: {:tensor, Nx.type(tensor), Nx.shape(tensor), Nx.to_binary(tensor)}
defp decode_term({:tensor, type, shape, binary}),
do: binary |> Nx.from_binary(type) |> Nx.reshape(shape)
Plus JSON metadata (saved_at) alongside.
ML.ServingManager — GenServer owning the lifecycle:
# config/runtime.exs — the backend is selected ONCE, for the whole node
config :nx, :default_backend, EXLA.Backend
# lib/mnist_phoenix/ml/serving_manager.ex
def init(_opts) do
# NO Nx.default_backend/1 here. It is process-local: setting it in this
# GenServer's init does NOT reach the Nx.Serving partition workers, which
# are separate processes doing the actual tensor work. Ch 18 §18.3 has the
# four setters and their scopes.
case load_model_and_start_serving() do
{:ok, model, params} -> {:ok, %{model: model, params: params, serving_started: true}}
{:error, _reason} -> {:ok, %{model: nil, serving_started: false}} # degrade, don't crash boot
end
end
(“Degrade, don’t crash boot” is the right call here and wrong for most supervisors. Serving is the app’s reason to exist, so you may prefer a failed start — decide per app, and be deliberate either way.)
Also handles :status calls and {:retrain, opts} — retraining can happen
live without restarting the endpoint.
ML.Serving — starts the batched serving, decodes the wire format, and
exposes typed entry points. The curl above posts base64; nothing decodes it
yet, and that glue is the part you always end up writing:
@serving_name :mnist_classifier
@batch_size 32
@batch_timeout 5
# The controller hands a base64 string; tensors must never come from JSON.
defp decode_image!(%{"image" => b64}) when is_binary(b64) do
b64
|> Base.decode64!()
|> Nx.from_binary(:u8)
|> Nx.reshape({1, 784})
|> Nx.as_type(:f32)
|> Nx.divide(255)
end
# ...and the response goes back out as labels + confidence, never raw logits.
defp encode_prediction(logits) do
%{label: Nx.to_number(Nx.argmax(logits, axis: 1)),
confidence: logits |> Nx.exp() |> Nx.sum(axis: 1) |> Nx.to_flat_list()}
end
Then the serving itself:
def start_serving(model, params) do
predict_fn = Model.build_predict_fn(model)
serving_params = Nx.backend_copy(params, Nx.BinaryBackend)
# Nx.Serving.jit/2 IS `new/1` with the jit wrapper already applied —
# do not call new/1 on its result.
{:ok, _} =
Nx.Serving.jit(fn batch -> predict_fn.(serving_params, batch) end)
|> Nx.Serving.process_options(batch_size: @batch_size, batch_timeout: @batch_timeout)
|> then(&Nx.Serving.start_link(name: @serving_name, serving: &1))
{:ok, params}
end
The callback passed to Nx.Serving.jit/1 takes one argument — the
%Nx.Batch{} — and jit/2 is literally new(fn opts -> Nx.Defn.jit(fun, opts) end).
Do not re-wrap its result with new/1; that expects a function, not an
%Nx.Serving{}.
The batch-keyed form Nx.Serving.new(fn key, opts -> ... end) is only worth
the extra indirection once you actually produce keys with Nx.Batch.key/2
and declare batch_keys: in process_options (see Nx.Serving’s docs for
the two-key example). Without a key producer, the batch key is dead
complexity — and Bumblebee does pass keys, which is why its path hits that
EMLX incompatibility in Ch 18.
Serving input is a %Nx.Batch{}, not a tensor. That is why every caller
goes through Nx.Batch.concatenate/1 — it adds the batch axis and marks the
structure as batched:
def predict_single(image) do
image
|> ensure_batch_dim() # {784} → {1, 784}
|> then(&Nx.Batch.concatenate([&1]))
|> Nx.Serving.batched_run(@serving_name)
|> Nx.argmax(axis: 1)
|> Nx.to_number()
end
def predict_batch(images) do
images
|> ensure_batch_dim()
|> then(&Nx.Batch.concatenate([&1]))
|> Nx.Serving.batched_run(@serving_name)
|> Nx.argmax(axis: 1)
|> Nx.to_flat_list()
end
# Shape validation lives at the boundary — and it is only useful if the
# helper actually exists. Here it is:
defp ensure_batch_dim(t) when is_struct(t, Nx.Tensor) do
case Nx.rank(t) do
1 -> Nx.new_axis(t, 0) # {784} → {1, 784}
2 -> t # already {B, 784}
r -> raise ArgumentError, "expected {784} or {B, 784}, rank #{r}"
end
end
Without that guard a single image arrives as {784}, the model’s first
Nx.dot broadcasts against a weight matrix expecting a batch dim, and you
get a shape error 200ms downstream instead of a clear message at the edge.
Mix.Tasks.Mnist.Train / Mnist.Retrain — ops tasks wrapping the same
modules:
mix mnist.train --epochs 20 --batch-size 128
Tasks call Trainer.train_and_save/1 → prepare data → train → evaluate →
persist.
Telemetry Wiring and Warmup
Attach handlers once at boot — the events carry batch sizes and latencies, ready for LiveDashboard or any metrics backend:
:telemetry.attach_many(
"serving-metrics",
[
[:nx, :serving, :execute, :stop],
[:nx, :serving, :preprocessing, :stop],
[:nx, :serving, :postprocessing, :stop]
],
fn event, measurements, _meta, _cfg ->
Logger.info("#{inspect(event)}: #{inspect(measurements)}")
end,
nil
)
One operational subtlety: compilation is per-boot and per-shape-signature. The first real request after a deploy pays it — so health checks should send a synthetic prediction (a zeros tensor works) before marking the node ready. Kubernetes users know this as a readiness probe; here it doubles as JIT warmup.
Lessons to steal
- Model lifecycle is a process: load-on-boot, health via
:status, hot retrain via messages. - Params are immutable data: copy to BinaryBackend once; capture in the JIT closure.
- Persistence is explicit: serialize tensors with type+shape so loads are backend-agnostic.
- Degrade gracefully: missing model file ≠ crashed app; the page renders and reports serving status.
- Batching knobs live next to the serving, not scattered across callers.
Deployment notes specific to EXLA-based releases:
- Bake dependencies (and the downloaded XLA runtime archive) into the release image; nodes must not fetch runtimes at boot.
- Pre-populate the model directory (
priv/models/) in the image or mount it — first-boot downloads are an outage waiting to happen. - Container memory must cover weights + activations + BEAM heap; watch RSS under load, not just at idle.
- Keep backend selection in one place —
config/runtime.exs, orNx.global_default_backend/1for a notebook. Not a GenServerinit/1:Nx.default_backend/1is process-local and would not reach the serving workers (Ch 18 §18.3).
21.4 A Reviewer’s Checklist for Inference Services
Before shipping any Nx.Serving-based service, walk this list — each row
maps back to material above:
| Concern | Question | Reference |
|---|---|---|
| Supervision | Serving a supervised child with sane shutdown? | §21.2 |
| Degradation | Missing/corrupt model file degrades, not crashes? | §21.3 |
| Shapes | Input validated at the boundary (rank, dtype, size)? | §21.3 |
| Batching | Size/timeout match measured traffic, not guesses? | §21.1 |
| Observability | batch_size/latency telemetry attached? | §21.3 |
| Warmup | Readiness gating absorbs first-call compilation? | §21.3 |
| Artifacts | Weights versioned and pinned beside the release? | §21.3 |
| Backend | Platform selection centralized and reviewable? | Ch 18 |
The meta-point for Erlang practitioners: none of this is novel machinery.
It is gen_server etiquette, supervisor hygiene, and telemetry discipline —
applied to tensors. Once the model is just another supervised process with
an API, production AI stops feeling special.
Explore More
- Nx.Serving docs — streaming servings, process options, and the full telemetry event list
Nx.Batch— concatenate vs pad, per-batch compilation keys- Build the §21.3 blueprint yourself, then break one piece on purpose (delete a model file) to watch graceful degradation work
- Telemetry guide — wire
[:nx, :serving, :execute, :stop]into a LiveDashboard chart - Exercise idea: add a probabilities endpoint to your blueprint app — return all ten logits after softmax instead of only the argmax digit
- Practice Labs: Lab 4 — Fashion-MNIST CNN and Lab 6 — Semantic Search — train-then-serve discipline and multi-model serving on all-new examples
Checkpoint
- Difference between
Nx.Serving.run/2andbatched_run/2? - Where does the app change backends per platform?
- How would you add a second model to the same app?
Answers
run/2executes inline (own single batch);batched_run/2goes through the registered serving process and joins other concurrent callers’ batches.config/runtime.exs(config :nx, :default_backend, EXLA.Backend).- Define its serving under a new name in
ML.Serving, add it to the supervision children (or ServingManager), callbatched_run(OtherName, ...).
Next: Chapter 28 — LLM Integration & Agents — skipping Part V (Ch 22–27) because the AI track goes straight to agents. If you want the OTP mechanics under the hood before that, detour to Chapter 22 — Processes through Chapter 27 — Debugging & Tracing.
Chapter 22 — Processes Deep Dive: The Raw Material
Everything you will ever build on the BEAM — Phoenix channels, Ecto pool workers, Nx serving batches, Oban jobs — is arrangements of one primitive: the process. You know this material from Erlang; this chapter re-grounds it in Elixir syntax and goes deeper than day-to-day code requires, because Chapters 23–24 (GenServer, supervisors) are disciplined shapes of what we unpack here.
From Erlang you know: nothing here is semantically new.
spawn, mailboxes, links, monitors, exit signals — identical machinery, same BIFs underneath. Elixir adds a tidier surface (Process, macros likereceive) and tooling. Every construct in this chapter has a direct:erlangequivalent.
22.1 Spawn, Send, Receive — the Whole Vocabulary
A process owns a heap, a stack, a mailbox, and a run queue entry. It runs one function to completion and then waits on its mailbox. Three verbs cover most of process programming:
pid = spawn(fn -> receive do {:hello, from} -> send(from, :hi) end end)
send(pid, {:hello, self()})
receive do :hi -> :done end
The Elixir-to-Erlang translation is mechanical:
| Elixir | Erlang equivalent | Notes |
|---|---|---|
self() | self() | caller’s pid |
spawn/1, spawn_link/1 | spawn/1, spawn_link/1 | fun-based |
spawn(Mod, :fun, [args]) | spawn/3 | MFA form |
send(dest, msg) | Dest ! Msg | never fails, even for dead pids |
receive do ... end | receive Clauses end | selective, scans whole mailbox |
Process.exit(pid, reason) | exit(Pid, Reason) | sends an exit signal |
Process.alive?(pid) | erlang:is_process_alive/1 | |
Process.info(pid) | process_info/1 | introspection dump |
Two properties shape everything downstream:
send/2is unconditional. Sending to a dead or nonexistent pid silently discards the message. Delivery failures surface only through links and monitors — never throughsend.receiveis selective. It scans the mailbox oldest-first and runs the first matching clause; non-matching messages stay put, in order. This is the foundation of request/response over an unordered pipe.
Step-by-step: a conversation between two processes
Type this in iex:
me = self()
pid =
spawn(fn ->
receive do
{:ping, caller} -> send(caller, :pong)
end
end)
send(pid, {:ping, me})
receive do
:pong -> IO.puts("round trip complete")
end
Nothing here shares memory: me was copied into the closure, the tuple was
copied into the child’s mailbox, :pong was copied back into yours.
Isolation is not a convention — it is enforced by the copy semantics of
every message.
22.2 Mailbox Mechanics and Selective Receive
A mailbox is an unbounded FIFO queue plus a scan pointer. That pointer explains both the power and the classic cost of selective receive. When no clause matches any queued message, the scan visits every message — O(n) in queue depth — and the queue stays intact:
send(self(), :stale_request)
send(self(), :stale_response)
receive do
:never_sent -> :impossible
after
0 -> :mailbox_scanned_and_untouched
end
This is the same trap you know from Erlang: never selective-receive against a busy mailbox. The standard avoidance patterns, which Elixir libraries encode for you:
- Unique reference, tightly scoped. Generate a ref, send the request,
then match the ref in the receive. The compiler recognizes this shape and
emits a receive mark, letting the search skip everything already queued
when the ref existed. The ref must be created and bound before the message
carrying it is sent — but it does not have to be the line immediately
above the
receive; the interveningsendis normal and still optimizes. This is why request/response stays cheap even with deep mailboxes:
ref = make_ref()
send(server, {:work, ref, self()})
receive do
{^ref, result} -> result # skips pre-ref messages via recv mark
after
5_000 -> exit(:timeout)
end
- One mailbox, one concern. A process mixing traffic kinds (requests + broadcasts + system messages) either prioritizes poorly or scans heavily. OTP behaviours own their mailbox discipline (Ch 23); dedicated processes per concern beat multiplexing into one busy mailbox.
From Erlang you know:
after 0turnsreceiveinto a mailbox poll — useful for draining, fatal as a wait strategy. Same semantics, same footgun.
Inspect your own mailbox any time:
send(self(), :a_note)
:erlang.process_info(self(), :message_queue_len)
#=> {:message_queue_len, 1}
flush() # iex helper — drains and prints each message
22.3 Termination and Exit Reasons
A process terminates when its initial function returns, raises, calls
exit/1, or receives a lethal exit signal. “Initial” is the operative word:
any spawned process — spawn/1 fun or spawn/3 MFA — dies when that first
entry point returns. Later returns from functions it called are ordinary
returns. The reason attached to the termination is load-bearing: it decides
how links behave (22.4) and how supervisors react (Ch 24).
| Exit reason | Meaning | Typical source |
|---|---|---|
:normal | finished cleanly | function returned |
:shutdown | planned shutdown | supervisor orders children down |
{:shutdown, term} | planned shutdown, annotated | graceful stop carrying info |
| any other term | abnormal — crash | raise, exit/1, badmatch, … |
:killed | forcibly killed | someone sent exit(pid, :kill) |
child = spawn(fn -> exit(:boom) end)
Process.sleep(50)
Process.alive?(child)
#=> false
Exceptions are convenient syntax for abnormal exit: a raise inside a
process becomes exit reason {exception_struct, stacktrace}. That is why
logs and supervisors speak of exit reasons, not exceptions — the exception
object never crosses a process boundary.
flowchart TD
S["process running"] --> R["function returns<br/>normally"]
S --> X["raise / exit/1"] --> A["abnormal reason"]
S --> K["receives exit signal<br/>with reason kill"] --> KL["killed"]
R --> D["terminated<br/>reason attached"]
A --> D
KL --> D
D -.->|"exit signal fan-out<br/>to all linked processes"| L["link propagation<br/>rules in §22.4"]
22.4 Links and Exit Signals
A link is a bidirectional propagation channel between two processes. When one endpoint terminates, every linked process receives an exit signal carrying the exit reason. The delivery rules are worth memorizing verbatim:
- Abnormal reason → each linked process dies with the same reason.
:normalreason → linked processes ignore it — unless trapping.trap_exit = true→ exit signals arrive as ordinary messages{:EXIT, pid, reason}instead of killing. Exception: reason:killcannot be trapped; it kills unconditionally.
# in iex — observe a linked peer die:
Process.flag(:trap_exit, true)
peer =
spawn_link(fn ->
receive do
:die -> exit(:crashed_on_purpose)
end
end)
send(peer, :die)
receive do
{:EXIT, ^peer, :crashed_on_purpose} -> IO.puts("exit signal arrived as a message")
end
Two subtleties:
Process.flag/2affects the calling process only. The child above did not trap exits; it genuinely died, and the trap converted what would have killed us into a message we could pattern-match.spawn_link/1is atomic on purpose. Spawning then linking as two calls leaves a window where the child exists but its death would go unnoticed. Every supervision framework on the BEAM is built on the atomic version.
flowchart TD
subgraph RULES["what happens to a linked observer"]
direction LR
AB["peer exited<br/>abnormal"] -->|"no trap"| DIE["observer dies<br/>same reason"]
AB -->|"trap_exit"| MSG["receives<br/>EXIT message"]
NM["peer exited<br/>normal"] -->|"no trap"| IGN["unaffected"]
NM -->|"trap_exit"| MSGN["receives<br/>EXIT normal"]
KL["peer was sent<br/>reason kill"] -->|"any setting"| KILL["observer dies<br/>kill is untrappable"]
end
From Erlang you know: the
error/throw/exitdistinction carries over unchanged. Elixir’stry … catch :exit, reasoncatches exactly what Erlang’scatch exit:Reasoncatches — Elixir just gives exits and throws separate keywords instead of overloaded catch tags.
Monitors — the asymmetric case
Links say “if either of us dies, the other should care.” Monitors say “tell me when that one dies” — one-directional, one-shot, and never fatal:
ref = Process.monitor(server_pid)
receive do
{:DOWN, ^ref, :process, ^server_pid, reason} -> handle_death(reason)
end
- Delivers exactly one
{:DOWN, ref, :process, pid, reason}message. - Monitoring an already-dead (or nonexistent) pid delivers
:noprocimmediately — no race window. - Multiple monitors of the same target produce independent refs; demonitor
with
Process.demonitor(ref, [:flush])to also purge a pending DOWN.
This asymmetry is why clients monitor servers (GenServer.call does exactly
this — Ch 23) while servers link to their children’s supervisor (Ch 24).
One OTP 24+ Detail: Aliases
The ref + monitor protocol above is the mental model every Erlang
developer already has, and it remains correct. Since OTP 24 the runtime adds
one more thing on top, and you should know it exists even if you never write
it by hand:
alias = :erlang.alias([:reply])
send(server, {:"$gen_call", {self(), alias}, request})
receive do
{^alias, reply} -> reply # only THIS request's reply matches
end
An alias is a reference-like token scoped to the receiver that gets
deactivated when the reply arrives. What that buys: a stale reply cannot be
confused with a fresh one, and demonitor(ref, [:flush]) is no longer
needed to clean up — the alias deactivates itself. GenServer.call/3 uses
this internally on OTP 24+, so when you read :gen_server source you will
see {self(), alias} where older tutorials showed {self(), ref}.
Nothing in this chapter depends on it. But “monitor + ref is the whole protocol” is no longer literally true, and a reader who goes to the OTP source deserves the explanation. Ch 23 §23.3 shows the caller’s side.
22.5 Naming Processes
Pids are ephemeral — restart the process and every cached pid is stale. Registration maps an atom (or tuple) to a live process:
Process.register(self(), :the_counter)
send(:the_counter, :hello) # works like any destination
Process.whereis(:the_counter) #=> pid or nil
| Scope | Mechanism | Notes |
|---|---|---|
| local node | Process.register/2 | one name = one pid, atoms only |
| cluster-wide | :global.register_name/2 | slower, consensus-based |
| many names, dynamic | Registry | Elixir’s scalable directory (Ch 10) |
GenServer.start_link(name: :the_counter) does the registration for you,
and GenServer.whereis/1 wraps the lookup — including :via tuples for
Registry-backed names.
From Erlang you know: same rules as
register/2— registration is not ownership; a name can be re-registered by whoever gets there next, which is exactly why named processes + supervision matter (Ch 24).
22.6 Schedulers, Reductions and GC — Why This All Works
You know this from Erlang; here it is once, in the vocabulary this book uses later:
- One scheduler per core runs runnable processes; each process gets a budget of reductions (roughly, function calls). Exhausting the budget or hitting certain BIFs triggers preemption at the next function boundary. A tight numeric loop cannot starve its neighbors.
- Blocking work must not run on a scheduler. Long NIFs and dirty native code go to dirty schedulers; everything else stays cooperative.
- GC is per-process. Each heap is collected independently and short-lived processes are often never collected at all — there is no stop-the-world pause to fear.
The consequence for architecture: processes are cheap enough to model concurrency units directly — one per connection, per request, per session. Elixir’s ecosystem leans on that constantly (Phoenix spawns one per connection, LiveView one per view — Ch 10).
22.7 Lab: A Hand-Rolled Stateful Server
Before GenServer formalizes this in Ch 23, write the raw loop once. This is the entire pattern — recursion carrying state inside a receive:
defmodule RawCounter do
def start_link(initial), do: spawn_link(fn -> loop(initial) end)
def bump(pid) do
send(pid, {:bump, self()})
receive do {:count, n} -> n end
end
defp loop(n) do
receive do
{:bump, from} ->
send(from, {:count, n + 1})
loop(n + 1)
end
end
end
counter = RawCounter.start_link(0)
RawCounter.bump(counter)
#=> 1
RawCounter.bump(counter)
#=> 2
Then break it on purpose and watch link propagation reach you:
counter = RawCounter.start_link(0)
Process.exit(counter, :boom) # counter died abnormally…
# …and because spawn_link linked it to this shell's evaluator, iex prints
# ** (EXIT from #PID<...>) :boom and restarts the evaluator.
# You just experienced a link doing its job.
Trap exits first and the same crash becomes data you can inspect:
Process.flag(:trap_exit, true)
counter = RawCounter.start_link(0)
Process.exit(counter, :boom)
receive do
{:EXIT, ^counter, :boom} -> IO.puts("observed the crash as a message")
end
And inspect what a live process costs:
pid = RawCounter.start_link(0)
[:message_queue_len, :heap_size, :reductions]
|> Enum.map(&Process.info(pid, &1))
#=> [message_queue_len: 0, heap_size: 233, reductions: 0]
Every awkwardness you feel in this lab — hand-rolled reply tuples, no
timeout on the receive, no handling of unexpected messages, no clean
shutdown — is precisely the list of features GenServer adds. That mapping
is Chapter 23.
Explore More
Processmodule docs — the full surface over the BIFs- :erlang module docs — links, monitors, exit signals under Process
- Efficiency Guide: Processes — mailbox and scheduling details straight from OTP
- Exercise idea: extend
RawCounterwith areset(pid)cast-style call (no reply), then send it a garbage message and observe that the loop’s catch-all absence silently leaves the message queued forever — check withProcess.info(pid, :message_queue_len) - Exercise idea: build two linked processes where one traps exits and the
other does not; kill the non-trapper with
exit(pid, :kill)and verify the trapper receives{:EXIT, pid, :killed}
Checkpoint
- What happens when you
send/2to a dead pid? How would you have known? - Why does
ref = make_ref()right before areceivechange performance characteristics? - A linked peer exits with reason
:normal. What does each of these see: a non-trapping observer? A trapping observer? - Why is
spawn_link/1’s atomicity load-bearing for supervisors? - Where does a raised exception “go” if no process catches it?
Answers
- Nothing — the message is silently dropped. You learn of death only via a
link (you die too / get
{:EXIT, ...}) or a monitor ({:DOWN, ...}). - The compiler emits a receive mark so the scan skips all messages already present when the ref was created — selective receive becomes O(new messages) instead of O(mailbox).
- Non-trapping observer: unaffected — normal exits don’t propagate fatally.
Trapping observer: receives
{:EXIT, pid, :normal}as a message. - Without atomicity there is a window where the child exists but its death would be invisible to the parent — the exact failure supervision exists to prevent.
- It terminates the process abnormally; the exception struct never crosses
the boundary — only the exit reason
{exception, stacktrace}propagates through links and appears in crash reports.
Next: Chapter 23 — GenServer Under the Microscope
Chapter 23 — GenServer Under the Microscope
GenServer is the most used behaviour in Elixir and the least understood:
most people learn its callback shapes and never see the machinery that
makes them work. You are in a position to skip that gap — you have written
the raw receive loop yourself (22.7). This chapter opens the box: what
:gen_server actually does for you, one request at a time, and where the
bodies are buried.
From Erlang you know: Elixir’s
GenServeris Erlang’sgen_server. There is no reimplementation —use GenServerwires your module to the same OTP behaviour module, and every Elixir callback has a one-to-onegen_servercounterpart (init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3). The differences are ergonomic: atoms instead of quoted messages,handle_continue, better stacktraces,child_specgeneration.
23.1 What the Behaviour Buys You
Your hand-rolled counter from §22.7 had a loop, a reply convention, and nothing else. Compare what production traffic demands:
| Concern | Hand-rolled loop | gen_server |
|---|---|---|
| request/response | hand-built {from, ref} tuples | call/2 with monitor + ref |
| caller timeout | you write the after clause | built-in, default 5 s |
| dead-server detection | link kills caller silently-wrongly | caller gets a precise exit |
| unexpected messages | silently queued forever | routed to handle_info/2 |
| clean shutdown | none | {:stop, …} + terminate/2 |
| hot-code upgrade | none | code_change/3 |
| supervision handshake | none | standard child_spec/1 |
| debug introspection | none | :sys trace/statistics |
That last row is invisible but decisive: OTP system messages (tracing,
suspend/resume for upgrades, sys.get_state) arrive as ordinary mailbox
traffic with reserved priorities. Your loop never answers them; a
gen_server does. This is why the book keeps saying never spawn a bare
loop in production — not because loops fail, but because they are blind to
the tooling.
23.2 The Two Sides of Every GenServer Module
Every module splits into a client API (functions other processes call)
and callback modules (functions gen_server invokes). Keeping them
textually separated is the single best readability habit:
defmodule Stack do
use GenServer # defines child_spec/1 + defaults
# ── client API ──────────────────────────────────────────────
def start_link(initial \\ []) do
GenServer.start_link(__MODULE__, initial, name: __MODULE__)
end
def push(item), do: GenServer.cast(__MODULE__, {:push, item})
def pop, do: GenServer.call(__MODULE__, :pop)
# ── callbacks ────────────────────────────────────────────────
@impl true
def init(initial), do: {:ok, initial}
@impl true
def handle_call(:pop, _from, [head | tail]), do: {:reply, head, tail}
def handle_call(:pop, _from, []), do: {:reply, nil, []}
@impl true
def handle_cast({:push, item}, state), do: {:noreply, [item | state]}
end
iex> Stack.start_link([:a])
iex> Stack.push(:b)
:ok
iex> Stack.pop()
:b
Note the discipline points:
use GenServergenerateschild_spec/1so the module can appear directly in a supervision tree (Ch 24). It also provides default callbacks you have not defined — which is why omittinghandle_info/2compiles yet leaks (23.4).- The API functions never touch state. They package requests. All state lives in the last argument of the callbacks and is returned, not mutated.
@impl trueon every callback — typos likehandle_calbecome compile errors instead of silent fallthroughs to defaults.
Callback return values are a small closed set. Learn them as shapes:
| Callback | Returns | Effect |
|---|---|---|
init(arg) | {:ok, state} · {:ok, state, timeout | :hibernate} · :ignore · {:stop, reason} | startup |
handle_call(req, from, state) | {:reply, reply, state} · {:noreply, state} · {:stop, reason, reply, state} · variants with trailing timeout | :hibernate | synchronous |
handle_cast(req, state) | {:noreply, state} · {:stop, reason, state} · variants | asynchronous |
handle_info(msg, state) | same shapes as handle_cast | stray/system signals |
terminate(reason, state) | any (ignored) | cleanup hook |
handle_continue/2 (available in gen_server since OTP 21) lets init and
handlers defer work to a step that runs after the mailbox is polled once
more — ideal for expensive post-start setup without delaying startup
itself, and far cleaner than sending yourself an init message by hand.
23.3 Anatomy of a call — the Real Protocol
GenServer.call/3 is not magic. It is precisely the monitor-plus-ref
pattern from §22.4, executed on the caller’s side:
# simplified but faithful — what GenServer.call/3 does:
ref = make_ref()
Process.monitor(server)
send(server, {:"$gen_call", {self(), ref}, request})
receive do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
reply
{:DOWN, ^ref, :process, _pid, reason} ->
exit(reason) # server died mid-request
after
timeout ->
Process.demonitor(ref, [:flush])
exit(:timeout)
end
This is the protocol as it was written for OTP 23 and earlier, and it is
still the clearest way to think about call/3. On OTP 24+ the real
implementation swaps ref for an alias ({self(), alias} instead of
{self(), ref}) — see §22.4’s alias note. The semantics are identical: one
token identifies one reply, one monitor detects the server’s death. Read the
ref version as the model; read the :gen_server source for the mechanism.
The server side recognizes the :"$gen_call" tag, invokes your
handle_call/3, and sends {ref, reply} back. Because the receive matches
on the unique ref (with the receive-mark optimization from §22.2), a caller
waiting on a busy server stays cheap; because it monitors, a dead server is
detected instantly instead of waiting out a 5-second timeout.
sequenceDiagram
participant C as Caller process
participant S as GenServer process
C->>S: monitor + make_ref
Note over C: ref = make_ref with receive mark
C->>S: send $gen_call with self and ref and request
S->>S: handle_call runs to completion
S-->>C: send {ref, reply}
C->>C: demonitor flush then return reply
Note over C,S: if S dies first the DOWN message<br/>replaces the reply and the caller exits<br/>with the same reason
Three exit shapes reach the caller (args is [target, request, timeout]) —
learn to read them in production:
| Situation | Caller exits with |
|---|---|
| name/pid never existed | {:noproc, {GenServer, :call, args}} |
| server died during the call | {server_reason, {GenServer, :call, args}} — the server’s crash reason wrapped with call context |
| no reply within timeout | {:timeout, {GenServer, :call, args}} |
At a system boundary — where you call into a server that may legitimately
be down — catch exits explicitly (rescue will not see them):
case GenServer.whereis(Stack) do
nil ->
{:error, :not_running}
pid ->
try do
{:ok, GenServer.call(pid, :pop)}
catch
:exit, _reason -> {:error, :down}
end
end
Inside your own supervision tree you normally let these exits propagate — the caller crashing is itself a signal something upstream must react to.
Deferred replies: {:noreply, …} + reply/2
When the answer needs work that must not block this server’s mailbox — a slow external call, a round-trip to another service — keep processing and answer later:
@impl true
def handle_call(:fetch, from, state) do
Task.start_link(fn -> # or a Task.Supervisor child
result = SlowApi.fetch()
GenServer.reply(from, result) # unblocks the original caller
end)
{:noreply, state} # mailbox keeps draining
end
from is exactly the {caller_pid, ref} pair from the protocol above.
Deferred replies are also how long-poll style APIs avoid holding the whole
server hostage.
23.4 handle_info — Where Stray Messages Go
Messages that arrive without the $gen_call/$gen_cast envelope land in
handle_info/2. Sources you will meet: Process.send_after/3 timers,
monitor DOWNs, raw sends from linked ports and tasks, exit signals when
trapping. The default implementation silently drops them all — which is why
this clause belongs in nearly every server:
@impl true
def handle_info(msg, state) do
Logger.warning("unexpected message: #{inspect(msg)}")
{:noreply, state}
end
Silent dropping is not merely impolite — it hides protocol bugs for months. A log line converts them into day-one discoveries.
23.5 Idle Timeouts and Hibernation
Two knobs control a server’s behavior between messages:
- Callback timeout —
{:noreply, state, timeout}arms a one-shot timer; if no message arrives intimeoutmilliseconds, the server sends itself:timeoutthroughhandle_info/2. Classic use: expire idle sessions.
@impl true
def handle_call(:start_session, _from, state) do
{:reply, :ok, state, 30_000} # arm the idle timer
end
@impl true
def handle_info(:timeout, state) do
{:stop, :normal, %{state | session: nil}} # idle too long — leave cleanly
end
- Hibernation —
{:noreply, state, :hibernate}(orhibernate_after: msinstart_link) garbage-collects and shrinks the heap while waiting. For thousands of mostly-idle sessions this is real memory; for a hot server it is pure overhead (waking costs a GC + heap rebuild).
From Erlang you know: same semantics as returning
{noreply, State, Timeout}fromgen_servercallbacks. Elixir adds nothing but syntax — including the{noreply, State, :hibernate}fourth-element form.
23.6 terminate/2 — the Truth Table
terminate/2 is a cleanup hook, not a destructor. Whether it runs depends
on how death arrives — the dividing line is whether termination is
observable as an internal event or arrives as an untrapped external
signal:
| How the GenServer dies | terminate/2 runs? |
|---|---|
callback returns {:stop, reason, …} | yes |
GenServer.stop/3 called | yes |
| exception raised inside a callback | yes — reason is {exception_struct, stacktrace} |
exit(reason) called inside a callback | yes |
| parent orders shutdown, trapping | yes — reason :shutdown |
| parent/external exit signal, not trapping | no — immediate death |
killed (exit(pid, :kill)) | never — untrappable |
From Erlang you know: older Erlang lore says a callback that raises skips
terminate/2. That has not been true for a long time::gen_serverinvokesterminate/2with the reason{exception_struct, stacktrace}when a callback raises, whether or not the process traps exits. The rows that still hold are the untrapped-signal ones — an externalexit(pid, reason)where the target does not trap kills it outright, because nothing can run your cleanup unless you asked for the message by trapping.The practical consequence:
terminate/2is reliable for crashes you can catch in your own code, unreliable for signals you did not anticipate. Design for that, not for the myth either way.
This is why servers holding resources (sockets, files, NIF handles) set
Process.flag(:trap_exit, true) in init/1, and why supervisors give
children a shutdown grace period (Ch 24).
And the corollary that saves production nights: do not put correctness-
critical work only in terminate/2 — a kill or untrapped crash skips it.
Persist incrementally, or make recovery cheap instead of shutdown perfect.
23.7 Debugging a Live Server
The :sys module works identically to Erlang — because it is it:
pid = Process.whereis(Stack)
:sys.get_state(pid)
#=> [:b] current state, no code changes needed
:sys.trace(pid, true) # every message in/out printed to shell
# statistics are OFF until enabled; :get then answers {:ok, :no_statistics}
:sys.statistics(pid, false) # explicitly stop collecting
:sys.statistics(pid, :get)
#=> {:ok, :no_statistics}
:sys.statistics(pid, true) # start collecting
# ... traffic ...
:sys.statistics(pid, :get)
#=> {:ok, [
# start_time: {{2026, 10, 1}, {13, 33, 19}},
# current_time: {{2026, 10, 1}, {13, 33, 19}},
# reductions: 60,
# messages_in: 1,
# messages_out: 0
# ]}
Note the shape: it is a proplist inside an :ok tuple, not a map. Match
{:ok, stats} and Keyword.get(stats, :messages_in) rather than reaching
for stats.messages_in. And the counters only move once you have called
:sys.statistics(pid, true) — before that, :get returns
{:ok, :no_statistics}.
Process.info(pid) remains the X-ray for pressure symptoms:
:message_queue_len climbing means producers outpace handlers;
:memory growing without plateau means unbounded state or binary refs;
:current_function stuck in a module you did not write means a blocking
call inside a callback.
For whole-tree views, :observer.start() (from a GUI-capable node) shows
mailbox depths, memory, and supervisor structure live — Ch 24 uses it again.
23.8 The Pitfall Catalog
Each of these is a production incident with a name:
- Synchronous self-call deadlock.
handle_call(:x, …)callingGenServer.call(__MODULE__, :y)waits for a reply the busy loop can never deliver. Same for two servers calling each other synchronously in a cycle. Fix: read the state directly (it is right there), split work acrosshandle_continue, or go async viacast/messages. - Blocking callbacks. A 200 ms HTTP call inside
handle_callfreezes every queued request behind it — and the callers’ 5 s timeouts start ticking meanwhile. Fix: defer via Task + deferred reply (23.3), or move the work to dedicated workers. - Unbounded mailbox. Casting faster than handling turns the mailbox into an invisible queue with no backpressure and no observability until the node OOMs. Fix: demand-based flow (GenStage/Broadway, Ch 13), bounded worker pools, or drop-and-count semantics.
- State bloat. Accumulating full histories “for debugging” grows heaps and GC times monotonically. Fix: cap, summarize, or externalize (ETS/ disk).
- Reads through a bottleneck. A cache GenServer answering 20 k reads/s
serializes what could be parallel. Fix: an
:etstable owned by a stable process (often a dedicated owner under the supervisor), with the GenServer handling only writes (Ch 22 §22.7, Ch 13’s Broadway/Ecto notes). - Catching everything in callbacks. Rescuing around business logic converts crashes into corrupted-state zombies — the opposite of let-it- crash. Let the supervisor restart clean (Ch 24); rescue only at boundaries.
Explore More
- GenServer docs — especially
How to supervise and the callback reference; note each callback’s doc
mirrors its
:gen_servercounterpart :gen_serverreference — the protocol-level truth, including system messages:sysmodule — tracing, statistics, suspend/resume used by debuggers and upgraders- Exercise idea: reproduce the deadlock — a server whose
handle_callcalls itself withGenServer.call(__MODULE__, :other)— watch both hang, then fix it three ways: direct state access,handle_continue, deferred reply - Exercise idea: send a raw message (
send(Stack, :garbage)) before and after adding the catch-allhandle_info; confirm the default swallows it silently
Checkpoint
- What exactly does
GenServer.call/3do before sending the request, and why? - Your
handle_callraises. What does the caller see, doesterminate/2run, and what happens to the queued messages? - Why does the default
handle_infodropping messages matter, and where do DOWN messages arrive if you monitor something inside a GenServer? - A server must call a flaky third-party API taking ~10 s. Sketch the shape that keeps its mailbox healthy.
- When is
terminate/2guaranteed to run, and why is that guarantee weaker than it looks?
Answers
- Monitors the target, generates a unique ref (with receive-mark
optimization), then sends
{:"$gen_call", {self(), ref}, request}and selective-receives either{ref, reply}or a DOWN. Monitor = instant death detection; ref = correct pairing despite interleaving. - Caller exits with
{crash_reason, {GenServer, :call, args}};terminate/2does run (moderngen_servercalls it on failures too); queued messages die with the process — restart rebuilds frominit/1. - Because silent drops hide protocol bugs; DOWNs are ordinary messages so
they arrive in
handle_info/2— another reason the catch-all clause exists. handle_callreturns{:noreply, state}capturingfrom, spawns a supervised Task for the HTTP call, which completes withGenServer.reply(from, result); the server keeps draining meanwhile.- Only when death is observable as a trapped/internal exit (
{:stop,…},GenServer.stop/3, trapped shutdown). Kills and untrapped abnormal exits skip it — so critical persistence cannot rely on it.
Next: Chapter 24 — Supervisors & Restart Trees
Chapter 24 — Supervisors Deep Dive: Restart Trees That Hold the System Up
A supervisor has exactly one job: start children, watch them, and restart them according to policy — forever, without holding state anyone needs. It is the component that turns let it crash from a slogan into an operating mode. Chapters 22–23 built the raw material; this chapter arranges it into trees that survive production.
From Erlang you know: Elixir’s
Supervisoris OTP’ssupervisorbehaviour, andDynamicSupervisoris what replacedsimple_one_for_one(which you should no longer write by hand). Child specs are the same maps/tuples you configured in Erlang — Elixir just gives them first-class syntax and generates them fromuse GenServer.
24.1 A Supervisor Is Just a Process With One Loop
Strip away the DSL and a supervisor is: a process with trap_exit = true,
holding a list of child specs, running a receive loop over {:EXIT, pid, reason} messages. When a linked child dies:
- look up which spec owned that pid;
- decide from the exit reason and the spec’s restart policy whether this death warrants a restart;
- if yes, run the child’s
{m, f, args}again — there is no magic state transfer, the new process starts from scratch; - check the restart budget (24.4) — if the policy is being violated too fast, give up and terminate yourself, escalating upward.
That last step is what makes trees honest: a supervisor that cannot keep a child alive does not hide the fact; it dies loudly and lets its supervisor try a larger-scale fix. Restarts propagate as a last resort, not a first.
flowchart TD
C["child dies<br/>exit reason attached"] --> P{"restart policy<br/>says restart?"}
P -->|"no"| DONE["leave it dead"]
P -->|"yes"| B{"within budget?<br/>max_restarts per max_seconds"}
B -->|"yes"| R["start child again<br/>fresh init, fresh state"] --> W["keep watching"]
B -->|"no"| UP["supervisor terminates<br/>reason escalates to its parent"]
24.2 The Child Spec, Dissected
Every supervised process is described by one map:
| Key | Meaning | Default |
|---|---|---|
:id | unique identity within this supervisor | required |
:start | {module, function, args} to spawn it | required |
:restart | when to restart — :permanent, :transient, :temporary | :permanent |
:shutdown | grace period on tree shutdown — :brutal_kill, ms, :infinity | 5_000 |
:type | :worker or :supervisor | :worker |
:significant | participates in auto-shutdown (OTP 24+) | false |
:modules | for hot-code upgrade analysis | [module] |
You rarely write maps by hand. use GenServer defines Stack.child_spec/1,
and Elixir offers shorthand forms in the children list:
children = [
Stack, # {Stack, []} — default argument []
{Stack, [:a]}, # Stack.start_link([:a]) — ONE arg, a list
{Stack, [:b], restart: :temporary} # 3-tuples are NOT specs — this raises
]
{Stack, []} passes the empty list as a single argument (start_link([]));
it is not splatted. And a 3-tuple {Module, Args, Opts} raises
ArgumentError at supervisor start: the accepted forms are a module, a
{module, arg} tuple, a map, or the 6-element Erlang tuple — a 3-tuple is
none of them. For overrides, use Supervisor.child_spec/2:
children = [
Stack,
{Stack, [:a]},
Supervisor.child_spec({Stack, []}, id: :stack_a, restart: :transient)
]
From Erlang you know: these fields map one-to-one onto the tuple
{ChildId, MFA, RestartType, Shutdown, ChildType, Modules}you passed tosupervisor:start_child/2. Same semantics; the map keys are just kinder.
24.3 Strategies — Deciding Who Else Restarts
The strategy answers one question: when this child restarts, who else does?
| Strategy | On a child restart | Use when |
|---|---|---|
:one_for_one | only the dead child | children are independent |
:one_for_all | every other child too (dead ones restarted, live ones stopped then restarted) | children share coupled state |
:rest_for_one | the dead child and everything started after it | ordered dependencies |
DynamicSupervisor | n/a — children started at runtime | fleets, sessions, tasks |
flowchart TD
subgraph OFO["strategy: one_for_one"]
direction LR
A1[cache] ~~~ B1[pool] ~~~ C1[metrics]
KILL1X["pool crashes"] -.->|"only pool restarts"| B1R["pool v2"]
end
subgraph RF1["strategy: rest_for_one"]
direction LR
A2["registry"] --> B2["dynamic sup"] --> C2["workers"]
KILL2X["registry crashes"] -.->|"registry AND dynamic sup<br/>AND workers all restart"| RF1R["whole tail rebuilt"]
end
Choosing wrongly shows up later, not immediately: :one_for_one over
processes that actually depend on each other produces zombie pairs (a fresh
worker talking to a stale cache). The dependency rule from the architecture
chapters applies inside the tree: if B’s correctness depends on A’s
liveness, order them A→B and let the strategy say so.
24.4 Restart Intensity — the Budget That Prevents Storms
Restarting forever is not resilience; a child that dies instantly after
every start would burn a core spinning. The supervisor therefore budgets
restarts: by default 3 restarts per 5 seconds (max_restarts,
max_seconds). Exceeding the budget — a crash loop — makes the
supervisor terminate itself with reason :shutdown, escalating to its own
parent (24.1).
Supervisor.start_link(children,
strategy: :one_for_one,
max_restarts: 3,
max_seconds: 5,
name: MyApp.Supervisor
)
Tune the numbers after you know your restart latency, never before. A child legitimately taking 10 retries in its first seconds wants a bigger budget; a subsystem crash-looping every minute wants an alarm, and the escalation gives you exactly one.
From Erlang you know: same
intensity/periodpair under other names, same semantics — the budget counts restarts, and only deaths that trigger restarts count toward it.
24.5 Restart Policies — Deciding Whether This Death Matters
The per-child :restart value classifies exits:
| Policy | Restarted on | Typical for |
|---|---|---|
:permanent | any exit | servers holding critical state |
:transient | abnormal exits only — anything except :normal, :shutdown, {:shutdown, _} | workers whose clean finish means done |
:temporary | never | one-shot jobs; things that re-register themselves |
Task children are :temporary by default — a finished task must not be
resurrected. Note how this composes with exit reasons from Ch 22: a worker
that finishes cleanly returns → :normal; a worker killed mid-flight dies
abnormally → restarted under :transient.
24.6 Shutdown — Orderly Retreat
When the tree stops (deploy, System.stop/0, supervisor giving up), the
supervisor walks its children in reverse start order and terminates each
according to the child’s :shutdown value:
:brutal_kill—exit(pid, :kill), no ceremony;- integer ms — send exit signal
:shutdown, wait that long, then kill; :infinity— wait forever (correct for supervisors-as-children; abuse elsewhere hangs deploys).
Two facts connect directly to Chapter 23’s truth table:
- The supervisor itself traps exits — that is literally how it receives child deaths as messages.
- A worker only gets its graceful
terminate/2during shutdown if the worker traps exits; otherwise the:shutdownsignal kills it where it stands. Resources needing cleanup set the flag themselves (23.6).
24.7 Wiring Real Trees
The application callback is just the root of the tree:
defmodule MyApp.Application do
use Application
@impl true
def start(_type, _args) do
children = [
MyApp.Repo,
{Phoenix.PubSub, name: MyApp.PubSub},
MyAppWeb.Endpoint
]
Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)
end
end
Flat :one_for_one at the top is fine — genuinely independent subtrees.
Structure appears when children depend on each other: group them under a
sub-supervisor whose strategy encodes the dependency.
defmodule MyApp.WorkerPool do
use Supervisor # a module-based sub-supervisor
def start_link(arg), do: Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
@impl true
def init(_arg) do
children = [
{Registry, keys: :unique, name: MyApp.WorkerRegistry},
{DynamicSupervisor, name: MyApp.WorkerSupervisor}
]
Supervisor.init(children, strategy: :one_for_all)
end
end
If the Registry died alone, every worker’s registered name would dangle —
so :one_for_all rebuilds the pair together (this is the shape Postgrex and
Phoenix.PubSub ship internally). Use :rest_for_one instead when the
dependency is ordered but partial: everything downstream of the failure
rebuilt, upstream preserved.
OTP 24+ adds one more tool for trees with “optional” parts: mark children
:significant and set the parent’s auto_shutdown so the tree stops
cleanly when all significant children end — designed for session-style
trees that have a natural lifetime.
24.8 DynamicSupervisor — Children Born at Runtime
Static specs describe what exists at boot. Fleets — one process per session, per upload, per connection — need children started (and replaced) later:
defmodule MyApp.SessionSup do
use DynamicSupervisor
def start_link(init_arg), do: DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
def start_session(id) do
spec = Supervisor.child_spec({MyApp.Session, id}, restart: :transient)
DynamicSupervisor.start_child(__MODULE__, spec)
end
@impl true
def init(_init_arg), do: DynamicSupervisor.init(strategy: :one_for_one)
end
iex> MyApp.SessionSup.start_session("user-42")
#=> {:ok, #PID<0.180.0>}
iex> DynamicSupervisor.which_children(MyApp.SessionSup)
#=> [{:undefined, #PID<0.180.0>, :worker, [MyApp.Session]}]
iex> DynamicSupervisor.count_children(MyApp.SessionSup)
#=> %{active: 1, specs: 1, supervisors: 0, workers: 1}
Use the DynamicSupervisor functions, not Supervisor.which_children/1 —
the latter happens to work because DynamicSupervisor implements the same
:supervisor calls, but it teaches the wrong module and any child-spec-only
helper you reach for next will not exist.
Notes that matter:
-
The dynamic supervisor itself is a static child of something above it; only its children are dynamic.
-
start_child/2returns{:ok, pid}or{:error, {:already_started, pid}}— but thealready_startedcomes from the child’s ownstart_link/1, not from the spec. If your child registers via{:via, Registry, ...}and that key is taken, you get{:error, {:already_started, pid}}. A:idin the spec does not deduplicate:DynamicSupervisorpermits duplicate ids, so “one process per session” is enforced by theRegistry, not the supervisor.case DynamicSupervisor.start_child( MyApp.SessionSup, Supervisor.child_spec({MyApp.Session, session_id}, id: session_id) ) do {:ok, pid} -> {:ok, pid} {:error, {:already_started, pid}} -> {:ok, pid} # idempotent other -> other end -
Task.Supervisoris this exact pattern prepackaged for tasks.
From Erlang you know: this is
simple_one_for_onewith the rough edges sanded off — per-child specs instead of one frozen MFA, and no more positionalstart_childargument lists.
24.9 Watching Trees Fail — On Purpose
Production debugging starts with reading crash reports; they are already structured:
[error] GenServer MyApp.Session terminating
** (KeyError) key :token not found in: %{user_id: 42}
my_app/session.ex:23: MyApp.Session.handle_info/2
Last message: {:DOWN, ...}
State: %{user_id: 42}
Four lines tell you: which process, why, on what message, holding what state. For live views:
Supervisor.which_children(MyApp.Supervisor)
Supervisor.count_children(MyApp.WorkerPool)
#=> %{active: 12, specs: 12, supervisors: 1, workers: 11}
:observer.start() # GUI: trees, mailboxes, memory, scheduler usage
And the highest-value exercise in this chapter: kill things deliberately
in dev. Process.exit(pid, :kill) your cache under load, watch the tree
rebuild, and check what clients experienced. A supervision tree you have
never killed is an untested component wearing a production name.
Explore More
- Supervisor docs — child spec reference and strategy semantics
- DynamicSupervisor docs
Task.Supervisor— supervised ad-hoc processes without writing any supervisor yourself- OTP Design Principles: Supervision Behaviour
— the Erlang-side truth, including
supervisor_bridge - Exercise idea: build a three-child tree (
registry → pool → worker) with:rest_for_one; kill each child in turn and log exactly who restarted - Exercise idea: set
max_restarts: 2, max_seconds: 5over a child that crashes ininit/1, catch the supervisor’s own exit, and confirm reason is:shutdown
Checkpoint
- What does a supervisor actually do when it “restarts” a child?
- Your registry crashed while workers were running. Which strategy would you pick to avoid stale registrations, and why not the others?
- A
:transientchild exits with{:shutdown, :done}. Restarted? - Why does exceeding the restart budget terminate the supervisor rather than just logging?
- During shutdown, when does a worker’s
terminate/2run — and who decides how long it may take?
Answers
- Re-runs the child’s
{module, function, args}from scratch — fresh process, fresh state viainit. Nothing is transferred; recoverability comes from rebuilding, not snapshotting. :rest_for_onewith the registry first in start order. Workers registered under names die with the registry, so they must be rebuilt after it; plain:one_for_oneleaves them pointing at nothing. The §24.7 example uses:one_for_all, which also works but needlessly restarts anything started before the registry too — prefer:rest_for_oneand put the dependency first.- No —
{:shutdown, term}counts as clean, like:shutdownand:normal;:transientrestarts abnormal deaths only. - Because a crash loop means the local fix has failed; escalating gives a larger context (the parent restarts the whole subtree) a chance, and surfaces the failure upward until something can actually address it. Silently spinning would hide the outage.
- Only if the worker traps exits (then it receives the
:shutdownsignal as a message); the child’s own:shutdownspec value — integer ms,:infinity, or:brutal_kill— sets the grace period before the supervisor kills it. Order is reverse start.
Next: Chapter 25 — Pattern Matching Deep Dive — the last mechanics chapter. Ch 14 (High-Level Process Frameworks) packages these primitives into libraries if you want that detour.
Chapter 25 — Pattern Matching Deep Dive: How = Really Works
Pattern matching is the reflex you will use more than any other feature in
Elixir — this chapter expands my
dev.to article on the topic
into the full mechanics: what = actually does, how a match executes step
by step, everywhere patterns can appear, what the compiler builds from them,
and the rules for maps and binaries that most tutorials skip.
From Erlang you know: the matching semantics are identical — structural unification over terms, selective
receive, function-clause dispatch, the same binary-segment syntax. One difference changes how you read every line of Elixir code: variables are rebindable, so a bound variable in an Erlang pattern compares, while in Elixir it would rebind — hence the pin operator^. Everything else transfers intact.
The three verbs from the article still organize everything:
- Check — assert a value’s shape or exact content (
{:ok, "hello"} = {:ok, "hello"}). - Extract — pull parts out of a complex term (
{:ok, value} = tuple). - Dispatch — choose behavior by shape (function clauses,
case,receive).
And its summary of the operator holds verbatim: = always evaluates the
right-hand side, tries to make it fit the pattern on the left, returns the
right-hand term so expressions compose, and raises MatchError when no
fit exists:
result = {:ok, {total, items} = payload} = {:ok, {1, ["hi"]}}
#=> {:ok, {1, ["hi"]}}
payload
#=> {:ok, {1, ["hi"]}} captured mid-chain too
total
#=> 1
One expression, three bindings: result, payload, then total/items
— because matching nests like the terms do.
25.1 = Is Unification With Rebinding
In Erlang, = performs single-assignment unification: once X is bound,
X = 5 compares. In Elixir, = matches the pattern against the term;
a bare variable in the pattern binds or rebinds:
expected = 2
{^expected, tag} = {2, :b} # ^compares: only matches if expected == 2
{expected, tag} = {99, :c} # no pin: REBINDS expected to 99
The pin is compile-time sugar for “compare against this variable’s current binding,” and it composes anywhere a variable can appear:
%{id: ^user_id} = record
[<<^header, _::binary>>] = frames
Two relatives complete the family:
| Pattern piece | Behavior |
|---|---|
value | binds or rebinds |
^value | compares against existing binding |
_ | consumes anything, binds nothing, reusable freely |
_reason | does bind — naming for readability, warnings suppressed |
That last row trips people: _reason is a real variable. Only bare _
refuses to bind, which is why _ = 1 followed by _ = :anything is fine.
Chained matches flow the term right-to-left through every pattern; all must accept it, and each gets to extract:
list = {:ok, {:waiting, [1, 2, 3]}, {:running, [4, 5, 6]}}
{:ok, _, _} = {_, {:waiting, list1}, _} = {_, _, {:running, list2}} = list
list1
#=> [1, 2, 3]
list2
#=> [4, 5, 6]
25.2 How a Match Executes
Conceptually the runtime walks the pattern and the term together, top-down:
flowchart TD
START["pattern = term<br/>right side evaluated first"] --> KIND{"what is this<br/>pattern part?"}
KIND -->|"bare variable"| BIND["bind the value"]
KIND -->|"underscore"| SKIP["consume, bind nothing"]
KIND -->|"pin caret name"| CMPV["compare against<br/>current binding"]
KIND -->|"literal"| CMPL["structural equality check"]
KIND -->|"tuple · list · map · struct"| DESCEND["descend into the shape"]
CMPV --> PART
CMPL --> PART
BIND --> PART["part matched"]
SKIP --> PART
DESCEND --> KIND
PART --> MORE{"parts remaining?"}
MORE -->|"yes"| KIND
MORE -->|"no"| DONE["success: expression returns<br/>the term - else MatchError"]
Rules worth internalizing because they explain otherwise-surprising errors:
-
Shape must agree exactly. Tuples encode arity:
{_, _, _}matches only 3-tuples. Lists decompose head/tail, with the tail holding the remainder:[a | b] = [1, 2] #=> a = 1, b = [2] [a | b] = [1] #=> a = 1, b = [] match?([_ | _], <<1>>) #=> false — a binary is not a list -
Repeated variables must agree within one pattern.
%{a: v, b: v}matches%{a: 10, b: 10}and raisesMatchErroron%{a: 10, b: 11}— repetition is an implicit equality constraint, because the secondvis a match against the first’s binding.Note the consequence: you cannot write the pinned form in the same pattern, because
^vis only legal oncevis already bound —v = 10 %{a: ^v, b: x} = %{a: 10, b: 11} # legal: ^v compares against v # %{a: v2, b: ^v2} = ... # CompileError: undefined variable ^v2Inside one pattern, repetition is the comparison. Across patterns, you pin. That is the whole pin story (Ch 02 §2.7.5).
-
Map patterns are subset matches (next section), tuples are exact-shape matches. Choosing between them is a design decision about strictness.
-
Failure raises immediately —
MatchErrorfor=,CaseClauseErrorfor an exhaustedcase,FunctionClauseErrorfor function dispatch. This is the article’s fail-fast point wired directly into let-it-crash: a bad shape kills the process early with full context instead of poisoning downstream state (Ch 22–24 own the recovery).
25.3 Where Patterns Live
Every construct below accepts full patterns — literals, pins, guards, nesting:
| Site | Notes |
|---|---|
| function heads | the default dispatch style; clauses tried top-down |
anonymous fn heads | same, inline: fn :ok -> true; _ -> false end |
case | one term, many patterns; must handle what can arrive |
receive | mailbox scan per clause (§22.2’s receive-mark pairs with this) |
with <- | non-matching value falls through as the result |
for generators | non-matching elements are silently filtered |
%Module{} in args | struct-kind check plus field extraction |
= anywhere | assertions mid-expression |
Three behaviors distinguish these sites, and mixing them up is a classic bug source:
- Failure kind. Function dispatch raises
FunctionClauseError;casewith no matching clause raisesCaseClauseError; bare=raisesMatchError. Reading production stacktraces is faster when you know which failure means which stage. - Fall-through semantics.
withreturns the first non-matching value (optionally intercepted byelse);forskips it silently:
with {:ok, n} <- {:ok, 41},
{:ok, m} <- {:error, :nope} do
:unreachable
else
{:error, reason} -> {:failed, reason}
end
#=> {:failed, :nope}
for {:ok, n} <- [{:ok, 1}, :junk, {:ok, 3}], do: n
#=> [1, 3] # :junk vanished without a trace
- Order is semantics. Among overlapping clauses the first match wins, so a catch-all placed early shadows everything after it — and the compiler tells you:
warning: this clause for f/1 cannot match because a previous clause
at line 87 always matches
The compiler reorders nothing you wrote; it only refuses to compile dead clauses and builds efficient decision trees underneath (25.6). Put specific clauses first, guards to narrow them, and the catch-all last.
Defaults + multiple clauses = explicit header
A function with both \\ defaults and pattern-matched clauses needs a
bare header declaring the default once:
defmodule Greet do
def hello(name, greeting \\ "Hello")
def hello(nil, _greeting), do: "who?"
def hello(name, greeting), do: "#{greeting}, #{name}!"
end
Guards extend patterns where patterns run out
Patterns check structure; guards check properties:
def classify(n) when is_integer(n) and n > 0, do: :positive
def classify(n) when is_integer(n), do: :non_positive
def classify(_other), do: :other
And match?/2 answers yes/no without binding — the captured variable stays
local to the pattern:
match?({:ok, val}, {:ok, 1})
#=> true # but `val` does not exist out here - use case/= to extract
25.4 Maps and Structs — Subset vs Kind Matching
Two asymmetries matter constantly:
Map patterns ignore extra keys. %{a: 1} matches any map that has
:a => 1, regardless of what else it holds. Missing keys fail; extra keys
pass through untouched:
%{a: 1} = %{a: 1, b: 2}
#=> matches
%{missing: _} = %{a: 1}
#=> MatchError
Consequently %{} matches every map — including structs, since structs
are maps with a __struct__ key. That makes bare %{} nearly useless as
an assertion and occasionally dangerous as a catch-all clause. When you mean
“a value of this record type,” name the struct — the kind check comes free
alongside field extraction:
%Date{day: day, year: year} = deadline # checks Date, extracts fields
%Time{} = t # rejects a Date outright
Cost note for hot paths: each key in a map pattern is one lookup, so a pattern naming five keys costs five lookups against maps stored as sorted flat arrays (≤32 keys) or hash-tries (larger). Fine almost everywhere; relevant inside per-message loops.
25.5 Binaries and Bitstrings — the Article’s Core, Extended
The article’s progression is exactly right, and every example below is verified. Bytes first:
bin = <<1, 2, 3, 4, 5>>
<<first, rest::binary>> = bin
#=> first = 1, rest = <<2, 3, 4, 5>>
<<1, second, rest::binary>> = bin # literal + variable segments mix
#=> second = 2
<<head::binary-size(2), tail::binary>> = bin
#=> head = <<1, 2>>
Bit-level access needs only size specifiers — the same syntax constructs and matches:
bit = <<3::4, 1::4, 3::4, 0::4>> # 16 bits total
<<first_8::bitstring-size(8), rest::bitstring>> = bit
#=> first_8 = <<3::4, 1::4>>, rest = <<3::4, 0::4>>
<<3::4, next_4::bitstring-size(4), _>> = bit
#=> matches literal 3, extracts the following nibble, drops the last byte
Three extensions turn this from syntax into a working protocol tool.
Sizes can read earlier segments — the pattern is processed left to right, so a length prefix drives the extraction (this single feature replaces most hand-written parsers):
packet = <<11, "hello world">>
<<len, body::binary-size(len)>> = packet
#=> len = 11, body = "hello world"
Sizes must be pinned in patterns. This is the Elixir 1.20 rule that catches everyone writing a parser, and it applies whenever the size comes from a variable bound outside the pattern:
bin = <<1, 2, 3, 4, 5>>
n = 3
<<a::size(n), _::binary>> = bin
# ~~~~ warning: "the variable n is accessed inside size(...) but it was
# defined outside of the match. You must precede it with
# the pin operator"
# then MatchError — the compiler treated `n` as a fresh pattern variable
<<a::size(^n), _::binary>> = bin # correct
In construction the bare variable is fine — <<9::size(n), 0::3>> builds
correctly, because there is nothing to compare against. The asymmetry is
patterns-compare, construction-compute.
Combined with the tail rules below, <<a::size(^n), rest::binary>> only
matches when bit_size(bin) - n is a multiple of 8. Verified:
n = 8 matches; n = 3 does not. If the length prefix is in bits, either
divide it by 8 yourself or use rest::bits. This is the exact hazard that
used to show up as a mysterious MatchError in hand-rolled parsers.
UTF segments decode during matching:
<<"h", é::utf8, rest::binary>> = "héllo"
#=> é = 233, rest = "llo" - one codepoint, not one byte
Tail types have strict rules, verified against the runtime:
| Final segment | Matches remainder of |
|---|---|
rest::binary | whole bytes only — fails on non-byte-aligned leftovers |
rest::bits / ::bitstring | any remainder, down to single bits |
match?(<<_::1, t::binary>>, <<31::5>>) # 4 bits would remain
#=> false - ::binary refuses non-byte-aligned tails
case <<31::5>> do
<<_::1, t::bits>> -> {:got, bit_size(t)} # => {:got, 4}
end
And the quiet performance win underneath it all: extracting rest does not
copy. A sub-binary is an offset-and-length view into the original, so
slicing a gigabyte log line costs the same as slicing two bytes — with the
caveat that the view pins the whole original in memory until every view is
gone; long-lived extractions of huge binaries should be copied explicitly
(:erlang.binary_copy/2) or re-encoded.
25.6 Under the BEAM Hood
What the compiler actually builds from your patterns:
- Function clauses become decision trees. Clauses sharing structure are
grouped and tested by tag/type once, then branched — ten clauses matching
on
%{kind: ...}cost roughly one map-type test plus per-clause key probes, not ten full rescans. Your clause order remains the semantic contract; the trees preserve it while skipping tests that cannot matter. - Binary patterns compile to dedicated bit-matching instructions
(
bs_matchfamily) walking segment by segment; constant prefixes become fast comparisons, dynamic sizes consume earlier bindings. - Sub-binaries are views, as above — allocation-free extraction is why protocol parsers written as pattern matches routinely beat hand-rolled index arithmetic.
- Map patterns lower to keyed lookups, not iteration: no scanning of entries you did not name.
receivepairs selective scan with unique refs (22.2): the compiler’s receive-mark optimization exists precisely because function/case-style pattern matching runs over the mailbox too.
From Erlang you know: all of the above machinery is shared — your
erlintuition about clause grouping, binary instructions, and sub-binary economics applies unchanged. Only the surface syntax differs, plus the pin operator from Ch 02.
25.7 A Workflow, Not Just Syntax
The article’s closing thought deserves the last word before practice: pattern matching is friendly to your brain because it is declarative — you describe the shape of acceptable data and name its parts, instead of writing the navigation code to reach inside. The habit that compounds:
- Assert at boundaries —
{:ok, term} = external_resultwhere a wrong shape is a bug you want loud. - Extract with named parts — patterns document structure better than
accessors (
%{headers: %{"content-type" => ct}} = resp). - Dispatch on shape — function heads over
if/is_map_key?chains; each clause is a documented case. - Fail fast and let the tree fix it — every chapter in this part is downstream of this one idea.
Explore More
- Pattern matching guide — official reference for the operator and pin
- Binaries, strings and charlists
— segment types,
utf8/utf16/utf32, endianness - Erlang Efficiency Guide: functions and pattern matching — clause compilation details straight from OTP
- The original article: Elixir pattern matching — Explain & Use cases
- Exercise idea: parse an IPv4 header with one binary pattern — version,
IHL, TOS, length, then rest; verify sizes against
byte_size - Exercise idea: write
def f(x)clauses where the second is unreachable, read the compiler warning, then reorder and watch it disappear
Checkpoint
- What does
=evaluate first, what does it return, and what does it raise on failure? - Without running it: does
{expected, tag} = {2, :b}changeexpected, and how would you prevent that? %{}matches%Date.new!(2026, 8, 26)— why, and what do you write when you want kind safety?<<len, body::binary-size(len)>>works — why can’tbody::binary-size(n)use a variablenbound later in the same pattern?- You need the remainder of a bitstring that may not be byte-aligned. Which
tail type, and why does
::binaryrefuse? - In production logs you see
FunctionClauseError. Which constructs were involved, and how is it different fromMatchError?
Answers
- Right side first; the expression returns the right-hand term; failure
raises
MatchError. - It rebinds
expectedto 2 (here harmlessly) — pin it:{^expected, tag} = {2, :b}compares instead of rebinding. - Structs are maps (with a hidden
__struct__key), and map patterns are subset matches. Write the struct pattern%Date{...}to check kind while extracting. - Binary segments are matched left to right, so earlier bindings are available as sizes; a size from a later binding would require solving the layout backwards, which the matcher does not do.
rest::bits(bitstring).::binaryrequires a whole number of bytes — e.g., 4 leftover bits fail it but match::bits.- Function-head dispatch found no accepting clause (function call site);
MatchErrorcomes from a bare=/struct-match failing. Same family of shape failures, different stage — which tells you where to look.
Next: Chapter 26 — OTP Wisdom — the last Part V chapter: the judgement the mechanics imply.
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.
Chapter 27 — Debugging & Tracing Techniques
Everything in this chapter exists in your Erlang world — dbg, tracing,
Observer — but Elixir layers ergonomic front ends over them and adds a few
tools of its own. The chapter is ordered by escalation: spy on values →
stop execution → watch processes → trace the machine → profile it.
From Erlang you know:
IO.inspect/1isio:format("~p~n", _)that returns its argument, so it never disturbs the pipeline it sits in.dbgis the:dbgmodule you know, reachable without leaving Elixir. Observer is Observer.
27.1 Spying on Values: IO.inspect/2 and dbg/2
IO.inspect/2 returns its argument unchanged, which makes it a safe
probe anywhere — including mid-pipeline:
[1, 2, 3]
|> IO.inspect(label: "before")
|> Enum.map(&(&1 * 2))
|> IO.inspect(label: "after")
|> Enum.sum()
before: [1, 2, 3]
after: [2, 4, 6]
binding() complements it inside functions — dump every variable at once:
def some_function(a, b, c) do
IO.inspect(binding()) #=> [a: :foo, b: "bar", c: :baz]
end
dbg/1 (Elixir 1.14+) goes further: it prints the source expression,
the file:line, and the value — and it understands pipelines, showing
every step’s result:
__ENV__.file
|> String.split("/", trim: true)
|> List.last()
|> dbg()
[my_file.exs:5: (file)]
__ENV__.file #=> "/home/myuser/my_file.exs"
|> String.split("/", trim: true) #=> ["home", "myuser", "my_file.exs"]
|> List.last() #=> "my_file.exs"
Rule of thumb: IO.inspect for quick labels, dbg when you want the
code next to the value. Neither requires a shell attached — both work
in tests and logs.
27.2 Stop the World: Pry and Breakpoints
Pry — step in where dbg sits
Run your session with pry enabled:
iex --dbg pry # plain iex
iex --dbg pry -S mix # inside a project
Every dbg call now asks whether to stop execution. Accept, and you
drop into IEx in the context of that code — all variables, imports, and
aliases are reachable. Execution resumes with continue (c) or steps
with next (n). The VM process handling your shell blocks while you
pry; other processes keep running — isolation you already trust.
Breakpoints — no source edits
IEx.break!/2 sets a breakpoint on any compiled module, no code change:
IEx.break!(&MyApp.Accounts.find_user/1) # stop once, on first call
IEx.break!(&MyApp.Accounts.find_user/1, 3) # stops: fire 3 times, not a line
IEx.break!(MyApp.Accounts, :find_user, 1) # module · function · arity
IEx.break!(MyApp.Accounts, :find_user, 1, 3) # …with 3 stops
In the capture form the second argument is the number of stops — how
many times the breakpoint fires, starting with the first call — not a line
number. In the module form the third argument is the function’s arity
and the fourth is the stop count, so {MyApp.Accounts, :find_user, 3}
targets find_user/3, not “the third call”. Passing 3 hoping for line 3
is a genuinely confusing way to lose an afternoon. For a line, use
IEx.break() inside the function body.
Once hit, you land in an IEx session with the arguments bound and can step line by line. Breakpoints have one limitation versus pry: no access to aliases/imports from the module’s source context.
Mix integrates breakpoints with tests directly:
# Debug all failed tests — breakpoint at each failing test's start
iex -S mix test --breakpoints --failed
# Debug the test at a specific file:line
iex -S mix test -b path/to/file:line
27.3 The IEx Session Is a Debugging Environment
An Erlang veteran keeps a ~/.erlang file; Elixir’s equivalent is
.iex.exs in the project root — auto-loaded by every
iex -S mix (or iex -S mix phx.server) start:
# .iex.exs
alias MyApp.Background.Worker, as: W
alias MyApp.Repo
import Ecto.Query
# one-off helper scripts for development — call YOUR app's real functions
defmodule FillData do
def add_sample() do
MyApp.Chat.create_room(%{name: "Hello room"})
MyApp.Chat.add_members("hello", ["user_1", "user_2", "user_3"])
end
end
# print long lists/maps without truncation
IEx.configure(inspect: [limit: :infinity])
Now in the shell: W.run(), FillData.add_sample(), Repo.all(...) —
your whole app is one alias away while debugging.
Two more session conveniences worth installing as habits:
# persistent, searchable shell history (put in .bashrc/.zshrc)
export ERL_AFLAGS="-kernel shell_history enabled"
h Enum.map/2— docs in-shell;h IEx.break!while learning this chapter.respawn/0— restart the shell inside the same node after you broke it, keeping the app and all processes alive.
27.4 Watching Processes: Observer
For system-level debugging, :observer beats every code-level tool:
iex -S mix phx.server
iex> :observer.start()
If Observer is missing in iex -S mix, ensure the application first:
Mix.ensure_application!(:observer)
:observer.start()
(Some package managers install a minimized Erlang without WX — install
erlang-wx or the non-nox package. On headless machines — containers,
K8s — connect from a graphical node and open Observer remotely against
the target, exactly as you would with an Erlang distribution.)
Observer gives you: supervision tree walk, per-process state and mailbox length, ETS tables, memory breakdown, and the “trace” button that attaches live call traces to a chosen process.
Also available without any GUI — and on a container or K8s pod, where WX usually is not installed at all, these are what you actually reach for:
:observer_cli(Hex dependency) — a full supervision-tree browser in your terminal::observer_cli.start(). The real Observer, text-mode.:etop— atop-style process list::etop.start(). Mailbox lengths and memory, sortable.runtime_info/0in IEx — mini dashboard, no dependency- Phoenix LiveDashboard — the web version, already mounted in generated Phoenix apps (Ch 10.7’s telemetry events feed it)
Prefer these over “connect from a graphical node” when the target is a container: they need no second machine and no WX.
27.5 Tracing: :sys.trace, :dbg, and recon
Trace one OTP process
Every gen_server/gen_statem process answers to sys — trace its
message and callback flow live:
pid = Process.whereis(MyApp.Cache)
:sys.trace(pid, true)
# ...interact with the system...
:sys.trace(pid, false)
Output shows each receive, callback entry/exit, and reply — the
fastest possible answer to “why is this GenServer behaving like that?”
Trace by pattern across the node — the :dbg module
The Erlang :dbg module needs no code changes and survives in any shell:
:dbg.tracer()
:dbg.tpl(MyApp.Accounts, :_, :_) # all functions of the module
:dbg.p(:all, [:c]) # trace calls from all processes
# ...reproduce the bug...
:dbg.stop_clear() # always clean up — tracing costs
Scope it down (:dbg.tp/3 on specific functions, [:c, :timestamp]
flags) before aiming it at a busy node; broad traces on hot paths will
flood the tracer process.
recon — production-safe inspection
The recon library is the community
standard for poking running nodes safely:
# add {:recon, "~> 2.5"} to deps, then in the shell:
:recon_trace.calls({MyApp.Accounts, :_, :_}, 10) # capped trace — auto-stops
:recon.proc_count(:memory, 10) # top 10 processes by memory
:recon.proc_count(:message_queue_len, 10) # the mailbox-backlog hunt
:recon.info(Process.whereis(MyApp.Cache), :messages)
Note the module prefixes: recon is an Erlang library, so in Elixir it is
:recon and :recon_trace. Bare recon.proc_count(...) raises
UndefinedFunctionError — recon ships no delegating functions. The exception
is Extrace (the Elixir wrapper, {:extrace, "~> 0.3"}), which does export
Extrace.calls/2,3 and lets you write the bare calls.
:recon_trace.calls/2,3 refuses unlimited traces by design — a guardrail
:dbg does not give you.
Telemetry and Logger (the framework layer)
Logger.debug/1withconfig :logger, level: :debugwhen you need application-level breadcrumbs (levels compared viaLogger.compare_levels/2).- Framework events ride
:telemetry— Phoenix/Ecto emit spans at every boundary (§10.7); attach handlers or point LiveDashboard/Telemetry.Metrics at them before writing your own instrumentation.
27.6 When Config Lies: Debugging Compile-Time vs Runtime Configuration
A large class of “the code is right but behaves wrong” bugs is config read at the wrong time. Elixir splits configuration in two — and the split matches the compilation model of Ch 08:
flowchart LR
CE["config.exs + dev/prod/test.exs<br/>COMPILE time — frozen into the build"] --> APP["application boots"]
RE["runtime.exs<br/>RUN time — reads System.get_env"] --> APP
APP --> RT["running node"]
Common failure modes and their probes:
| Symptom | Likely cause | Probe |
|---|---|---|
| Release ignores env vars | value baked into config.exs/prod.exs | move to runtime.exs |
| Test passes, prod crashes | test.exs overrode the value | Application.get_all_env(:my_app) in both |
Value is nil in runtime.exs | env var not exported / wrong name | System.get_env("MEDIA_PATH") in iex on the target |
| Library sees stale value | it read config at compile time | move the read to runtime.exs, then read with Application.get_env/2 in init/1 |
The read-side functions tell you what the running node actually sees:
Application.get_env(:my_app, :media) # value or nil — probe, don't fail
Application.fetch_env!(:my_app, :media) # value or raises — contract
Application.compile_env(:my_app, :media) # COMPILES the value in — do not
# use to fix a stale-value bug; it
# makes the freezing explicit, which
# is only useful when compile-time
# really is what you want
Application.get_all_env(:my_app) # everything the node believes
Application.put_env(:my_app, :media, "/tmp/x") # experiment in iex, no restart
For MIX_ENV experiments: MIX_ENV=prod mix phx.server compiles the
prod path; confirm which file a value came from by temporarily setting it
to a sentinel string and letting fetch_env! crash with it in hand.
27.7 Profiling and the Heavy Artillery
When tracing says where but not why, escalate:
| Tool | Use |
|---|---|
mix profile.tprof | start here — time+memory, low overhead (OTP 27+) |
mix profile.cprof | call counts only; legacy, superseded by tprof |
mix profile.fprof | exhaustive trace profile incl. GC; very slow |
:crashdump_viewer | GUI over erl_crash.dump files |
microstate accounting (:msacc) | where runtime threads spend their time |
| LTTng / DTrace / SystemTap | OS-level tracers, per runtime_tools docs |
| Erlang in Anger (free ebook) | the systematic playbook for sick nodes |
Explore More
- Elixir — Debugging guide — the official tour this chapter follows
- Mạnh Vũ — Elixir Tricks & Tips for debugging & developing —
the
.iex.exs, Observer-in-dev, and shell-history tips of §27.3 - Mạnh Vũ — Elixir Configuration & Environment variables — the compile-time/runtime split behind §27.6
- recon documentation — every function is documented with a “when to use on a live node” note
- Exercise idea: take a failing test and fix it three ways —
dbgin the function,IEx.break!on the module, andmix test --breakpoints— then decide which you’d want at 3 AM
Checkpoint
- Why is
IO.inspect/2safe inside a pipeline whileio:formatis not? - You need to trace all calls to
MyApp.Worker.handle_infoin production. Why:recon_trace.calls/3rather than:dbg.p(:all, [:c])? - A release ignores
MEDIA_PATH. Give the two-minute diagnosis path. - What can you reach in a pry session that breakpoints on compiled code cannot?
Answers
- It returns its argument — a probe, not a statement.
io:formatreturns:ok, so splicing it into a pipeline changes the value that flows on. :recon_trace.calls/2,3caps the number of trace messages and auto-stops — an unbounded:dbg.p/2on a hot path can flood the tracer and degrade the node.- Check where the value is read:
runtime.exs(runs at boot, sees env vars) vsprod.exs(frozen at compile). On the target node:Application.get_all_env(:my_app)— if the key is stale ornil, the value was baked at build time; move it toruntime.exsand rebuild. - Aliases and imports from the source file — pry compiles the snippet in the function’s lexical scope; breakpoints bind arguments only.
Next: Chapter 28 — LLM Integration & Agents — Part V is done; Ch 30 is the migration roadmap if you want practice first.
Chapter 28 — LLM Integration & Agents
LLM inference doesn’t mean rewriting your application outside the BEAM. The winning architecture: BEAM orchestrates; a specialized runtime computes.
28.1 The Division of Labor
flowchart TD
APP["Elixir Application"]
APP --> PHX["Phoenix<br/>sessions · streaming UI"]
APP --> OTP["OTP<br/>queues · supervision"]
APP --> AI["AI calls"]
PHX --> ADP["LLM Adapter"]
OTP --> ADP
AI --> ADP
ADP --> RT["llama.cpp / vLLM / Ollama"]
RT --> LLM["LLM"]
The BEAM handles (your existing strengths):
- User sessions & authentication
- Networking (HTTP, WebSocket, gRPC)
- Streaming responses (chunked, SSE, WebSocket)
- Rate limiting & quotas
- Request queues & backpressure (GenStage)
- Supervision & fault isolation
- Distributed orchestration
- Observability (telemetry, metrics, tracing)
The specialized runtime handles: model loading & quantization, tensor computation, token generation/sampling, KV cache management.
The BEAM doesn’t need to do every computation itself. It orchestrates specialized runtimes extremely well.
That thesis is Chapter 29’s subject, developed as the five-layer chain and the deployment consequences. This chapter is the concrete version: adapters, streaming, RAG, and an agent loop you can run today.
28.2 The Adapter Pattern
One interface, swappable transports (Port to llama.cpp binary, NIF into its library, HTTP to Ollama/vLLM/TGI, or local Nx/Bumblebee):
defmodule LLM do
@type backend :: :port | :http | :nx
def complete(prompt, opts \\ []) do
case Keyword.get(opts, :backend, :http) do
:http -> complete_http(prompt, opts)
:port -> complete_port(prompt, opts)
:nx -> complete_nx(prompt, opts)
end
end
defp complete_http(prompt, opts) do
url = Keyword.get(opts, :url, "http://localhost:11434/api/generate")
model = Keyword.get(opts, :model, "llama3")
# Pass the map directly — Req encodes JSON for you.
# (A classic bug is calling Jason.encode! here AND passing json:,
# which double-encodes into a JSON string body.)
case Req.post(url, json: %{model: model, prompt: prompt, stream: false}) do
{:ok, %{status: 200, body: %{"response" => response}}} ->
{:ok, response}
{:ok, %{status: status, body: body}} ->
{:error, {:http_error, status, body}}
{:error, reason} ->
{:error, reason}
end
end
defp complete_port(prompt, _opts) do
# Port.open({:spawn_executable, "llama-cli"}, ...) → talk stdin/stdout
{:ok, "port-based response for: #{prompt}"}
end
defp complete_nx(_prompt, _opts) do
# Bumblebee.Text.generation serving started locally (Ch 20)
{:ok, "nx-based response"}
end
end
# Runnable against a local Ollama:
# LLM.complete("Explain OTP supervision in one sentence",
# backend: :http, url: "http://localhost:11434/api/generate", model: "llama3")
This is the Erlang pattern you know — gen_server calling a Port/NIF —
applied to LLM runtimes.
From a case Clause to a Behaviour
The case works until you need a second transport, tests without a
network, or per-environment selection. The upgrade is the contract tool
you know from -callback in Erlang — a behaviour plus adapters:
defmodule LLM.Provider do
@callback complete(String.t(), keyword()) ::
{:ok, String.t()} | {:error, term()}
end
defmodule LLM.Providers.Mock do
@behaviour LLM.Provider
@impl true
def complete(prompt, _opts), do: {:ok, "echo: #{prompt}"}
end
An HTTP adapter wraps the Req code above; local inference wraps
Nx.Serving (Ch 20). Selection becomes configuration, not code:
# config/test.exs — no sockets in CI
config :my_app, :llm_provider, LLM.Providers.Mock
# config/runtime.exs — real transport
config :my_app, :llm_provider, LLM.Providers.HTTP
defmodule LLM do
def complete(prompt, opts \\ []) do
default = Application.get_env(:my_app, :llm_provider, LLM.Providers.Mock)
provider = Keyword.get(opts, :provider, default)
provider.complete(prompt, opts)
end
end
Forget a callback and the compiler warns — exactly as -behaviour does in
Erlang. Same public API, open for extension without touching dispatch.
28.3 Streaming Into LiveView
Ollama streams NDJSON. With Req, into: :self makes the response body a
lazy enumerable — a perfect fit. Two things to know about the modern Req
shape: the body becomes a %Req.Response.Async{} struct (which implements
Enumerable, so you iterate it rather than pattern-matching a “stream”), and
into: :self delivers messages to the calling process, so consume it there or
in a process that stays alive.
defmodule LLM.Stream do
@spec stream_complete(String.t(), keyword()) :: Enumerable.t()
def stream_complete(prompt, opts \\ []) do
url = Keyword.get(opts, :url, "http://localhost:11434/api/generate")
model = Keyword.get(opts, :model, "llama3")
case Req.post(url,
json: %{model: model, prompt: prompt, stream: true},
into: :self
) do
{:ok, %Req.Response{status: 200, body: body}} ->
body
|> to_chunks()
# reassemble FIRST: TCP chunks are not lines (see LLM.Lines below)
|> LLM.Lines.to_lines()
|> Stream.map(&parse_ollama_line/1)
|> Stream.reject(&(&1 == ""))
{:ok, resp} ->
[{:error, {:http_error, resp.status}}]
{:error, reason} ->
[{:error, reason}]
end
end
# with into: :self the body is %Req.Response.Async{} — enumerable, and
# each element is whatever Req hands over (bytes or already-decoded
# chunks depending on the response content-type). Handle both:
defp to_chunks(%Req.Response.Async{} = async), do: Enumerable.to_list(async)
defp to_chunks(binary) when is_binary(binary), do: [binary]
# A COMPLETE line looks like:
# {"response":"Hel","done":false}
defp parse_ollama_line(line) do
case Jason.decode(line) do
{:ok, %{"response" => text}} -> text
_ -> ""
end
end
end
Two contract details this shape gets right, both of which are easy to get wrong:
stream_complete/2returns anEnumerable.t(), not{:ok, stream}. An HTTP request either succeeds and yields a stream, or fails — there is no “stream plus an error tag” middle. Failures are elements in the stream ([{:error, reason}]), so a consumer can handle them mid-stream. Writing{:ok, stream} = LLM.Stream.stream_complete(msg)raisesMatchError.- Reassemble before parsing. Decoding a raw TCP chunk with
Jason.decode/1fails for any chunk that ends mid-JSON, which is most of them — the partial pieces get silently dropped byparse_ollama_line’s catch-all and your output arrives with holes in it.LLM.Lines.to_lines/1buffers the partial tail; only complete lines reach the parser.
Consuming it in a LiveView — note the stream is pulled, not assigned:
def handle_event("chat", %{"message" => msg}, socket) do
owner = self()
Task.start(fn ->
LLM.Stream.stream_complete(msg)
|> Enum.each(&send(owner, {:token, &1}))
end)
{:noreply, assign(socket, :response, "")}
end
def handle_info({:token, text}, socket) do
# streams are the right tool for a growing list; plain append is fine here
{:noreply, update(socket, :response, &(&1 <> text))}
end
Assigning the lazy Stream to the socket would work but never consume it —
nothing pulls, so nothing renders.
Backpressure, Made Explicit
into: :self builds exactly the Stream.resource machine you would
hand-roll around a socket: acquire the request, yield a chunk only when
the consumer pulls, and run cleanup even when the consumer halts early.
Slow rendering therefore pauses HTTP reads — demand flows upstream to the
socket, exactly like GenStage demand.
One catch the convenience hides: TCP chunks are not lines, so NDJSON
and SSE need reassembly across chunk boundaries — SSE just adds a
"data: " prefix and a data: [DONE] sentinel:
defmodule LLM.Lines do
# Raw chunks → complete lines; a partial tail stays buffered.
def to_lines(chunks) do
Stream.transform(chunks, "", fn chunk, buffer ->
parts = String.split(buffer <> chunk, "\n")
{Enum.drop(parts, -1), List.last(parts)}
end)
end
end
28.4 Production Patterns
| Pattern | Use Case |
|---|---|
| Oban workers | Background jobs (summarization, embedding backfills) |
| GenStage | Batch requests → one LLM call → fan out |
NimblePool | Bounded pool of Port/NIF connections to llama.cpp |
Finch | HTTP connection pools + adaptive limits — the current answer for HTTP, not poolboy |
| Phoenix Channels | Real-time streaming to browsers |
| Nx.Serving | Batched local inference for embeddings/classification |
On poolboy: it filled a real gap and is now unmaintained. For Erlang
migrators it is still the reflex, and for a pool of Port connections it works
— but new code should use NimblePool,
which is a small supervisor-friendly pool with built-in checkout timeouts.
For HTTP specifically, do not hand-roll a pool at all:
Finch owns the connections and already
handles keepalive and per-host limits:
# in your supervision tree
{Finch, name: MyApp.Finch}
# in the adapter — no Req pool options to configure
Req.new(url: url, finch: [name: MyApp.Finch], json: payload)
Wrong vs Right: Fan-Out Shape
Batch-embedding 500 documents? The naive version opens 500 simultaneous requests — the BEAM shrugs; the provider answers with 429s:
# WRONG — unbounded: every task launches at once.
tasks = Enum.map(prompts, &Task.async(LLM, :complete, [&1]))
results = Enum.map(tasks, &Task.await(&1, 30_000))
# RIGHT — bounded window, per-task timeout, timeouts become values.
results =
Task.async_stream(prompts, &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 + timeout: GenStage’s demand-based flow control in
one option. (The underlying Task.async_stream failure semantics —
laziness over tasks, the {:ok, _}/{:exit, _} contract — are Ch 05 §5.5.2;
note max_concurrency bounds parallelism, not provider rate — a 429
still needs the retry policy below.)
Retry Policy: Idempotent, Transient, Deadline-Budgeted
| Response | Action |
|---|---|
| 429 | Retry — honour Retry-After |
| 500/502/503/504 | Retry — two or three attempts |
| 400/401/403/404 | Never — fix the request |
Req ships this: retry: :transient retries 5xx/429/timeouts with
exponential backoff and jitter by default. Budget the total deadline,
not just per attempt. Four guardrails worth bolting on early:
- Don’t park a GenServer: route LLM calls through delayed replies
(
Task.start+GenServer.reply/2) — never blockhandle_call. - Rate limits: treat 429 +
Retry-Afteras admission control; an ETS token bucket per user rejects before spend happens. - Costs: token spend is prompt-dominated — hoist static prefixes; ~4 characters/token is close enough for quota accounting.
- Breaker + evaluation: fuse-style counting (N failures ⇒ fail fast for a cooldown, then probe); replay a golden set via Oban to gate every prompt change.
Zero-Shot Intent Routing: Classify Before You Generate
The cheapest request is the one that never needs generation. A zero-shot classifier routes utterances to handlers using labels that are data — no training run, no redeploy when the taxonomy changes:
{:ok, model_info} = Bumblebee.load_model({:hf, "facebook/bart-large-mnli"})
{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "facebook/bart-large-mnli"})
labels = ["New booking", "Update booking", "Cancel booking", "Refund", "Complaint"]
serving = Bumblebee.Text.zero_shot_classification(model_info, tokenizer, labels)
Nx.Serving.run(serving, "I need a room with two beds for tomorrow")
#=> %{predictions: [%{label: "New booking", score: 0.92}, ...]}
Mechanically this is natural-language inference: the input becomes the premise, each label becomes a “This text is about {label}” hypothesis, and entailment scores are normalized across labels — one forward pass per label, ~400M params, no fine-tuning ever. Three integration rules:
- Gate on confidence — route argmax only above a calibrated threshold; below it, fall through to the LLM or a human queue.
- Labels are config — add
"Flight status"by appending one string; version the label list like any interface contract. - Compose with the agent loop (§28.7) — classification is the decider’s first stage: known intents dispatch straight to tools; open-ended text escalates to full generation.
Pair with Ch 20 §20.7’s MiniLM embeddings when routing needs semantic similarity rather than fixed labels — same serving pattern, vector outputs, brute-force ranking until pgvector earns its keep.
28.5 A Complete RAG Pipeline
Every step runs on the boundary discipline from Ch 18:
defmodule RAGPipeline do
@doc """
1. Embed query (Nx + EXLA/EMLX — Ch 20 text_embedding)
2. Vector search (Postgres + pgvector / Redis)
3. Retrieve docs (Ecto — Ch 11)
4. Generate answer (LLM via Port/HTTP — this chapter)
5. Stream to user (Phoenix LiveView — Ch 10)
"""
def query(question) do
embedding = Embeddings.embed(question)
chunks = VectorSearch.top_k(embedding, k: 5)
context = Enum.map_join(chunks, "\n---\n", & &1.content)
prompt = build_prompt(question, context)
stream = LLM.Stream.stream_complete(prompt)
stream
end
end
Chunking Decides Retrieval Quality
Vectors cannot fix bad segmentation — chunk thoughtfully at ingest:
| Strategy | How | Best for | Weakness |
|---|---|---|---|
| Fixed size | N tokens + overlap | uniform text, logs | cuts mid-sentence |
| Recursive | heading → para → sentence | structured docs | separators per format |
| Semantic | split on embedding-distance jumps | prose, chat logs | extra embedding passes |
Default to fixed-with-overlap; go recursive for structured docs. Store
doc_id + chunk_index beside each vector so answers can cite sources.
Rank Fusion Beats Score Fusion
Vector search misses exact tokens — error codes, function names — so run
keyword search alongside it and merge the two ranked lists with
reciprocal rank fusion: each document scores Σ 1/(k + rank) over
every ranking it appears in (k ≈ 60). A dozen-line Enum.flat_map/2 +
Enum.reduce/3 into a score map implements it. Ranks are comparable
across retrievers where raw similarity scores are not, so consensus wins
with zero score-calibration step.
28.6 The Agent Landscape
The BEAM’s primitives map onto agent requirements almost embarrassingly well:
| Agent Requirement | BEAM Primitive | Framework Mapping |
|---|---|---|
| Persistent state per agent | GenServer | Jido Agent, session state |
| Supervision & restart | Supervisor | Jido Supervisor |
| Inter-agent messaging | :gen_statem, PubSub | Jido Signal, LangChain callbacks |
| Distributed coordination | :rpc, :pg, Phoenix.PubSub | distributed agent pools |
| Backpressure & flow control | GenStage, Broadway | streaming pipelines |
Jido — OTP-native autonomous agents
Agents are immutable state structs with a schema, running (when needed)
inside supervised AgentServer processes — the same machinery Ch 14
walked through:
defmodule MyApp.Agents.Researcher do
use Jido.Agent,
name: "researcher",
schema: [
topic: [type: :string, required: true],
findings: [type: {:list, :string}, default: []]
],
signal_routes: [
{"research", MyApp.Actions.Research}
]
end
children = [
MyApp.Jido # the `use Jido, otp_app:` runtime — start_agent children live here
]
{:ok, pid} = MyApp.Jido.start_agent(MyApp.Agents.Researcher, id: "r-1")
{:ok, agent} =
Jido.AgentServer.call(pid,
Jido.Signal.new!("research", %{topic: "BEAM agents"}, source: "/dashboard"))
LangChain Elixir — chains, tools, memory
LangChain for Elixir wires chat models, tool execution, and conversation
state into a LLMChain value you drive step by step (LangChain.Chains.LLMChain.new!/1
plus add_message/2 and run/2). Reach for it when you want a ready-made
chain/tool loop; reach for §28.7’s hand-rolled version when you want zero
framework.
Instructor — structured output via Ecto schemas
defmodule ResearchResult do
use Ecto.Schema
@primary_key false
embedded_schema do
field :summary, :string
field :key_points, {:array, :string}
field :confidence, :float
end
end
{:ok, %ResearchResult{} = result} =
Instructor.chat_completion(
model: "gpt-4o",
response_model: ResearchResult,
messages: [%{role: "user", content: "Summarize the BEAM ecosystem"}],
max_retries: 3
)
ReqLLM / LlmComposer
- ReqLLM — unified HTTP clients (OpenAI, Anthropic, Ollama, Mistral) with streaming + retries over Req.
- LlmComposer — declare workflows as data (steps, parallel branches, loops), compile to executable graphs.
28.7 Minimal Multi-Agent Demo (Pure OTP)
You can build real multi-agent systems with nothing but GenServers:
defmodule ResearchAgent do
use GenServer
def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
def research(topic), do: GenServer.call(__MODULE__, {:research, topic})
@impl true
def handle_call({:research, topic}, _from, state) do
summary = "Summary of #{topic}" # ← replace with LLM adapter call
{:reply, summary, state}
end
end
defmodule WritingAgent do
use GenServer
def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
def write(summary), do: GenServer.call(__MODULE__, {:write, summary})
@impl true
def handle_call({:write, summary}, _from, state) do
article = "Article based on: #{summary}"
{:reply, article, state}
end
end
Supervisor.start_link([ResearchAgent, WritingAgent], strategy: :one_for_one)
summary = ResearchAgent.research("Elixir agents")
article = WritingAgent.write(summary)
Each agent is supervised, observable (:sys.get_state), and distributable.
The BEAM is not just a runtime for agents — it is the agent architecture itself.
The Tool-Call Loop as a gen_statem
An agent that plans → calls tools → observes → repeats is a state machine, and you already own the right primitive. Injected funs stand in for the LLM adapter, keeping the loop pure and testable:
defmodule AgentLoop do
@behaviour :gen_statem
def start_link(opts), do: :gen_statem.start_link(__MODULE__, opts, [])
@impl true
def callback_mode, do: :state_functions
@impl true
def init(opts) do
data = %{question: Keyword.fetch!(opts, :question),
decider: Keyword.fetch!(opts, :decider),
executor: Keyword.fetch!(opts, :executor),
turn: 0, max: Keyword.get(opts, :max_turns, 5), answer: nil}
{:ok, :thinking, data, [{:next_event, :internal, :step}]}
end
# one model turn per :step event; the cap bounds spend
def thinking(:internal, :step, %{turn: t, max: m} = d) when t >= m do
{:next_state, :failed, d, []}
end
def thinking(:internal, :step, d) do
case d.decider.(d.question, d.turn) do
%{tool_calls: [], answer: answer} ->
{:next_state, :done, %{d | answer: answer}, []}
%{tool_calls: calls} ->
{:keep_state, %{d | turn: d.turn + 1},
[{:next_event, :internal, {:exec, calls}}]}
end
end
def thinking(:internal, {:exec, calls}, d) do
_results = d.executor.(calls) # append results to the transcript here
{:keep_state_and_data, [{:next_event, :internal, :step}]}
end
# terminal states absorb stragglers; inspect via :sys.get_state/1
def done(_e, _c, _d), do: :keep_state_and_data
def failed(_e, _c, _d), do: :keep_state_and_data
end
Drive it with a decider that returns tool calls until it returns
%{tool_calls: [], answer: ...}; {state, data} = :sys.get_state(pid)
then shows :done plus the answer. The cap bounds cost, supervision
restarts a wedged loop, and :sys traces every transition.
Explore More
- Req docs — streaming responses
(
into: :self), retries, and step instrumentation - Instructor — structured outputs via Ecto schemas with automatic retry/validation (§28.6)
- Jido — OTP-native agent framework; read its supervision strategy against §28.7’s hand-rolled version
- pgvector — the Postgres side of the RAG pipeline; pair with Ch 11’s Ecto knowledge
- Exercise idea: extend §28.5’s RAGPipeline with real pgvector retrieval — embed documents at write time with an Oban worker, query-time top-k in Ecto, stream answers through a LiveView
- Practice Lab: Lab 6 — Bumblebee Semantic Search — the retrieval/re-ranking half of this chapter’s RAG pipeline, built on an all-new support-desk example
Checkpoint
- Which BEAM primitive gives each agent isolated persistent state?
- Name three transports an LLM adapter can hide behind.
- In RAG, which steps are numerical vs data vs web?
Answers
- GenServer.
- Port (external binary), NIF (in-process library), HTTP (Ollama/vLLM/API), plus local Nx/Bumblebee.
- Numerical: embedding + generation; Data: vector search/retrieval; Web: LiveView streaming to the user.
Next: Chapter 29 — Architecture Philosophy
Chapter 29 — Architecture Philosophy: BEAM Orchestrates
The value of the Elixir ecosystem is not any single library. It is the architecture created by composing them — a pattern an Erlang developer already knows by heart.
29.1 The Three-Layer Picture
flowchart TD
EX["Elixir"] --> WEB["Web<br/>Phoenix"]
EX --> RT["Realtime<br/>OTP"]
EX --> AI["AI<br/>Nx"]
WEB --> BEAM["BEAM"]
RT --> BEAM
AI --> BEAM
BEAM --> NB["Native Backends"]
NB --> HW["CPU / GPU / Device"]
The philosophy in one line:
BEAM handles orchestration. Specialized runtimes handle specialized computation.
It applies across every domain:
| Domain | Elixir describes | Native runtime executes |
|---|---|---|
| Web | Phoenix, controllers, LiveView | the browser + BEAM schedulers |
| Data | Ecto / Explorer queries | Database engines |
| AI | Nx / Axon graphs | XLA / MLX / llama.cpp |
| IoT | Nerves / AtomVM supervision | Linux kernel / MCU hardware |
| Mobile | Mob / Dala logic | SwiftUI / Jetpack Compose |
| Native | Rustler/NIF interfaces | Rust / C |
The Chain, Concretely
The five-layer chain below resolves to named building blocks. Read the table bottom-up: incidents start at the bottom, and the architecture question is always “what does the layer above do when this one dies?”
| Chain layer | Concrete tech | When it fails |
|---|---|---|
| Specialized runtime | Postgres, XLA, llama.cpp | black box; degrade gracefully |
| External capability | Req/Finch, Port, Rustler NIF | error tuple/timeout to caller |
| Message | PubSub, GenStage, Broadway | redelivered/dropped per contract |
| Process | GenServer, LiveView, Nx.Serving | crash contained; restarted |
| Supervisor | Supervisor, restart intensity | last resort — escalates upward |
29.2 You Already Know This Pattern
This is exactly how gen_server calls into a Port or NIF — generalized.
Read bottom-up (a request flows downward; a failure propagates upward):
flowchart TD
NAT["Native / specialized runtime"] --> EXT["External capability<br/>Port · NIF · HTTP · gRPC"]
EXT --> MSG["Messages<br/>async · sync · PubSub"]
MSG --> PROC["Processes<br/>GenServer · GenStage · LiveView"]
PROC --> SUP["Supervisor"]
The BEAM doesn’t need to become the GPU runtime, database engine, or device firmware. It is the reliable coordinator. That’s why the same runtime now spans cloud → edge → devices → accelerators.
29.3 From Infrastructure to Product
Erlang historically owned infrastructure-heavy systems. The ecosystem lets the same foundation move closer to the product:
Distributed systems → messaging + concurrency → real-time backend
→ web application → data pipeline → edge device → AI-powered application
| Domain | Examples | BEAM Advantage |
|---|---|---|
| SaaS | multi-tenant platforms | isolation, supervision |
| Fintech | trading, ledgers | fault tolerance, auditability |
| Real-time collab | docs, whiteboards | stateful connections, Presence |
| Messaging | chat, notifications | gen_server, clustering |
| Live tracking | sports, betting | low latency, massive concurrency |
| Data platforms | ETL, analytics | Broadway/GenStage backpressure |
| IoT | gateways, robotics | Nerves, AtomVM, watchdogs |
| Edge inference | smart cameras | local Nx, privacy, offline |
| AI-enabled apps | RAG, agents, copilots | orchestration + native inference |
29.4 Why Now?
- Phoenix/LiveView made BEAM ideas product-facing for the web.
- Nx/Axon/Bumblebee opened ML without leaving the runtime.
- Nerves/AtomVM pushed it onto devices.
- Gradual typing (Ch 07) is landing without breaking the ecosystem.
The Deployment Story, Honestly
mix release emits a directory: ERTS bundled, runtime.exs for
environment-driven config, and two commands that matter here —
bin/<app> rpc 'EXPR' evaluates one expression on the running node, while
bin/<app> remote drops you into an interactive remote shell. (bin/<app> rpc alone is not “a shell”; that distinction costs an afternoon once.) You trade a single-file artifact for live introspection —
attach to production, inspect any process, run a migration check without
redeploying. Containers level most of the difference; pick per ops
culture, not ideology.
The valuable career skill is not “I know Elixir.” It is:
“I can build reliable distributed systems and apply the BEAM across modern application domains.”
Architecture · distributed systems · real-time · edge · AI integration — high-leverage systems engineering.
Four Things This Chapter Owes You
The five-layer chain above is a claim about code. These are the claims about deployment an Erlang team inherits and Elixir does not change:
Distribution. Nothing new, but nothing automatic either. Nodes cluster
via :pg (a built-in) for process discovery, Phoenix.PubSub for
message broadcast, and :rpc/:erpc for calls across the cluster.
libcluster handles the gossip and the DNS-based discovery most fleets
actually use:
topologies = [
dns: [
strategy: Cluster.Strategy.DNSPoll,
config: [query: "my-app.example.com", node_basename: "my-app",
polling_interval: 5_000]
]
]
children = [
{Cluster.Supervisor, [topologies, [name: MyApp.ClusterSupervisor]]},
{Phoenix.PubSub, name: MyApp.PubSub}
]
The hosting question. Fly.io, Render, Railway, or a plain VPS with a
systemd unit calling bin/<app> daemon. Ch 09 has the release mechanics;
this is the operational wrapper.
Observability. Telemetry events (Ch 10 §10.7, Ch 27 §27.5) →
Telemetry.Metrics → LiveDashboard or Prometheus. This is the layer that
makes “what does the layer above do when this one dies” answerable in
production instead of in your head.
Rollback. Immutable images plus a database migration that can go backwards — or, when it cannot, an expand/contract migration sequence. Ch 30’s rollback-per-phase table is the same discipline at migration scale.
None of this is Elixir-specific; that is the point. The runtime is the same one you already know, which means the operational playbook transfers too.
Explore More
- The Beam Book — distribution, scheduling, and memory internals behind every claim in §29.1–29.3
- Designing for Scalability with Erlang/OTP (Hésson & Vinoski) — the architecture patterns Elixir inherits wholesale
- Phoenix deployment guides — where the “BEAM orchestrates” pattern meets real infrastructure
- Exercise idea: draw your current system as §29.1’s five-layer chain — mark each layer’s failure blast radius, and note which boundaries already let it crash safely
Checkpoint
- What role does the BEAM play when XLA does the math?
- Name the five layers of the orchestration chain and what each contributes.
- What is the pattern shared between a GenServer calling a Port and an app calling an LLM?
Answers
- Reliable coordinator: sessions, streaming, queues, supervision, distribution around the accelerator.
- Specialized runtime → external capability → message → process → supervisor; each boundary defines a failure contract.
- Supervisor → process → message → external capability → specialized runtime. Identical shape at every scale.
Next: Chapter 30 — The Migration Roadmap
Chapter 30 — The Migration Roadmap
An 8-week, step-by-step plan from “I know Erlang” to “I ship in the Elixir ecosystem.” Each phase has concrete actions, artifacts, and an exit checklist. Adjust the pace — keep the order.
Phase 0 — Environment (Day 1)
Do:
- Install Elixir via your version manager (mise/asdf): target Elixir 1.20.x (gradual typing, Ch 07) on a current OTP release. The minimum for this book is OTP 26+, but new projects should start on the latest stable line (OTP 28/29 as of writing) — check erlang.org and the Elixir “Compatibility and deprecations” page for the pairing.
- Install Livebook:
brew install livebook(ormix escript.install hex livebook). - Keep a scratch notebook open from day one — every chapter’s iex blocks paste directly into cells.
Exit when: elixir --version shows 1.20+ on your chosen OTP, Livebook opens.
Verify Before You Trust
elixir --version
#=> Erlang/OTP 28 [erts-…] … [64-bit] …
#=> Elixir 1.20.x (compiled with Erlang/OTP 28)
Pin the pair, not just the Elixir version — most first-day failures are
an Elixir binary compiled against a different OTP than the one on $PATH.
Phase 1 — Syntax (Week 1)
Goal: read Elixir as fast as you read Erlang.
- Work through Ch 02 tables; translate one of your own
.erlmodules by hand. - Drill the differences: strings-are-binaries,
fnvsfun,@attrvs-define, structs vs records. - Practice pipes until nested calls feel wrong: rewrite three list pipelines
with
|>+Enum. - Read Ch 25 (pattern matching deep dive) and redo this phase’s drills with its rules in mind — pins instead of Erlang’s auto-compare, map subset matching, binary segments. Week 1 is where Erlang reflexes cost you most; the deep dive names each trap before it bites.
Exit checklist:
- Translated module compiles under
mix compile - Can pattern-match a struct in a function head
- Can explain what
^(pin) changes versus a plain variable match (Ch 25) - Know when
"abc"is a binary vs~c"abc"a charlist
The Translation Drill, Side by Side
Pick a module you know cold — translation exposes the real differences:
%% totals.erl
total([]) -> 0;
total([{_, Price} | Rest]) -> Price + total(Rest).
defmodule Totals do
def total([]), do: 0
def total([{_, price} | rest]), do: price + total(rest)
end
Identical shape. Then rewrite it as Enum.reduce/3 and notice the
recursive clause pair was the reduce all along — that click is Week 1’s
real goal.
Phase 2 — Tooling (Week 2)
Goal: Mix replaces rebar3 muscle memory (Ch 03).
mix new drill --sup; add a GenServer child — after skimming Ch 23, so the catch-allhandle_info, call timeouts, andterminatetruth table are right from day one; write ExUnit tests.- Add a Hex dep, call an Erlang module (
:lists,:ets) from Elixir code. - Run
mix format,mix docs(add ex_doc), buildmix release(Ch 09). - Turn on the type checker: read every warning from
mix compile(Ch 07 §7.3’styping_demoscratch project is the sandbox). - Kill your own GenServer mid-request and watch the supervisor rebuild it
(Ch 22–24) — restart budgets,
:rest_for_oneordering, and crash reports read in dev cost nothing; in prod they cost incidents.
Exit checklist:
- Supervised app with tests passes
mix test - Release boots:
_build/prod/rel/drill/bin/drill start - Fixed at least two gradual-typing warnings
- Killed and restarted a supervised child on purpose, then explained the crash report line by line (Ch 24)
Read the Build Like a Profiler
mix xref graph --label compile-connected
#=> every edge here recompiles downstream files — keep this list short
mix test --cover
#=> per-module coverage %; track the trend across phases, not the absolute
Compile-time coupling is Erlang’s xref habit wearing Elixir clothes —
same disease, better tooling.
Phase 3 — Idioms & Polymorphism (Week 3)
Goal: write code that looks native (Ch 04–05).
- Convert an eager pipeline over large data to
Stream; measure memory. - Write one behaviour (with
@impl) and one protocol with twodefimpls. - Read a small library’s source starting from its
__using__macro (Ch 06).
Exit checklist:
- Can explain protocol-vs-behaviour choice in one sentence
- Comfortable reading macro-generated Phoenix/Ecto code without panic
Phase 4 — Web (Week 4)
Goal: ship a real-time feature (Ch 10).
mix phx.new realtime_demo --live; walk the generated supervision tree in Observer — recognize everything.- Build a LiveView counter/chat; add PubSub broadcast; open two tabs.
- Persist something with Ecto (schema → changeset → migration → query).
- Add an Oban worker that writes summaries of stored rows.
Exit checklist:
- Two-browser-tab real-time update working
- One DB-backed feature end-to-end (changeset validated)
- One background job retried on forced failure
Phase 5 — AI on the BEAM (Weeks 5–6)
Goal: hands-on Numerical Elixir (Part IV).
Work through the code in order, evaluating every block in your notebook:
| Order | Source | Focus |
|---|---|---|
| 1 | Ch 17 §17.3–17.7 | tensors, broadcasting, defn, autodiff |
| 2 | Ch 19 §19.1–19.3 | MNIST MLP → custom grad loop → CNN |
| 3 | Ch 20 §20.2–20.10 | HF models: text/vision/audio/embeddings |
| 4 | Bumblebee example Livebooks | end-to-end community recipes |
Round out the week with Scholar (Ch 13 §13.4) — Scholar.Cluster.KMeans.fit/2
on synthetic blobs takes five minutes and proves traditional ML shares the
same tensors and backends.
Then productionize:
- Build Ch 21’s blueprint app:
mix phx.new mnist_phoenix --live, add the four ML modules from §21.3, train, serve. - Read your four modules against Ch 21’s lessons (Model/Persistence/Serving/ServingManager).
- Modify one thing: batch size, backend, or add a probabilities endpoint.
Backend selection reminder (Ch 18): EXLA everywhere for Bumblebee; EMLX only for plain Nx on Apple Silicon; BinaryBackend for CI/debugging.
Exit checklist:
- MNIST notebook trains to >95% test accuracy locally
- Your blueprint app serves predictions from the drawn canvas
- Can articulate what
Nx.Defn.gradreturns for a map container
Phase 6 — Specialize (Weeks 7–8)
Pick ONE lane and go deep:
- Edge:
mix nerves.new blinky, burn to a Pi; wire one Circuits peripheral (Ch 16). Stretch: AtomVM on an ESP32. - Agents/RAG: extend Ch 28’s RAGPipeline with pgvector + Ollama adapter; stream answers through a LiveView.
- Data platform: Broadway pipeline from a queue into Ecto + Explorer analytics in Livebook (Operate mode attached to it).
Exit artifact: one deployed/demo-able project in your lane using ≥2 ecosystem libraries.
Milestone Exit Criteria, Measured
Each checkpoint is observable — collect the evidence, don’t self-certify:
| Week | Milestone | Measurable exit |
|---|---|---|
| 1 | Syntax | translated module compiles clean; 3 pipelines on |>; pin rule explained (Ch 25) |
| 2 | Tooling | mix test green, release boots, zero type warnings; forced child restart explained (Ch 24) |
| 3 | Idioms | Stream memory numbers recorded; behaviour + protocol merged |
| 4 | Web | two-tab update < 100 ms locally; forced job retry observed |
| 5–6 | Numerical | MNIST > 95%; serving p95 latency logged |
| 7–8 | Lane | demo URL reachable; README reproduces it from a fresh clone |
Rolling Out to a Team
- Pairing rotation: every Erlang developer pairs a week on the new Elixir service, then rotates — knowledge spreads, nobody becomes the single translator.
- Review guidelines:
mix format --check-formattedand Credo gate CI;@implmandatory on behaviour callbacks; macro-containing PRs need a written justification (see the pitfalls table below). - Style adoption order: formatter first, pipes/naming second, behaviours/protocols third, macros last — the same order as the pitfalls table. Adopting style bottom-up beats debating it.
Common Pitfalls for Erlang Developers
| Pitfall | Fix |
|---|---|
| Expecting bound vars to compare in patterns (Erlang reflex) | Elixir rebinds; use ^var to compare (Ch 25) |
Treating "str" as charlist | Strings are binaries; charlists are ~c"str" ('str' is deprecated since 1.17) |
Expecting 10 / 4 to be integer division | / always returns floats; use div/2, rem/2 (Ch 02) |
Using = where you mean exact equality | == is numeric-loose; === is the match-exact one (1 === 1.0 is false) |
| Fighting the pipe style | Data-last argument order enables |>; adopt it |
| Writing macros early | Functions + behaviours cover 95%; macros are last resort |
Skipping mix format | It’s canonical; enable in CI |
| Reaching for Redis for queues/jobs | Postgres-backed Oban usually suffices |
| Double-encoding JSON with Req | Pass maps to json:; don’t pre-call Jason.encode! (Ch 28) |
Assuming unless is fine | Soft-deprecated in 1.18 (no warning emitted) — prefer if not / explicit case; unless ... else is the confusing case |
| Using EMLX for Bumblebee notebooks | EXLA required today (Ch 18) |
| Expecting ORM-style implicitness | Ecto changesets are explicit by design |
Migration Risk Register
Project-level risks, distinct from the language pitfalls above:
| Risk | Likelihood | Mitigation |
|---|---|---|
| False confidence from easy syntax | High | pair reviews month 1; strict Credo |
| Split-brain conventions | Medium | one formatter-enforced style guide, day 1 |
| OTP mistranslation | Medium | behaviour-callback checklist in review |
| Dependency drift | Medium | pinned mix.lock; monthly mix hex.outdated |
| Perf surprises on hot paths | Low–Med | benchmark before porting |
| Onboarding ramp | Medium | this roadmap is the onboarding plan |
Tracking Migration Health
Pick three numbers; review them weekly like uptime:
| Signal | Source | Healthy trend |
|---|---|---|
| Compile-time coupling | mix xref graph --label compile-connected | shrinking |
| Test coverage | mix test --cover | rising per ported module |
| Incident attribution | alert → process via Observer/:sys/recon | falling |
Rollback Strategy Per Phase
Decide the undo before each step, not during the incident:
| Phase | Rollback move |
|---|---|
| Syntax drills | branches only — discard; nothing shipped |
| Tooling | revert mix.lock; release dirs are immutable |
| Web features | feature-flag the route; mix ecto.rollback for migrations |
| Background jobs | Oban: pause queues, drain, flip workers off |
| Prod cutover | blue-green: old node stays in the cluster one full cycle |
Rule of thumb: never migrate data you cannot unmigrate, and ship dark (wired but disabled) before cutting traffic.
Resources
Books / docs
- Machine Learning in Elixir — Sean Moriarity (PragProg)
- hexdocs: nx · axon · bumblebee · scholar · polaris · phoenix
- Nx backends guide: hexdocs.pm/nx/backends.html
Community / browsing
- ElixirForum (phoenix & nx subforums)
- Hugging Face models tagged Bumblebee: huggingface.co/models?library=bumblebee
- Livebook examples: github.com/livebook-dev/livebook/tree/main/examples
In this guide
- Ch 02 §2.6 — the Erlang↔Elixir keyword map, plus checkpoint drills per chapter
- Ch 07 §7.3 — the gradual-typing sandbox recipe (
typing_demo) - Ch 21 §21.3 — the production serving blueprint (
mnist_phoenix, assembled) - Ch 22–25 (Part V) — deep dives to keep at hand when drills get real: processes & signals, GenServer’s call protocol, supervisor strategies and restart budgets, pattern-matching execution rules
The Final Message
Erlang gave us a runtime for building reliable concurrent systems.
Elixir is building an ecosystem that takes those ideas into web, real-time, edge, mobile and AI.
You don’t need to leave Erlang behind. You already know the hardest part: BEAM + OTP. Elixir gives you more places to apply it.
The strongest career story is not “learn another language.” It is:
Become an orchestrator — build things for yourself first; opportunity and career follow.
flowchart TD
OTP["OTP
what you know"] --> EX["Elixir
types · tooling · macros · composition"]
EX --> WEB["Phoenix / LiveView ↔ Data
web · Ecto/Ash"]
WEB --> AIm["AI/ML
Nx · EXLA · EMLX · Axon · Bumblebee"]
AIm --> EDGE["IoT / Edge / Mobile
Nerves · AtomVM · Mob/Dala"]
EDGE --> EI["Edge Intelligence
local inference/training"]
Part VII — AI Practice Labs
Six guided labs. Each pairs a chapter here with a runnable Livebook in the
livebooks/ collection. The examples are all new — a solar-farm tracker,
an iris botanist, tangled spirals, wardrobe vision, a tiny text generator,
and a support-desk search engine — chosen so every lab teaches a distinct
invariant instead of re-walking the chapters.
| Lab | Title | Livebook | Pairs With | Invariant it teaches |
|---|---|---|---|---|
| LAB 1 | Nx Optimization: Tilting Solar Panels | LAB1_nx_tilt_optimizer.livemd | Ch 17, 18 | defn + autodiff: you supply the forward definition, grad/2 supplies the derivative |
| LAB 2 | Classical ML with Scholar | LAB2_scholar_iris.livemd | Ch 17, 13 | when not to reach for Axon — a tabular model is Scholar.Linear, not a neural net |
| LAB 3 | Axon: Untangling the Two Spirals | LAB3_axon_spiral.livemd | Ch 19 | the loop is a reduction over a stream; run/4 returns an %Axon.ModelState{} |
| LAB 4 | CNN on Fashion-MNIST | LAB4_cnn_fashion_mnist.livemd | Ch 19, 21 | shape arithmetic is the design work — you can read the table fluently |
| LAB 5 | Character-Level LSTM | LAB5_char_lstm.livemd | Ch 19, 20 | batching and dtype discipline: one short batch means a recompile |
| LAB 6 | Bumblebee Semantic Search | LAB6_bumblebee_semantic_search.livemd | Ch 20, 28 | rank fusion beats score fusion; retrieval quality is decided by chunking |
Open Livebook from the repository root and each LAB*.livemd runs top to
bottom. The runnable files are bundled in this directory’s
livebooks/ folder.
Running the Labs
Each lab starts with its own Mix.install/1 cell, so Livebook handles
dependency resolution per notebook — you do not need a mix.exs. That cell
is also the reason every lab must be run from the top: nothing below it has
its dependencies until it evaluates.
Requirements:
- Elixir 1.20+ on OTP 27+
- Livebook
0.14+(livebook serverfrom the repo root, then open a lab) - Disk: 1GB for deps and model caches; LAB6 additionally downloads embedding models (~130MB for E5, more if you swap in a larger one)
- RAM: 4GB minimum. EXLA compiles on first use and wants a core per scheduler; 8GB is comfortable.
Expect roughly:
| Lab | Wall clock (first run) | Notes |
|---|---|---|
| LAB1 | 2–4 min | dep compile dominates; the rest is instant |
| LAB2 | 3–5 min | |
| LAB3 | 3–6 min | trains on CPU in under a minute once compiled |
| LAB4 | 5–10 min | the longest; convolution is slower on CPU |
| LAB5 | 3–8 min | corpus download at the start |
| LAB6 | 4–8 min | model download dominates |
No GPU? Everything runs on Nx.BinaryBackend — drop the {:exla, ...}
line from Mix.install and the labs still work, just slower. EXLA on
laptop CPU is the default expectation, not a GPU.
Stale pins are the most common failure. If a dep resolves to something
that does not exist, or a signature changed, Livebook caches the build:
restart the notebook and clear the cache (File.rm_rf!(".livemd-cache")
or Livebook’s “Restart and clear cache”). Library versions across these labs
match Part IV: nx ~> 0.13, exla ~> 0.13, axon ~> 0.8,
bumblebee ~> 0.7, scholar ~> 0.4, kino ~> 0.14.
A Note on Hardware Claims
Every lab prints timings. On a laptop CPU those numbers are honest for CPU and meaningless for GPU — do not quote a CPU figure as an accelerator result. The measurement discipline (pin shapes, warm up, compare backends on equal footing) is the transferable part; the absolute numbers are not. Ch 18 §18.8 explains what makes a backend comparison fair.
Lab 1 — Nx Optimization: Tilting Solar Panels with Autodiff
Section
Chapters 17 and 18 explained tensors, defn, gradients, and backends. This lab makes you
use them on a problem that is not a toy function on a whiteboard:
squeezing daily energy out of a solar tracker. Every example is new — we
optimize the daily energy output of a solar panel by finding its best
tilt angle, then fit the panel’s calibration curve from noisy sensor
readings, and finally benchmark backends.
From Erlang you know:
grad/2is the numerical analogue of writing a derivative by hand in a paper you never trust again. You hand over the forward definition; the machine derives the rest. Nothing here mutates state — the ascent loop threads a tensor like a fold over a list.
What You’ll Build
- Gradient ascent on tilt angle — find the tracker angle that
maximizes daily energy, starting from a bad guess, using only the
forward model and
grad/2. - A calibration fit from noisy sensors — two parameters, one
defnloss, gradients returned in a map container. - A backend benchmark — the same
defnunderNx.BinaryBackendand EXLA, timed with Benchee.
Mix.install([
{:nx, "~> 0.13"},
{:exla, "~> 0.13"},
{:kino, "~> 0.14"},
{:vega_lite, "~> 0.1"},
{:kino_vega_lite, "~> 0.1"},
{:benchee, "~> 1.3"}
])
Section 1 — Sensor readings as tensors
A solar farm reports hourly readings: panel tilt (degrees) and measured irradiance (kW/m²). Pack one hour’s readings into a tensor and broadcast a unit-conversion (kJ → kWh) over the whole day.
Nx.global_default_backend(EXLA.Backend)
tilts =
Nx.tensor([
[20.0, 25.0, 30.0, 35.0], # morning set-point sweep
[40.0, 45.0, 50.0, 55.0] # afternoon set-point sweep
])
irradiance =
Nx.tensor([
[0.41, 0.62, 0.78, 0.88],
[0.93, 0.97, 0.91, 0.80]
])
# kWh per reading = irradiance * panel_area * 0.25h, broadcast over both axes
panel_area = 2.1
kwh = irradiance |> Nx.multiply(panel_area) |> Nx.multiply(0.25)
Nx.shape(kwh)
Named axes remove the “which axis is which?” guesswork:
kwh
|> Nx.rename([:rows, :slots])
|> Nx.mean(axes: [:slots]) # per-row average, shape {2}
Section 2 — The energy model and its gradient
A single-axis tracker’s daily energy E(tilt) rises, peaks, and falls.
We model it with a curve that peaks near the site latitude (40°):
defmodule Tracker do
import Nx.Defn
# Normalized daily energy for a tilt angle in degrees. Peaks near 40.
# Scaled by 40 so gradients are O(1) — unscaled models converge slowly.
defn energy(tilt) do
x = Nx.divide(tilt, 40.0)
Nx.multiply(40.0, Nx.multiply(x, Nx.exp(Nx.negate(x))))
end
defn energy_grad(tilt) do
grad(tilt, &energy/1)
end
# One gradient-ascent step: move uphill, scaled by the learning rate.
defn ascent_step(tilt, lr) do
tilt + lr * grad(tilt, &energy/1)
end
end
tilts = Nx.linspace(0.0, 120.0, n: 121)
energies = Tracker.energy(tilts)
alias VegaLite, as: Vl
Vl.new(title: "Daily energy vs tilt", width: 720, height: 480)
|> Vl.data_from_values(%{
tilt: Nx.to_flat_list(tilts),
energy: Nx.to_flat_list(energies)
})
|> Vl.mark(:line)
|> Vl.encode_field(:x, "tilt", type: :quantitative)
|> Vl.encode_field(:y, "energy", type: :quantitative)
Gradient ascent from a bad starting angle — no closed form, just the
derivative. Ascent is descent with a sign flip: no loop library, no
framework, an Enum.reduce/3 threads the tensor exactly like threading
an accumulator through lists:foldl/3:
tilt = Nx.tensor(5.0)
lr = 50.0
final_tilt =
Enum.reduce(1..80, tilt, fn _, t ->
Tracker.ascent_step(t, lr)
end)
"Optimal tilt: #{Float.round(Nx.to_number(final_tilt), 2)}°, " <>
"energy: #{Float.round(Nx.to_number(Tracker.energy(final_tilt)), 4)}"
Sweeping all starting points at once — tensors let every row ascend in parallel:
starts = Nx.tensor([2.0, 10.0, 30.0, 80.0, 110.0])
Enum.reduce(1..80, starts, fn _, t -> Tracker.ascent_step(t, 50.0) end)
|> Nx.to_flat_list()
|> Enum.map(&Float.round(&1, 1))
All five converge to the same peak regardless of where they started. Because tensors are data, every candidate angle ascends in parallel — one compiled program, one gradient per row.
Section 3 — Fitting a calibration from noisy sensors
Real panels deviate from the ideal model. Field calibration is affine:
measured ≈ gain * ideal(tilt) + offset. Fit both parameters by
minimizing squared error. Note the params container: a map in, a map of
gradients out — and the update is plain Elixir, outside defn. This
division of labor is the contract Axon’s optimizers are built on — after
this lab, Chapter 19’s Axon.ModelState reads as “containers all the
way down.”
defmodule Calibration do
import Nx.Defn
defn model(params, tilt) do
params[:gain] * Tracker.energy(tilt) + params[:offset]
end
defn mse(params, tilt, measured) do
predicted = model(params, tilt)
measured
|> Nx.subtract(predicted)
|> Nx.pow(2)
|> Nx.mean()
end
# defn computes loss + gradients; it does not perform the update.
defn loss_and_grads(params, tilt, measured) do
value_and_grad(params, &mse(&1, tilt, measured))
end
end
Generate noisy “field data” and descend. (Why not update inside defn?
Map-building functions are plain-Elixir territory — defn computes
numbers, your code orchestrates the loop. Gradient descent is a fold.)
key = Nx.Random.key(1337)
{noise, _k} = Nx.Random.normal(key, 0.0, 0.03, shape: {400})
{x_train, _k} = Nx.Random.uniform(key, 0.0, 110.0, shape: {400})
true_gain = 1.05
true_offset = 0.02
y_train =
Calibration.model(%{gain: Nx.tensor(true_gain), offset: Nx.tensor(true_offset)}, x_train)
|> Nx.add(noise)
params = %{gain: Nx.tensor(0.6), offset: Nx.tensor(0.4)}
lr = 0.005
{final_loss, fitted} =
Enum.reduce(1..2000, {Nx.tensor(0.0), params}, fn _, {_, p} ->
{loss, grads} = Calibration.loss_and_grads(p, x_train, y_train)
{loss,
%{
gain: Nx.subtract(p[:gain], Nx.multiply(lr, grads[:gain])),
offset: Nx.subtract(p[:offset], Nx.multiply(lr, grads[:offset]))
}}
end)
IO.puts("final loss: #{Nx.to_number(final_loss) |> Float.round(6)} (noise floor ≈ 0.0009)")
"gain ≈ #{Nx.to_number(fitted[:gain]) |> Float.round(3)} (true #{true_gain}), " <>
"offset ≈ #{Nx.to_number(fitted[:offset]) |> Float.round(3)} (true #{true_offset})"
Visualize the fit against the data:
xs = Nx.linspace(0.0, 110.0, n: 200)
ys = Calibration.model(fitted, xs)
Vl.new(title: "Fitted calibration curve", width: 720, height: 480)
|> Vl.data_from_values(%{
measured_x: Nx.to_flat_list(x_train),
measured_y: Nx.to_flat_list(y_train),
fit_x: Nx.to_flat_list(xs),
fit_y: Nx.to_flat_list(ys)
})
|> Vl.layers([
Vl.new()
|> Vl.mark(:point, opacity: 0.3)
|> Vl.encode_field(:x, "measured_x", type: :quantitative)
|> Vl.encode_field(:y, "measured_y", type: :quantitative),
Vl.new()
|> Vl.mark(:line, color: "#d62728")
|> Vl.encode_field(:x, "fit_x", type: :quantitative)
|> Vl.encode_field(:y, "fit_y", type: :quantitative)
])
Section 4 — Backend benchmark: BinaryBackend vs EXLA
The same defn, two execution strategies. The defn body never
mentions the backend — backends are an execution decision, not a code
change. Benchee reports what the backend choice is worth on your machine,
and also shows EXLA’s first call paying a JIT compilation toll. Both
facts shape deployment: compile warmup belongs in release boot, not the
first request:
{big, _key} = Nx.Random.uniform(Nx.Random.key(7), 0.0, 1.0, shape: {1_000, 1_000}, type: :f32)
defmodule Bench do
import Nx.Defn
defn softmax_rows(t) do
t
|> Nx.exp()
|> Nx.divide(Nx.sum(Nx.exp(t), axes: [-1], keep_axes: true))
end
end
{binary_time, _} =
:timer.tc(fn ->
big |> Nx.backend_copy(Nx.BinaryBackend) |> Bench.softmax_rows()
end)
{exla_time, _} =
:timer.tc(fn ->
Bench.softmax_rows(Nx.backend_copy(big, EXLA.Backend))
end)
"binary: #{div(binary_time, 1000)} ms, exla (after JIT): #{div(exla_time, 1000)} ms"
For a rigorous comparison, let Benchee warm up the EXLA compilation first:
exla_input = Nx.backend_copy(big, EXLA.Backend)
Bench.softmax_rows(exla_input) # trigger JIT before benchmarking
Benchee.run(
%{
"binary" => fn -> Bench.softmax_rows(Nx.backend_copy(big, Nx.BinaryBackend)) end,
"exla" => fn -> Bench.softmax_rows(exla_input) end
},
time: 3,
memory_time: 1
)
Section 5 — Inspect the compiled graph
print_expr/2 shows what the compiler actually sees — notice how the
gradient was computed for you:
defmodule GradInspect do
import Nx.Defn
defn probe(t) do
t
|> Nx.multiply(2.0)
|> Nx.tanh()
|> Nx.sum()
|> print_expr(label: "forward")
end
defn probe_grad(t) do
grad(t, &probe/1)
|> print_expr(label: "gradient")
end
end
GradInspect.probe_grad(Nx.tensor([0.5, -0.5, 2.0]))
Checkpoint
- Why does starting five tilts at once converge faster wall-clock than five sequential runs?
- If you swapped the ascent step to
tilt - lr * grad(...), what does the optimizer find, and what is that called? - Why should the EXLA warmup happen at boot rather than on first request?
Answers
- One compiled
defncall computes all five gradients in a single fused program — the per-call overhead is paid once, and the backend vectorizes across the leading axis. - The minimum of the energy curve (gradient descent). Same code, one sign — the loss-minimization default everywhere in Part IV.
- The first call triggers JIT compilation of a shape-specific program; serving that latency to the first real request is a self-inflicted timeout.
Where to next
- Run the cells in order; try changing
lrin Section 3 and watch the fit diverge or crawl. - Exercise: replace the MSE in
Calibrationwith mean absolute error (Nx.mean(Nx.abs(...))) — does the gradient still flow? Watch how the fit responds to outlier sensors differently. - Exercise: convert the ascent loop in Section 2 to a
defnwhileloop so the whole optimization compiles into one XLA program, then benchmark it against theEnum.reduceversion. - Section 5 prints the graph
print_expr/2sees — including the synthesized gradient. Follow thegradnode to see reverse mode made concrete.
Lab 2 — Classical ML with Scholar: The Iris Botanist
Section
Not every problem needs a neural network. Scholar — traditional ML compiled through the same Nx/EXLA stack — handles the bread-and-butter work of production ML: scaling, logistic regression, k-NN, clustering, dimensionality reduction. This lab walks the full lifecycle on the 150-row iris flower set: 4 features, 3 species, 0 GPUs required. All-new examples: we classify iris flowers, read a confusion matrix, and let K-Means discover the species without labels — no deep learning anywhere, and yet this is the workflow most production ML actually looks like.
From Erlang you know: Scholar models are pure structs —
fit/3returns data,predict/2takes data. Like an ets-cached computation, a fitted model is a value you can pass between processes with no locks and no session.
What You’ll Build
- A leakage-free pipeline — shuffle by indices, standardize with train-only statistics, split 80/20.
- Two classifiers — multinomial logistic regression and 5-NN — plus the confusion matrix that explains their errors.
- Unsupervised discovery — K-Means recovers species with the labels removed; PCA projects 4-D onto 2-D for the plot.
Mix.install([
{:scholar, "~> 0.4"},
{:nx, "~> 0.13"},
{:exla, "~> 0.13"},
{:scidata, "~> 0.1.11"},
{:kino, "~> 0.14"},
{:vega_lite, "~> 0.1"},
{:kino_vega_lite, "~> 0.1"}
])
Section 1 — Load and standardize
Scidata.Iris returns plain lists: 150 rows × 4 features
(sepal length/width, petal length/width) and integer labels
0 = setosa, 1 = versicolor, 2 = virginica.
Nx.global_default_backend(EXLA.Backend)
{features_raw, labels_raw} = Scidata.Iris.download()
x = Nx.tensor(features_raw) # {150, 4} f32
y = Nx.tensor(labels_raw) # {150} s64
Nx.shape(x) |> IO.inspect(label: :features)
Nx.shape(y) |> IO.inspect(label: :labels)
Shuffle and split 80/20. The idiomatic way is to shuffle indices first, then gather — inputs and labels stay aligned by construction:
:rand.seed(:exsss, {7, 3, 2026})
indices =
Nx.to_flat_list(Nx.iota({150}))
|> Enum.shuffle()
|> Nx.tensor()
shuffled_x = x[indices]
shuffled_y = y[indices]
train_x = shuffled_x[0..119//1]
train_y = shuffled_y[0..119//1]
test_x = shuffled_x[120..149//1]
test_y = shuffled_y[120..149//1]
{Nx.shape(train_x), Nx.shape(test_x)}
Standardize using train statistics only — a classic leakage bug is letting the test set vote on the mean and std. Applying the test set’s own statistics is target leakage — the most common silent accuracy inflator in applied ML. The transform must be a closure over numbers the model could have known at training time:
mean = Nx.mean(train_x, axes: [0], keep_axes: true)
std = Nx.standard_deviation(train_x, axes: [0], keep_axes: true)
standardize = fn t -> Nx.divide(Nx.subtract(t, mean), std) end
train_x = standardize.(train_x)
test_x = standardize.(test_x)
Section 2 — Logistic regression (multinomial)
logreg = Scholar.Linear.LogisticRegression.fit(train_x, train_y, num_classes: 3)
preds = Scholar.Linear.LogisticRegression.predict(logreg, test_x)
Scholar.Metrics.Classification.accuracy(test_y, preds)
The confusion matrix tells you how it fails, not just how often. Accuracy compresses 30 test predictions into one number; the matrix decompresses it: which species eats which other’s samples, and how often. You will see setosa errors are (almost) nonexistent — it is linearly separable — while versicolor and virginica share borderline samples. That asymmetry is a product decision waiting to happen:
cm = Scholar.Metrics.Classification.confusion_matrix(test_y, preds, num_classes: 3)
classes = ["setosa", "versicolor", "virginica"]
cm_list =
cm
|> Nx.to_flat_list()
|> Enum.chunk_every(3)
|> Enum.with_index(fn row, i ->
%{"actual" => Enum.at(classes, i), "setosa" => Enum.at(row, 0),
"versicolor" => Enum.at(row, 1), "virginica" => Enum.at(row, 2)}
end)
Kino.DataTable.new(cm_list, name: "Confusion matrix (rows = actual)")
Section 3 — K-Nearest Neighbors
A lazy learner: no training at all, just distance lookups. Compare its accuracy with logistic regression’s:
knn =
Scholar.Neighbors.KNNClassifier.fit(train_x, train_y,
num_classes: 3,
num_neighbors: 5
)
knn_preds = Scholar.Neighbors.KNNClassifier.predict(knn, test_x)
Scholar.Metrics.Classification.accuracy(test_y, knn_preds)
Try num_neighbors: 1 vs 15 — low k chases noise, high k blurs class
boundaries. That trade-off is the whole game in k-NN.
Section 4 — K-Means: discovering species without labels
Drop the labels entirely. Does the geometry of the data recover the three species on its own?
kmeans = Scholar.Cluster.KMeans.fit(standardize.(x), num_clusters: 3)
kmeans.clusters |> Nx.shape() |> IO.inspect(label: :centroids)
Cluster IDs are arbitrary (2 may mean setosa), so compare distributions
rather than exact matches. K-Means on the unlabeled data recovers three
groups, but “cluster 2” has no canonical meaning — the plot below sets
clusters against PCA coordinates to make the correspondence visible
without pretending the IDs align. A 2-D projection makes the structure
visible:
alias VegaLite, as: Vl
pca = Scholar.Decomposition.PCA.fit(standardize.(x), num_components: 2)
projected = Scholar.Decomposition.PCA.transform(pca, standardize.(x))
species = Enum.map(Nx.to_flat_list(y), &Enum.at(classes, &1))
Vl.new(title: "Iris in 2 principal components", width: 720, height: 480)
|> Vl.data_from_values(%{
pc1: Nx.to_flat_list(projected[[.., 0]]),
pc2: Nx.to_flat_list(projected[[.., 1]]),
species: species
})
|> Vl.mark(:point, size: 80)
|> Vl.encode_field(:x, "pc1", type: :quantitative)
|> Vl.encode_field(:y, "pc2", type: :quantitative)
|> Vl.encode_field(:color, "species", type: :nominal)
Setosa is linearly separable from the other two — which explains why the confusion matrix in Section 2 had (almost) no setosa errors.
Section 5 — Where models disagree
Inspect the test rows where logistic regression and k-NN disagree — these are exactly the samples worth labeling by hand in a real project:
logreg_all = Scholar.Linear.LogisticRegression.predict(logreg, test_x)
disagreements =
Nx.equal(logreg_all, knn_preds)
|> Nx.to_flat_list()
|> Enum.with_index(fn same, i -> if same == 0, do: i end)
|> Enum.reject(&is_nil/1)
Enum.map(disagreements, fn i ->
%{
"row" => i,
"features" => Nx.to_flat_list(test_x[i]),
"logreg" => Enum.at(classes, Nx.to_number(logreg_all[i])),
"knn" => Enum.at(classes, Nx.to_number(knn_preds[i])),
"truth" => Enum.at(classes, Nx.to_number(test_y[i]))
}
end)
|> Kino.DataTable.new(name: "Disagreements")
Checkpoint
- Why shuffle indices and gather, instead of zipping shuffled rows?
- Your k-NN with
num_neighbors: 1scores 94% on train and 88% on test. What phenomenon is this, and which knob fixes it? - Two models disagree on 4 test rows. Why are those rows worth more than the rows both got right?
Answers
- Gathering by an index tensor is one
Nx.take-style operation — shape stays{n, 4}end-to-end, and inputs/labels cannot fall out of sync the way parallel shuffles can. - Overfitting (variance). Raising
num_neighborssmooths the decision boundary by averaging over a wider neighborhood. - Disagreements mark the boundary of what the features can express — exactly where labels are cheap and model headroom is highest.
Where to next
- Exercise: split 60/40 instead of 80/20 — how stable are the two accuracy numbers? Run the shuffle with three different seeds and record the accuracy spread — your first lesson in why single splits lie.
- Exercise: add per-class
Scholar.Metrics.Classification.precisionandrecall; decide which metric matters if a wrong “virginica” guess is costly, and which class you would collect more samples for. - Exercise: train a
Scholar.Linear.SVM(if your Scholar version ships it) on the same split and compare. - The preprocessing, metrics, and decomposition namespaces used in this lab are documented at hexdocs.pm/scholar.
Lab 3 — Axon: Untangling the Two Spirals
Chapter 19 trained on MNIST, where a linear model already scores ~92%. The two-spiral benchmark removes that crutch: two interleaved spirals that no straight line can separate. This lab makes the relationship between depth, nonlinearity, and capacity something you have watched fail and succeed in the same notebook. All-new examples: we synthesize a two-spiral dataset that no linear model can separate, watch a shallow network fail, then add depth and watch the decision boundary bend.
From Erlang you know: an Axon model is an immutable graph — pipe layers the way you compose function clauses. Adding a layer creates a new graph; nothing in place is mutated. Model state, like GenServer state, is threaded explicitly through the training loop.
What You’ll Build
- Synthetic data generation in pure Nx — two noisy spirals built
from polar coordinates, seeded through functional
Nx.Randomkeys. - A deliberately linear model — dense layers with no activation — and a front-row seat to it plateauing at ~50%.
- A three-layer ReLU MLP that carves the spirals apart, then a decision-boundary heatmap that shows how.
Mix.install([
{:axon, "~> 0.8"},
{:nx, "~> 0.13"},
{:exla, "~> 0.13"},
{:polaris, "~> 0.1"},
{:kino, "~> 0.14"},
{:vega_lite, "~> 0.1"},
{:kino_vega_lite, "~> 0.1"}
])
Section 1 — Synthesize the two-spiral dataset
Classic synthetic benchmark: two interleaved spirals. A straight line cannot separate them — this is the smallest dataset that requires a nonlinear network.
Nx.global_default_backend(EXLA.Backend)
key = Nx.Random.key(2026)
points_per_spiral = 300
# Spiral 1: r grows with theta over two full turns; Spiral 2: same path
# rotated by 180°. Two turns make the arms interleave — anything less and
# the spirals stay linearly separable.
build_spiral = fn offset, k ->
{noise_r, _} = Nx.Random.normal(k, 0.0, 0.06, shape: {points_per_spiral, 1})
{noise_a, _} = Nx.Random.normal(k, 0.0, 0.25, shape: {points_per_spiral, 1})
theta = Nx.linspace(0.0, 4.0 * :math.pi(), n: points_per_spiral) |> Nx.new_axis(-1)
radius = Nx.divide(theta, 4.0 * :math.pi()) |> Nx.multiply(1.0) |> Nx.add(0.2)
angle = Nx.add(theta, Nx.add(offset, noise_a))
cos = Nx.cos(angle)
sin = Nx.sin(angle)
x = Nx.multiply(radius, cos) |> Nx.add(Nx.multiply(noise_r, cos))
y = Nx.multiply(radius, sin) |> Nx.add(Nx.multiply(noise_r, sin))
Nx.concatenate([x, y], axis: 1)
end
spiral_a = build_spiral.(0.0, Nx.Random.fold_in(key, 1))
spiral_b = build_spiral.(:math.pi(), Nx.Random.fold_in(key, 2))
xs = Nx.concatenate([spiral_a, spiral_b], axis: 0)
ys =
Nx.concatenate(
[Nx.broadcast(0.0, {points_per_spiral, 1}), Nx.broadcast(1.0, {points_per_spiral, 1})],
axis: 0
)
{perm, _key2} = Nx.Random.shuffle(key, Nx.iota({2 * points_per_spiral}))
xs = xs[perm]
ys = ys[perm]
{Nx.shape(xs), Nx.shape(ys)}
Plot it — you can see why this is hard:
alias VegaLite, as: Vl
Vl.new(title: "Two spirals", width: 560, height: 560)
|> Vl.data_from_values(%{
x: Nx.to_flat_list(xs[[.., 0]]),
y: Nx.to_flat_list(xs[[.., 1]]),
class: Enum.map(Nx.to_flat_list(ys), &to_string/1)
})
|> Vl.mark(:circle, size: 40)
|> Vl.encode_field(:x, "x", type: :quantitative)
|> Vl.encode_field(:y, "y", type: :quantitative)
|> Vl.encode_field(:color, "class", type: :nominal)
Section 2 — A network that cannot learn it (on purpose)
Two dense layers with no activation between them is mathematically just one linear map — width without activation buys nothing; depth with nonlinearity buys composition. Watching the linear twin stall while the MLP climbs is the clearest 10-minute lesson in why “deep” learning is deep. Watch it plateau:
linear_model =
Axon.input("coords", shape: {nil, 2})
|> Axon.dense(8)
|> Axon.dense(1, activation: :sigmoid)
train_data =
xs
|> Nx.to_batched(64, leftover: :discard)
|> Stream.zip(Nx.to_batched(ys, 64, leftover: :discard))
linear_state =
linear_model
|> Axon.Loop.trainer(:binary_cross_entropy, Polaris.Optimizers.adam(learning_rate: 3.0e-3))
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(train_data, %{}, epochs: 30, compiler: EXLA)
Accuracy stuck around ~50%: the model draws one straight line through the spirals and gives up.
Section 3 — Depth + nonlinearity
Same optimizer, same data — the only change is activations and depth:
mlp_model =
Axon.input("coords", shape: {nil, 2})
|> Axon.dense(64, activation: :relu)
|> Axon.dense(64, activation: :relu)
|> Axon.dense(64, activation: :relu)
|> Axon.dense(1, activation: :sigmoid)
mlp_state =
mlp_model
|> Axon.Loop.trainer(:binary_cross_entropy, Polaris.Optimizers.adam(learning_rate: 3.0e-3))
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(train_data, %{}, epochs: 60, compiler: EXLA)
Section 4 — Visualize the decision boundary
The boundary is the model. Accuracy is one number; the decision-boundary heatmap is the model’s shape. Predict a dense grid of points through the trained network and paint the plane — you see the sigmoid fold the space around each spiral arm. When a classifier misbehaves in production, reproduce this plot on a 2-D slice of the feature space before touching the training loop. This is the single most instructive visualization for small classifiers:
{n, range} = {80, 2.2}
grid_axis = Nx.linspace(-range, range, n: n)
grid =
for gy <- Nx.to_flat_list(grid_axis), gx <- Nx.to_flat_list(grid_axis) do
[gx, gy]
end
|> Nx.tensor()
scores =
Axon.predict(mlp_model, mlp_state, grid)
|> Nx.reshape({n, n})
Build meshes for the plot axes and render the plane under the data:
gx_mesh = Nx.tile(Nx.reshape(grid_axis, {1, n}), [n, 1])
gy_mesh = Nx.tile(Nx.reshape(grid_axis, {n, 1}), [1, n])
Vl.new(title: "Decision boundary", width: 640, height: 640)
|> Vl.data_from_values(%{
bx: Nx.to_flat_list(gx_mesh),
by: Nx.to_flat_list(gy_mesh),
score: Nx.to_flat_list(scores)
})
|> Vl.layers([
Vl.new()
|> Vl.mark(:rect)
|> Vl.encode_field(:x, "bx", type: :quantitative)
|> Vl.encode_field(:y, "by", type: :quantitative)
|> Vl.encode_field(:color, "score", type: :quantitative)
|> Vl.encode(:opacity, value: 0.45),
Vl.new()
|> Vl.mark(:circle, size: 30)
|> Vl.data_from_values(%{
px: Nx.to_flat_list(xs[[.., 0]]),
py: Nx.to_flat_list(xs[[.., 1]]),
pclass: Enum.map(Nx.to_flat_list(ys), &to_string/1)
})
|> Vl.encode_field(:x, "px", type: :quantitative)
|> Vl.encode_field(:y, "py", type: :quantitative)
|> Vl.encode_field(:color, "pclass", type: :nominal)
])
Section 5 — Sanity check on held-out points
Never trust a pretty picture alone — evaluate on points the trainer never saw:
{test_x, _} =
Nx.Random.uniform(Nx.Random.fold_in(key, 9), -range, range, shape: {500, 2})
test_pred =
Axon.predict(mlp_model, mlp_state, test_x)
|> Nx.greater(0.5)
|> Nx.squeeze(axes: [-1])
# Ground truth via nearest neighbor: label of the closest spiral point.
dists =
test_x
|> Nx.new_axis(1)
|> Nx.subtract(Nx.new_axis(xs, 0))
|> Nx.pow(2)
|> Nx.sum(axes: [-1])
test_truth =
ys[Nx.argmin(dists, axis: 1)]
|> Nx.squeeze(axes: [-1])
acc =
test_pred
|> Nx.equal(test_truth)
|> Nx.mean()
|> Nx.to_number()
"Held-out agreement with nearest spiral point: #{Float.round(acc * 100, 1)}%"
Checkpoint
- Why does the linear model’s loss stop improving while the MLP’s keeps dropping on the same data and optimizer?
Nx.Random.key/1is threaded explicitly andfold_in/2derives sub-keys. What failure mode does this design prevent?- The held-out check uses nearest-neighbor labels from the synthetic distribution instead of a test split. When is that legitimate?
Answers
- The linear model has zero representational gap left — its best achievable loss on non-separable data is bounded, so gradient descent converges to that plateau. The MLP’s loss surface keeps offering directions downhill.
- Accidentally reusing an RNG stream — the bug class of hidden global seeds. Functional keys make every experiment reproducible and parallelizable without shared state.
- When the synthetic process is the ground truth: points between the noisy arms have no “real” answer, so agreement with the generating distribution is the only meaningful check.
Where to next
- Exercise: drop the hidden layers to one
dense(8, activation: :relu)— how much capacity does the spiral actually need? Find the minimum capacity that still separates the spirals. - Exercise: swap
:relufor:tanhand compare convergence speed and boundary smoothness. - Exercise: add
Axon.dropout(rate: 0.1)after each hidden layer. Does the boundary get smoother? - Exercise: replace the sigmoid output with logits +
Axon.Losses.binary_cross_entropy(from_logits: true)— the more production-idiomatic setup. - Exercise: retrain the linear model with polynomial features you engineer by hand (x², y², x·y) and see how far feature engineering gets you — then decide when feature engineering beats depth.
Lab 4 — CNN on Fashion-MNIST: Garments at 28×28
Chapter 19 introduced convolutions; Chapter 21 served the result. This lab sits between them and fills the operational gap: a three-way data split, early stopping on validation loss, and a confusion matrix that turns one accuracy number into a story about which garments look like which at 28×28. All-new examples: instead of digits or pets, we classify 10 categories of clothing, add a validation split with early stopping, and read the confusion matrix to see which garments the network confuses.
From Erlang you know:
Nx.to_batched/2returns a lazy Stream — the training loop never holds the dataset twice in memory, the same discipline as streaming a file through a fold rather than loading it into a list.
What You’ll Build
- Fashion-MNIST end-to-end — 60,000 grayscale images of clothing in
10 classes, loaded via
Scidata.FashionMNIST, kept as{n, 28, 28, 1}for the channel axis convolutions require. - A compact CNN — two conv/pool blocks into a dense head with
dropout, summarized with
IO.inspect/1. - Disciplined training — train/validation/test split, early stop with patience 3, and a single final evaluation on the untouched test set.
Mix.install([
{:axon, "~> 0.8"},
{:nx, "~> 0.13"},
{:exla, "~> 0.13"},
{:polaris, "~> 0.1"},
{:scidata, "~> 0.1.11"},
{:scholar, "~> 0.4"},
{:kino, "~> 0.14"}
])
Section 1 — Data
Fashion-MNIST ships in the same raw-binary format as MNIST: 60,000 grayscale 28×28 images, 10 classes.
Nx.global_default_backend(EXLA.Backend)
{images, labels} = Scidata.FashionMNIST.download()
{image_data, image_type, _shape} = images
{label_data, label_type, label_shape} = labels
images =
image_data
|> Nx.from_binary(image_type)
|> Nx.divide(255)
|> Nx.reshape({60_000, 28, 28, 1}) # keep the channel axis for conv layers
labels =
label_data
|> Nx.from_binary(label_type)
|> Nx.reshape(label_shape)
labels =
labels
|> Nx.new_axis(-1)
|> Nx.equal(Nx.iota({1, 10})) # one-hot {60000, 10}
classes = [
"t-shirt", "trouser", "pullover", "dress", "coat",
"sandal", "shirt", "sneaker", "bag", "ankle boot"
]
{Nx.shape(images), Nx.shape(labels)}
Render a few samples as heatmaps — Nx.to_heatmap gives you a quick
Kino-ready image with zero extra dependencies:
render = fn idx ->
img = images[idx][[.., .., 0]]
label = labels[idx] |> Nx.argmax() |> Nx.to_number()
Kino.Layout.grid(
[Nx.to_heatmap(img), Kino.Markdown.new("**#{Enum.at(classes, label)}**")],
boxed: true
)
end
Enum.map([0, 1, 2, 3, 4], render)
|> Kino.Layout.grid(columns: 5)
Section 2 — Split & batch: train / validation / test
Three-way split — three sets, three jobs:
| Set | Who sees it | What it decides |
|---|---|---|
| Train | gradient descent | parameter updates |
| Validation | early stopping | when to stop, hyperparameters |
| Test | you, once | the number you report |
The validation set steers training (Axon.Loop.validate/3 +
Axon.Loop.early_stop/3); the test set is touched exactly once, after
training is frozen. Merging them back is how teams ship models that were
never actually evaluated. The validation set drives early stopping; the
test set is touched exactly once at the end:
train_images = images[0..49_999//1]
train_labels = labels[0..49_999//1]
val_images = images[50_000..54_999//1]
val_labels = labels[50_000..54_999//1]
test_images = images[55_000..-1//1]
test_labels = labels[55_000..-1//1]
batch_size = 128
batch = fn xs, ys ->
# leftover: :discard — the default (:repeat) pads the final batch by
# repeating rows, which would leak junk samples into training.
xs
|> Nx.to_batched(batch_size, leftover: :discard)
|> Stream.zip(Nx.to_batched(ys, batch_size, leftover: :discard))
end
train_data = batch.(train_images, train_labels)
val_data = batch.(val_images, val_labels)
test_data = batch.(test_images, test_labels)
Section 3 — A compact CNN
Two conv/pool blocks, then a dense head with dropout. Padding :same
keeps spatial sizes predictable:
model =
Axon.input("pixels", shape: {nil, 28, 28, 1})
|> Axon.conv(32, kernel_size: {3, 3}, activation: :relu, padding: :same)
|> Axon.max_pool(kernel_size: {2, 2}, strides: [2, 2])
|> Axon.conv(64, kernel_size: {3, 3}, activation: :relu, padding: :same)
|> Axon.max_pool(kernel_size: {2, 2}, strides: [2, 2])
|> Axon.flatten()
|> Axon.dense(128, activation: :relu)
|> Axon.dropout(rate: 0.3)
|> Axon.dense(10, activation: :softmax)
# Compact summary — Axon.Display.as_table/2 is broken in Axon 0.8.1
# for conv graphs, so use the model inspect instead.
IO.inspect(model, label: "conv model")
Section 4 — Train with early stopping
Stop when validation loss stops improving — patience 3 epochs. Early stopping is a supervisor for epochs: three consecutive epochs without validation improvement and the loop halts. It is the same philosophy as a restart budget in a supervisor — bounded resources, explicit policy, no infinite retry:
trained_state =
model
|> Axon.Loop.trainer(:categorical_cross_entropy, Polaris.Optimizers.adam(learning_rate: 1.0e-3))
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.validate(model, val_data)
|> Axon.Loop.early_stop("validation_loss", mode: :min, patience: 3)
|> Axon.Loop.run(train_data, %{}, epochs: 12, compiler: EXLA)
Section 5 — Evaluate once on the test set
model
|> Axon.Loop.evaluator()
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(test_data, trained_state, compiler: EXLA)
Section 6 — Read the confusion matrix
Overall accuracy hides the interesting story. Which garments get mixed up?
test_preds =
Axon.predict(model, trained_state, test_images)
|> Nx.argmax(axis: -1)
test_truth =
test_labels
|> Nx.argmax(axis: -1)
cm =
Scholar.Metrics.Classification.confusion_matrix(test_truth, test_preds, num_classes: 10)
cm_rows =
cm
|> Nx.to_batched(1)
|> Enum.with_index(fn row, actual ->
vals = Nx.to_flat_list(row)
%{"actual" => Enum.at(classes, actual)}
|> Map.merge(
classes
|> Enum.with_index()
|> Map.new(fn {name, j} -> {name, Enum.at(vals, j)} end)
)
end)
Kino.DataTable.new(cm_rows, name: "Confusion matrix (rows = actual)")
Shirts dominate the off-diagonal: t-shirts, pullovers, coats, and shirts share a silhouette at 28×28. Sandals and ankle boots, with their distinct shapes, are nearly always right. Overall accuracy hides that asymmetry; per-class reading tells you which data to collect next, not just that something is wrong.
Checkpoint
- Why reshape to
{60_000, 28, 28, 1}instead of flattening to 784 immediately? - Your validation loss is still dropping at epoch 12 but the loop is set to 12 epochs with patience 3. What happens, and how do you get the extra training safely?
- Dropout is active during training and disabled at inference. Which Axon mechanism makes that switch, and what would go wrong without it?
Answers
- Convolutions operate on spatial structure; flattening discards the 2-D neighborhood relationships that kernels exploit.
- The loop stops at 12 — patience never extends a fixed epoch budget. Raise the epoch cap and let early stopping, not your guess, pick the stopping point.
- The
:modeflag (:trainvs:inference) threaded into every layer viaAxon.build/ the loop. Without it, dropout noise corrupts deterministic predictions.
Where to next
- Exercise: add
Axon.batch_norm()after each conv and retrain — does the early-epoch accuracy curve get steeper? - Exercise: convert to
:channels_firstlayout ({nil, 1, 28, 28}) and passchannels: :firstto conv/pool layers; measure the speed difference on your machine. - Exercise: log per-class accuracy with
Scholar.Metrics.Classification.recalland rank the classes by how much more data each one needs.
Lab 5 — Character-Level LSTM: A Tiny Text Generator
Everything before this lab classified. This lab generates: a small LSTM that reads a public-domain book one character at a time and then writes plausible continuations. It is the smallest possible tour of sequence modeling — the same machinery that, scaled up, powers the transformers of Chapter 28. All-new examples: we train a small LSTM to model a public-domain book, one character at a time, then sample new text with a temperature knob. This lab replaces vocabulary-of-words classification with sequence modeling over characters.
From Erlang you know: the sliding-window dataset is just
Enum.chunk_every/4with a stride — list processing you have written a hundred times, pointed at characters instead of log lines.
What You’ll Build
- A character vocabulary — no tokenizer library; the set of distinct
characters,
id 0reserved for padding. - A windowed dataset — every 64-character window predicts the character that follows, with overlapping windows (stride 8) to multiply the data.
- The LSTM — embedding → LSTM(128) → last time-step → dense over the vocabulary, trained with categorical cross-entropy.
- Temperature-controlled sampling — Gumbel-max sampling entirely in Nx, with the temperature knob demonstrated at 0.5 and 1.2.
Mix.install([
{:axon, "~> 0.8"},
{:nx, "~> 0.13"},
{:exla, "~> 0.13"},
{:polaris, "~> 0.1"},
{:req, "~> 0.7"},
{:kino, "~> 0.14"}
])
Section 1 — Fetch a small corpus
A single public-domain text keeps the download small and training fast. (Any text works — swap in your own file to see the model mimic it.)
Nx.global_default_backend(EXLA.Backend)
%Req.Response{status: 200, body: raw_text} =
Req.get!("https://www.gutenberg.org/cache/epub/11/pg11.txt")
corpus =
raw_text
|> String.graphemes()
|> Enum.take(120_000)
|> Enum.join()
String.length(corpus)
Section 2 — Character vocabulary
A char-level model needs no tokenizer library: the vocabulary is the set
of distinct characters. Reserve 0 for padding.
chars =
corpus
|> String.graphemes()
|> Enum.uniq()
|> Enum.sort()
char_to_id = chars |> Enum.with_index(1) |> Map.new()
id_to_char = chars |> Enum.with_index(1) |> Map.new(fn {c, i} -> {i, c} end)
vocab_size = length(chars) + 1 # +1 for the padding id 0
"#{vocab_size} distinct characters"
Section 3 — Build fixed-length training windows
Every window of seq_len characters predicts the character that follows
it. One book becomes tens of thousands of overlapping supervised
examples: the model never sees the “document” — only shifted frames of
it, which is exactly how next-token prediction frames language.
Overlapping windows multiply the amount of data:
seq_len = 64
stride = 8
ids = corpus |> String.graphemes() |> Enum.map(&Map.fetch!(char_to_id, &1))
windows =
ids
|> Enum.chunk_every(seq_len + 1, stride, :discard)
|> Enum.map(fn window ->
{input, [target]} = Enum.split(window, seq_len)
{input, target}
end)
num_windows = length(windows)
"#{num_windows} training windows"
Batch them:
batch_size = 64
{input_batches, target_batches} =
windows
|> Enum.shuffle()
|> Enum.chunk_every(batch_size, batch_size, :discard)
|> Enum.map(fn batch_windows ->
inputs = batch_windows |> Enum.map(&elem(&1, 0)) |> Nx.tensor()
targets = batch_windows |> Enum.map(&elem(&1, 1)) |> Nx.tensor()
onehot_targets =
targets
|> Nx.new_axis(-1)
|> Nx.equal(Nx.iota({1, vocab_size}))
{inputs, onehot_targets}
end)
|> Enum.unzip()
train_data = Stream.zip(input_batches, target_batches)
{Nx.shape(hd(input_batches)), Nx.shape(hd(target_batches))}
(Inputs stay as integer ids for the embedding layer; only the targets are one-hot encoded for the loss.)
Section 4 — The LSTM model
Embedding → LSTM → take the last time-step → dense over the vocabulary.
Axon.lstm/3 returns {sequence, state}; the sequence is
{batch, seq_len, features} and the final position carries the summary
the dense head consumes. This indexing pattern — slice the last step of
the middle axis — recurs in every sequence model you will read:
model =
Axon.input("chars", shape: {nil, seq_len})
|> Axon.embedding(vocab_size, 96)
|> Axon.lstm(128, unroll: :static)
|> then(fn {seq, _state} -> seq end)
|> Axon.nx(fn s -> s[[.., -1]] end)
|> Axon.dense(vocab_size)
# Compact summary — Axon.Display.as_table/2 is broken in Axon 0.8.1
# for LSTM graphs, so use the model inspect instead.
IO.inspect(model, label: "char-lstm model")
Section 5 — Train
trained_state =
model
|> Axon.Loop.trainer(
# the dense head emits raw logits — the loss must know, or log(prob)
# goes negative and the loss becomes NaN mid-training
&Axon.Losses.categorical_cross_entropy(&1, &2, from_logits: true, reduction: :mean),
Polaris.Optimizers.adam(learning_rate: 2.0e-3)
)
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(train_data, %{}, epochs: 15, compiler: EXLA)
Per-character accuracy will look modest — language modeling is hard — but the relative quality of samples is what matters.
Section 6 — Sample text with temperature
Temperature reshapes the distribution: near 0 the model repeats its most confident choice (safe, boring); near 1.5 it takes risks (fun, gibberish). Dividing logits by a temperature before adding Gumbel noise reshapes the sampling distribution, so the knob is demonstrated at 0.5 and 1.2 below. Sampling uses the Gumbel-max trick, so the whole draw stays inside Nx — no per-character round-trip to host-side randomness:
defmodule Sample do
import Nx.Defn
# Gumbel-max trick: adding Gumbel noise to logits and taking argmax is
# equivalent to sampling from softmax(logits / temp) — all inside Nx.
# The key is threaded out: reusing one key would add the *same* noise
# vector every step and lock the sampler into a repeating bias.
defn gumbel_sample(logits, temp, key) do
{gumbel, key2} = Nx.Random.gumbel(key, shape: Nx.shape(logits))
{Nx.argmax(logits / temp + gumbel), key2}
end
end
generate = fn prompt, num_chars, temp ->
seed_ids =
prompt
|> String.graphemes()
|> Enum.map(&Map.get(char_to_id, &1, char_to_id[" "]))
init_ids =
if length(seed_ids) >= seq_len do
Enum.take(seed_ids, -seq_len)
else
List.duplicate(char_to_id[" "], seq_len - length(seed_ids)) ++ seed_ids
end
init_window = init_ids |> Nx.tensor() |> Nx.reshape({1, seq_len})
{_win, _key, generated} =
for _ <- 1..num_chars, reduce: {init_window, Nx.Random.key(42), []} do
{win, k, acc} ->
logits = Axon.predict(model, trained_state, win)
{next_id, k2} = Sample.gumbel_sample(logits, Nx.tensor(temp), k)
next_char = Map.fetch!(id_to_char, Nx.to_number(next_id))
next_window =
win
|> Nx.to_flat_list()
|> tl()
|> Kernel.++([Nx.to_number(next_id)])
|> Nx.tensor()
|> Nx.reshape({1, seq_len})
{next_window, k2, [next_char | acc]}
end
prompt <> Enum.join(Enum.reverse(generated))
end
with_temp_05 = generate.("Alice was beginning to", 300, 0.5)
with_temp_12 = generate.("Alice was beginning to", 300, 1.2)
Kino.Layout.grid([
Kino.Markdown.new("**temperature 0.5**"),
Kino.Markdown.new(with_temp_05),
Kino.Markdown.new("**temperature 1.2**"),
Kino.Markdown.new(with_temp_12)
])
Checkpoint
- Why keep inputs as integer ids but one-hot encode only the targets?
- What does
unroll: :statictrade for the LSTM, and why does a fixedseq_lenmake it possible? - Per-character training accuracy is modest. Why is sample quality, not accuracy, the honest metric for a generator?
Answers
- The embedding layer consumes ids and looks up dense vectors; one-hot targets feed the cross-entropy directly. One-hot inputs would waste the embedding’s purpose and blow memory.
- Static unroll compiles the recurrence as a fixed graph — faster, and only possible because every window has the same length; variable lengths would need dynamic unroll or padding tricks.
- Cross-entropy measures confidence calibration, not coherence. A model can have middling per-character likelihoods and still produce fluent text — read the samples.
Where to next
- Exercise: switch the corpus to your own text file; compare how few characters the vocabulary needs before the model overfits, and watch how few epochs a tiny vocabulary needs before samples sound like it.
- Exercise: replace the dense head + sampling with a
:softmaxoutput and:categorical_cross_entropyon softmax probabilities — notice you must setfrom_logits: falseand why logit outputs are preferred. - Exercise: stack a second
Axon.lstm(128)layer and compare sample quality per epoch against the training-time cost. - Exercise: seed the sampler with several prompts and log outputs to a
Kino.Frameas the model trains, to watch the generator improve live.
Lab 6 — Bumblebee: Semantic Search for a Support Desk
The closing lab is the one closest to shipping: a semantic search engine over a support-desk FAQ, built from three pre-trained Bumblebee models — an embedding model for retrieval, a cross-encoder for re-ranking, and a named-entity recognizer for routing. No training at all. This is the “inference-first” pattern Chapter 20 promised, now end-to-end. All-new examples: we build a small FAQ search engine over support-desk snippets — embed with a sentence-transformer, retrieve by cosine similarity, re-score the shortlist with a cross-encoder, and extract entities from tickets with NER. No training, no Python.
From Erlang you know: each Bumblebee serving is a supervised process you call with
Nx.Serving.run/2— the GenServer boundary is already there. Wrapping three servings in one façade module is just writing a clean API over three workers.
What You’ll Build
- Embedding retrieval — E5 sentence embeddings with L2
normalization, so
Nx.dotis cosine similarity. - Cross-encoder re-ranking — retrieve wide with the fast bi-encoder, re-score the top few with the accurate-but-O(n) cross-encoder.
- NER routing — pull
PER/ORG/LOCentities out of free-form tickets for automatic queue assignment.
Mix.install([
{:bumblebee, "~> 0.7"},
{:axon, "~> 0.8"},
{:nx, "~> 0.13"},
{:exla, "~> 0.13"},
{:kino, "~> 0.14"}
])
Nx.global_default_backend(EXLA.Backend)
Nx.Defn.default_options(compiler: EXLA)
Section 1 — The corpus
A tiny knowledge base. In production this would come from Ecto; here it is inline so the lab is self-contained:
faqs = [
"Customers can reset their password from the login page using the Forgot password link.",
"Refunds are processed to the original payment method within 5 to 7 business days.",
"Team administrators can invite or remove members from the workspace settings page.",
"Our API rate limit is 60 requests per minute for every authentication token.",
"Subscriptions can be cancelled any time; access continues until the end of the billing period.",
"Two-factor authentication can be enabled under Security settings using any TOTP app.",
"Exported reports are available in CSV and PDF formats from the Reports page.",
"Invoices are emailed automatically on the first day of each billing cycle.",
"Mobile push notifications can be muted per project from the notification preferences.",
"Data residency options for EU customers can be requested through your account manager."
]
query = "how do I stop paying but keep access until the month ends?"
Section 2 — Text embeddings
E5 models expect the literal prefixes query: and passage: — bake
them into a small wrapper. These asymmetric prefixes mark each side’s
role: dropping them silently degrades ranking, a reminder that
pre-trained models carry contracts, and reading the model card is part of
integration, not documentation theater. L2 normalization makes plain dot
products equivalent to cosine similarity:
{:ok, embed_model} = Bumblebee.load_model({:hf, "intfloat/e5-small-v2"})
{:ok, embed_tokenizer} = Bumblebee.load_tokenizer({:hf, "intfloat/e5-small-v2"})
embedding_serving =
Bumblebee.Text.text_embedding(embed_model, embed_tokenizer,
# mean-pooling works on the rank-3 hidden states; the default
# :pooled_state attribute is already rank 2 (one vector per input)
output_attribute: :hidden_state,
output_pool: :mean_pooling,
embedding_processor: :l2_norm,
compile: [batch_size: 16, sequence_length: 96],
defn_options: [compiler: EXLA]
)
embed = fn prefix, text ->
Nx.Serving.run(embedding_serving, prefix <> text).embedding
end
A serving called with a list returns a list of results; called with
one string it returns one result. The case below handles both shapes so
the lab survives library evolution:
doc_matrix =
faqs
|> Enum.map(&"passage: " <> &1)
|> then(&Nx.Serving.run(embedding_serving, &1))
|> case do
%{embedding: single} -> [single]
list when is_list(list) -> Enum.map(list, & &1.embedding)
end
|> Nx.stack()
{Nx.shape(doc_matrix), Nx.type(doc_matrix)}
Section 3 — Retrieve by similarity
Every vector is unit length, so Nx.dot is the cosine similarity:
query_vec = embed.("query: ", query)
# {10, 384} dot {384} contracts the last axis -> one similarity score per doc
scores = Nx.dot(doc_matrix, query_vec)
top5 =
scores
|> Nx.to_flat_list()
|> Enum.with_index()
|> Enum.sort_by(fn {score, _} -> -score end)
|> Enum.take(5)
|> Enum.map(fn {score, i} ->
%{score: Float.round(score, 4), faq: Enum.at(faqs, i)}
end)
Kino.DataTable.new(top5, name: "Embedding retrieval")
Section 4 — Re-rank the shortlist with a cross-encoder
Two-stage retrieval: cheap filter, expensive judge.
query ──▶ bi-encoder ──▶ top-5 (dot products) ──▶ cross-encoder ──▶ best answer
(embed once, over ALL docs) (reads query + doc
compare vs jointly, per pair)
every doc)
The bi-encoder compares every document independently — fast, and the doc matrix can be embedded offline; a cross-encoder reads query and document together in one transformer pass, which is far more accurate but must run per candidate. Production RAG systems are almost universally this two-stage shape; this lab builds it in ~30 lines. Retrieve wide, re-rank narrow:
{:ok, rerank_model} = Bumblebee.load_model({:hf, "cross-encoder/ms-marco-MiniLM-L-6-v2"})
{:ok, rerank_tokenizer} = Bumblebee.load_tokenizer({:hf, "cross-encoder/ms-marco-MiniLM-L-6-v2"})
rerank_serving =
Bumblebee.Text.cross_encoding(rerank_model, rerank_tokenizer,
compile: [batch_size: 5, sequence_length: 128],
defn_options: [compiler: EXLA]
)
top5
|> Enum.map(& &1.faq)
|> Enum.map(&{query, &1})
|> then(&Nx.Serving.run(rerank_serving, &1))
|> case do
%{score: single} -> [%{score: single}]
list -> list
end
|> Enum.zip(top5)
|> Enum.map(fn {%{score: s}, hit} -> %{rerank_score: Float.round(s, 4), faq: hit.faq} end)
|> Enum.sort_by(& &1.rerank_score, :desc)
|> Kino.DataTable.new(name: "Cross-encoder re-ranking")
Section 5 — Extract entities from a support ticket
Named entity recognition rounds out the pipeline — pull people, orgs, and locations out of free-form tickets so they can be routed automatically:
{:ok, ner_model} = Bumblebee.load_model({:hf, "dslim/bert-base-NER"})
{:ok, ner_tokenizer} = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-cased"})
ner_serving =
Bumblebee.Text.token_classification(ner_model, ner_tokenizer,
aggregation: :same,
compile: [batch_size: 1, sequence_length: 128],
defn_options: [compiler: EXLA]
)
ticket =
"Priya Nair from Acme Logistics in Rotterdam says invoice #4471 was " <>
"emailed twice and the refund has not arrived yet."
Nx.Serving.run(ner_serving, ticket)
Section 6 — One function, three models
The whole desk in a single façade — an Erlang dev will recognize this as
a thin module over three supervised servings. Nx.Serving.run/2 hides a
GenServer that owns the compiled program and device memory. In production
(Chapter 21) you register servings under names in a supervision tree and
call Nx.Serving.batched_run/2; the façade below is the single place
those names would live:
defmodule SupportDesk do
@faqs [
"Customers can reset their password from the login page using the Forgot password link.",
"Refunds are processed to the original payment method within 5 to 7 business days.",
"Team administrators can invite or remove members from the workspace settings page.",
"Our API rate limit is 60 requests per minute for every authentication token.",
"Subscriptions can be cancelled any time; access continues until the end of the billing period.",
"Two-factor authentication can be enabled under Security settings using any TOTP app.",
"Exported reports are available in CSV and PDF formats from the Reports page.",
"Invoices are emailed automatically on the first day of each billing cycle.",
"Mobile push notifications can be muted per project from the notification preferences.",
"Data residency options for EU customers can be requested through your account manager."
]
def answer(query, embedding_serving, rerank_serving) do
docs =
@faqs
|> Enum.map(&"passage: " <> &1)
|> then(&Nx.Serving.run(embedding_serving, &1))
|> Enum.map(& &1.embedding)
matrix = Nx.stack(docs)
%{embedding: q} = Nx.Serving.run(embedding_serving, "query: " <> query)
top3 =
matrix
|> Nx.dot(q)
|> Nx.to_flat_list()
|> Enum.with_index()
|> Enum.sort_by(fn {s, _} -> -s end)
|> Enum.take(3)
top3
|> Enum.map(fn {_, i} -> {query, Enum.at(@faqs, i)} end)
|> then(&Nx.Serving.run(rerank_serving, &1))
|> Enum.map(& &1.score)
|> Enum.zip(Enum.map(top3, fn {_, i} -> Enum.at(@faqs, i) end))
|> Enum.sort_by(fn {s, _} -> -s end)
|> then(fn [{_s, best} | _] -> best end)
end
end
SupportDesk.answer("where do I add a new teammate?", embedding_serving, rerank_serving)
Checkpoint
- Why does L2 normalization make dot products equal to cosine similarity?
- You must re-rank 500 candidates with the cross-encoder instead of 5. What breaks first — correctness or latency — and what is the fix?
- Where would you persist
doc_matrixso a release restart skips re-embedding 10,000 documents?
Answers
- For unit vectors,
dot(a, b) = |a||b|cos(θ) = cos(θ)— the norms are 1, so the product of magnitudes vanishes. - Latency: the cross-encoder runs one transformer pass per pair, so 500 pairs is 100× the compute. Fix: keep the shortlist narrow, batch the pairs, or move the re-ranker to a bigger device — never widen it casually.
- Anywhere durable — ETS is lost on restart.
Nx.to_binary/1plus the type/shape metadata (the Ch 17 persistence triple) into a file or object store; reload withNx.from_binary/2.
Where to next
- Exercise: register both servings under names in a
Kino.start_childsupervision setup and switch the façade toNx.Serving.batched_run/2; measure throughput with 1 vs 8 concurrent callers. - Exercise: swap
intfloat/e5-small-v2for a larger embedding model and observe how the ranking of the trickier queries changes. - Exercise: persist
doc_matrixwithNx.to_binary/1+ type/shape metadata (the pattern from Ch 17) so restarts skip re-embedding. - Exercise: add a fallback — when the best re-rank score is below a threshold, answer “no confident match” instead of the top hit.
- Exercise: add a second stage that routes tickets by NER labels —
ORGtickets go to the billing queue,PERto a human reviewer — and log the routing decisions to decide which entities deserve their own queues.