Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 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, receive loops. Elixir calls spawn spawn, sends with send/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’s Supervisor/GenServer are thin wrappers over the same supervisor/gen_server modules.
  • Behaviours & distribution — callback contracts, -behaviour declarations, 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 / shapeContractExample
trailing ?returns a booleanMap.has_key?/2, your own verified?/1
trailing !raises on failure instead of returning a tupleMap.fetch!/2, File.read!/1
foo / foo! pairsame operation, tuple vs raise — caller picks by contextMap.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

SituationErlang instinctElixir instinct
Repeated boilerplatetolerate or extract higher-order fnconsume/write a macro or DSL
Helper returning yes/nois_valid(Term)valid?(term)
Expected failuremixed: tuple, throw, or crash{:error, reason}; ! twin for raise
Nested transformationsstaging variables, inside-outpipeline, top-to-bottom
Public API hygieneexports list is the contractdocs + 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
LayerFrom (Erlang)To (Elixir)Effort
Language.erl, records, -export.ex, structs, def/defpDays
Toolingrebar3, erlang.mkMix, Hex, ExUnit, ExDocDays
LibrariesOTP apps, jiffy, cowboyHex packages: Phoenix, Ecto, Nx…Weeks
Conventionsinfrastructure styleproduct/application styleOngoing

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 SkillElixir Ecosystem Application
GenServer / SupervisionPhoenix LiveView (stateful connections), Nerves device trees
Distribution / :rpcMulti-node Phoenix, clustered Nx serving, edge ↔ cloud
Message passingBroadway pipelines, GenStage flow, PubSub real-time
Fault isolationOban job retries, LiveView crash recovery, device watchdogs
ETS / MnesiaExplorer 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_call counter, 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_one instincts 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 termErlang viewElixir module / syntax
Atomhello:hello (true, false, nil are atoms)
Integer / Float1, 1.0Integer, 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
Portconnected external processPort module
Function objectfun M:f/1fn x -> x end, &Mod.fun/1
Referencemake_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 false nor nil
  • A value is falsy when it is either false or nil

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/not require the left operand to be a real boolean (raise BadBooleanError otherwise); when the left side is true/false they return the right operand untouched — semantically identical to Erlang’s andalso/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.

Failure-propagation primitives deserve one explicit pass, because the semantics are byte-for-byte Erlang’s while the surface syntax differs:

PrimitiveDirectionSignalElixir spelling
Linkbidirectionalan exit kills all linked processesspawn_link/1
Monitorunidirectional{:DOWN, ref, :process, pid, reason} msgProcess.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 using is_* predicates and &Mod.fun/1 captures 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:

  1. Which runtime do both languages compile to? (BEAM bytecode on the same VM)
  2. Name three OTP concepts that transfer without modification.
  3. Which four layers make up the actual learning curve?
  4. Why is “nicer Erlang” the wrong framing?
  5. What are Elixir’s two falsy values, and which operators respect them?
  6. Name three mindset shifts from §1.2 that are cultural rather than semantic.
Answers
  1. BEAM bytecode on the same VM.
  2. Processes and messages, supervision trees, links/monitors, the error kernel (let it crash), reductions and preemption, distribution, term ordering, per-process heaps.
  3. Language → Tooling → Libraries → Conventions (§1.3).
  4. Because it implies you must unlearn working instincts (single assignment, mutable-ish idioms) rather than just learn new syntax.
  5. false and nil. &&/|| respect them; and/or raise on them as the left operand.
  6. 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