jonnifyelixir
F3 · The Elixir Language / F3.08 · otp

F3 · OTP · module 8

OTP: GenServer & supervisors

OTP is the framework the BEAM grew up on — tested patterns for the actor model. A GenServer wraps the spawn, receive, and loop you wrote by hand into a behaviour with callbacks. A Supervisor watches a set of processes and restarts them when they crash. Together they turn isolated processes into a system that recovers on its own.

The portal's hand-written tally becomes a GenServer; talking to it splits into synchronous call and asynchronous cast; and a supervisor keeps it and its siblings alive. This module builds OTP from three pieces — the server, the client API, and the supervision tree.

Let it crash · the restart loop

SUPERVISOR :one_for_one watches GENSERVER running state = 7 LIFECYCLE 1 · running 2 · crash 3 · restart → state = 0

[ running · state = 7 ]
The child holds its own state and answers messages.

An OTP system in three pieces

A running OTP system is a small tree: a supervisor on top, one or more GenServers holding state, and clients sending them messages. Select each piece to see its role and the functions that define it.

The piece · select one

SUPERVISOR Supervisor supervises · restarts GENSERVER GenServer holds state CLIENT Client call / cast ROLE init/1 · handle_call/3

The three pieces are layered, not separate: a GenServer is a process with a behaviour, a supervisor is a process that starts and watches others, and the client is any process holding a PID.

Three deep dives

Three pages, in order: the GenServer behaviour and its callbacks; the synchronous and asynchronous client calls; then supervisors and the restart strategies that make the system fault-tolerant.

F3.08.1
The GenServer behaviour
use GenServer hides the loop; you fill in init/1, handle_call/3, and handle_cast/2, and the state threads between them.
F3.08.2
Synchronous call, asynchronous cast
call blocks until the server replies; cast returns :ok at once. One routes to handle_call, the other to handle_cast.
F3.08.3
Supervisors & restart strategies
A supervisor restarts crashed children by strategy — :one_for_one, :one_for_all, :rest_for_one. This is "let it crash".

F3.07 · a hand-written loop

A process held state by tail-calling a receive loop, alone and unsupervised.

F3.08 · GenServer & a supervisor

The loop becomes callbacks, the messages become call and cast, and a supervisor restarts the server when it dies.

Start with the GenServer behaviour, then call and cast, then supervisors and restart strategies. Next module: F3.09 — The process playground, an interactive lab where you spawn processes and watch the supervision tree restart them live.

References

Primary sources for this lesson, and where it connects in the course.

Sources

Related in this course