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.