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 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 GenServer is Erlang’s gen_server. There is no reimplementation — use GenServer wires your module to the same OTP behaviour module, and every Elixir callback has a one-to-one gen_server counterpart (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_spec generation.

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:

ConcernHand-rolled loopgen_server
request/responsehand-built {from, ref} tuplescall/2 with monitor + ref
caller timeoutyou write the after clausebuilt-in, default 5 s
dead-server detectionlink kills caller silently-wronglycaller gets a precise exit
unexpected messagessilently queued foreverrouted to handle_info/2
clean shutdownnone{:stop, …} + terminate/2
hot-code upgradenonecode_change/3
supervision handshakenonestandard child_spec/1
debug introspectionnone: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 GenServer generates child_spec/1 so the module can appear directly in a supervision tree (Ch 24). It also provides default callbacks you have not defined — which is why omitting handle_info/2 compiles 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 true on every callback — typos like handle_cal become compile errors instead of silent fallthroughs to defaults.

Callback return values are a small closed set. Learn them as shapes:

CallbackReturnsEffect
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 | :hibernatesynchronous
handle_cast(req, state){:noreply, state} · {:stop, reason, state} · variantsasynchronous
handle_info(msg, state)same shapes as handle_caststray/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:

SituationCaller 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 in timeout milliseconds, the server sends itself :timeout through handle_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} (or hibernate_after: ms in start_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} from gen_server callbacks. 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 diesterminate/2 runs?
callback returns {:stop, reason, …}yes
GenServer.stop/3 calledyes
exception raised inside a callbackyes — reason is {exception_struct, stacktrace}
exit(reason) called inside a callbackyes
parent orders shutdown, trappingyes — reason :shutdown
parent/external exit signal, not trappingno — 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_server invokes terminate/2 with 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 external exit(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/2 is 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, …) calling GenServer.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 across handle_continue, or go async via cast/messages.
  • Blocking callbacks. A 200 ms HTTP call inside handle_call freezes 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 :ets table 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_server counterpart
  • :gen_server reference — the protocol-level truth, including system messages
  • :sys module — tracing, statistics, suspend/resume used by debuggers and upgraders
  • Exercise idea: reproduce the deadlock — a server whose handle_call calls itself with GenServer.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-all handle_info; confirm the default swallows it silently

Checkpoint

  1. What exactly does GenServer.call/3 do before sending the request, and why?
  2. Your handle_call raises. What does the caller see, does terminate/2 run, and what happens to the queued messages?
  3. Why does the default handle_info dropping messages matter, and where do DOWN messages arrive if you monitor something inside a GenServer?
  4. A server must call a flaky third-party API taking ~10 s. Sketch the shape that keeps its mailbox healthy.
  5. When is terminate/2 guaranteed to run, and why is that guarantee weaker than it looks?
Answers
  1. 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.
  2. Caller exits with {crash_reason, {GenServer, :call, args}}; terminate/2 does run (modern gen_server calls it on failures too); queued messages die with the process — restart rebuilds from init/1.
  3. Because silent drops hide protocol bugs; DOWNs are ordinary messages so they arrive in handle_info/2 — another reason the catch-all clause exists.
  4. handle_call returns {:noreply, state} capturing from, spawns a supervised Task for the HTTP call, which completes with GenServer.reply(from, result); the server keeps draining meanwhile.
  5. 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