OTP design principles
The behaviours of this chapter are one idea repeated: a module declares that it follows a contract, the runtime calls the functions of the contract, and the module fills them in. OTP design principles are that idea carried through a whole system: every process is a callback module of a behaviour, every tree has a supervisor, every application names its dependencies, and every release can be started, stopped and upgraded. The GenServer, supervisors, applications and releases lessons build the parts; this one states the rules that hold them together.
A behaviour is a contract
A behaviour module declares the callbacks with the -callback attribute, and the compiler turns those declarations into a behaviour_info/1 function. A module that adds -behaviour(job) promises to export every function of that list, and the compiler checks the promise. The program below declares its own behaviour with one callback, reads the list back, and runs the check a plugin loader runs before it calls a plugin:
job.erl
-module(job). -export([main/0, callbacks/0, check/1]). -callback run(term()) -> ok | {error, term()}. main() -> io:format("job callbacks: ~p~n", [callbacks()]), io:format("job check: ~p~n", [check(?MODULE)]), io:format("application: ~w~n", [lists:sort(application:behaviour_info(callbacks))]). callbacks() -> ?MODULE:behaviour_info(callbacks). check(Module) -> {module, Module} = code:ensure_loaded(Module), Required = Module:behaviour_info(callbacks), Missing = [Callback || {Name, Arity} = Callback <- Required, not erlang:function_exported(Module, Name, Arity)], case Missing of [] -> ok; _ -> {missing, Missing} end.
erlc job.erl
erl -noshell -eval 'job:main(), halt().'
job callbacks: [{run,1}] job check: {missing,[{run,1}]} application: [{config_change,3},{prep_stop,1},{start,2},{start_phase,3},{stop,1}]
The module declares run/1 and does not export it, so its own check finds the callback missing: that is what a plugin loader reports as {missing, [{run,1}]} instead of crashing into an undef halfway through a call. erlang:function_exported/3 answers only for a module that is loaded, which is why the check loads it first, and the last line reads the callback list of a behaviour OTP itself ships.
When the contract is broken
The compiler reports a missing callback as a warning, and a project that compiles with -Werror treats that warning as a failed build. The file below declares gen_server and exports only init/1. The block is a fragment: the -module line is left out so that the two attributes it reports on are the whole subject, and the line numbers are those of the saved file, where the module line is line one. The command is the plain compiler of a reader, so the warning does not stop it:
half_server.erl
-behaviour(gen_server). -export([init/1]). init(_Args) -> {ok, 0}.
erlc half_server.erl
half_server.erl:2:2: Warning: undefined callback function handle_call/3 (behaviour 'gen_server') half_server.erl:2:2: Warning: undefined callback function handle_cast/2 (behaviour 'gen_server')
The warning names the line of -behaviour, not the missing function, and a real build with -Werror stops there. The mistake a beginner makes is to read that warning as harmless because the module compiles: it does compile, and it fails the first time the runtime calls a callback that is not there. The callbacks of gen_server are init/1, handle_call/3, handle_cast/2, handle_info/2 and terminate/2, plus the optional handle_continue/2 and code_change/3. The contract is also the shape of what a callback returns: a handle_call/3 that answers a bare ok instead of {reply, Value, State} stops the server with bad_return_value at the first call.
The checklist
These are the rules the lessons of this chapter followed one at a time. A module that breaks one of them still compiles, which is why the list is worth keeping:
- One process per responsibility, and every process is a callback module of a behaviour: gen_server for state, gen_statem for phases, gen_event for a signal with many observers.
- Every process is started by a supervisor, and every start function links. A tree has a budget per level, and a level that gives up takes its branch down, not the node.
- The state of a process is not the state of the system. Anything that must survive a restart lives in an ETS table, a file or a database, and the process reads it back in init/1.
- An application names its dependencies in applications and starts its tree from start/2; an application that is not in the list is missing at boot, not at the first call.
- No work in a callback that can block without a timeout: a call, a socket read, a file, anything that waits. A blocked server blocks every caller behind it.
- A release is built and started, not a folder of beams on a code path. It holds the versions it was built with, a boot script and a configuration, and it can be upgraded with a relup.
- The build treats warnings as errors, Dialyzer and Elvis run in the loop, and a test suite runs the tree. The static checks lesson puts those three in one job.
A codebase that follows the list is one where a crash report names the process, the supervisor restarts the part that failed, and the release that is running is the one that was tested. That is what OTP design principles buy, and none of it needs a package from outside the Erlang distribution.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a behaviour module declare?
Answer
The callbacks another module must export
-callbackattributes becomebehaviour_info/1, and the declarations are the contract. -
What does the compiler do when a module declares
-behaviour(gen_server)and misses a callback?Answer
It warns, and with
-Werrorthe build failsA missing callback is a warning that a project with warnings as errors turns into a failed build.
-
What does
Module:behaviour_info(callbacks)answer?Answer
The list of
{Name, Arity}pairs the behaviour requiresThe attribute list is compiled into that function, and a loader can read it before it calls anything.
-
Why does a start function have to link the child it starts?
Answer
The supervisor only learns of a death through the link
An unlinked child dies alone, and the supervisor keeps a dead pid in its bookkeeping.
-
Why must state that survives a restart live outside the process?
Answer
A restart starts a new process with its initial state
The supervisor restores the shape of the tree, and
init/1starts from the initial state again. -
What does a blocking call in a callback do to a server?
Answer
It blocks every request behind it
One process handles one message at a time, so a slow callback delays the whole mailbox.
-
What does this module print?
-module(q1). -export([main/0]). main() -> io:format("~p~n", [lists:sort(application:behaviour_info(callbacks))]).Answer
[{config_change,3},{prep_stop,1},{start,2},{start_phase,3},{stop,1}]The application behaviour declares five callbacks, and
behaviour_info/1answers them sorted. -
What does this module print?
-module(q2). -export([main/0]). main() -> Loaded = code:ensure_loaded(lists), Exported = erlang:function_exported(lists, reverse, 1), io:format("~p~n", [{Loaded, Exported}]).Answer
{{module,lists},true}The module is loaded first, and a loaded module that defines the callback exports it.
-
What does this module print?
-module(q3). -export([main/0]). -callback ping() -> pong. main() -> io:format("~p~n", [?MODULE:behaviour_info(callbacks)]).Answer
[{ping,0}]A callback is a name and an arity, and a behaviour with one callback answers one pair.
-
What does this module print?
-module(q4). -behaviour(gen_server). -export([main/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]). main() -> {ok, Pid} = gen_server:start(?MODULE, 5, []), io:format("~p~n", [gen_server:call(Pid, state)]). init(State) -> {ok, State}. handle_call(state, _From, State) -> {reply, State, State}. handle_cast(_Message, State) -> {noreply, State}. handle_info(_Message, State) -> {noreply, State}. terminate(_Reason, _State) -> ok.Answer
5The start function passes five to
init/1, and the call replies with the state the loop keeps.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev