GenServer
In Erlang a process that keeps state is a loop: receive a request, change the state, send a reply, loop again. Written by hand, that loop repeats the same protocol code in every server of the system, and the one place that gets it wrong is the one nobody tests. A gen_server is that loop written once by OTP: the runtime owns the receive loop, the reply, the links and the crash reports, and your module fills in the callbacks. The processes lesson shows the hand written loop; this lesson replaces it with the behaviour.
A server you write
The module below is a counter with a name. start_link/0 asks gen_server to start a process, register it under the atom counter, call init/1 with the number zero and link the new process to the caller. init/1 answers the initial state in an ok tuple, and the runtime keeps that state for the life of the process:
counter.erl
-module(counter). -behaviour(gen_server). -export([start_link/0, increment/0, value/0, stop/0, main/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, 0, []). increment() -> gen_server:cast(?MODULE, increment). value() -> gen_server:call(?MODULE, value). stop() -> gen_server:stop(?MODULE). main() -> {ok, _Pid} = start_link(), ok = increment(), ok = increment(), io:format("value: ~p~n", [value()]), ok = stop(), io:format("registered: ~p~n", [whereis(?MODULE)]). init(State) -> {ok, State}. handle_call(value, _From, State) -> {reply, State, State}. handle_cast(increment, State) -> {noreply, State + 1}. handle_info(_Msg, State) -> {noreply, State}. terminate(_Reason, _State) -> io:format("counter stopped~n"), ok.
erlc counter.erl
erl -noshell -eval 'counter:main(), halt().'
value: 2 counter stopped registered: undefined
Three things in that run are the whole behaviour. The two increments changed the state before the call read it, so the answer is two. stop/0 ran terminate/2, which printed its line. And the registered name is gone after the stop, because a name lives only as long as the process that owns it.
Calls and casts
A call is synchronous. gen_server:call/2 sends the request with a
reference, waits for the reply and returns it, so the caller blocks for as long as the
server takes. The request reaches handle_call/3, which gets the
request, a {Pid, Reference} tuple that identifies the caller, and
the state, and answers {reply, Value, NewState}: one value for
the caller, one state for the loop.
A cast is asynchronous. gen_server:cast/2 puts the message in the
mailbox and returns ok at once, and
handle_cast/2 answers {noreply, NewState}
with no value for anybody. That is the right shape for an increment or a log line, where
nobody waits for an answer, and the wrong shape for a read: a caller that needs the
state uses a call.
Both callbacks should match the requests they know and nothing else. An unknown request
then crashes the server with function_clause, which the
supervisor sees and reports, instead of being quietly accepted by a catch-all clause that
hides a broken client.
Plain messages
Everything that is not a call or a cast arrives at handle_info/2: a message sent with the exclamation mark, a timeout of erlang:send_after/3, and the monitor messages of the monitors lesson. The next module counts the messages it receives that way:
pinger.erl
-module(pinger). -behaviour(gen_server). -export([start_link/0, ping/1, seen/0, main/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2]). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). ping(Message) -> ?MODULE ! Message, ok. seen() -> gen_server:call(?MODULE, seen). main() -> {ok, _Pid} = start_link(), ok = ping(ping), ok = ping({late, 1}), io:format("info messages: ~p~n", [seen()]). init(_Args) -> {ok, 0}. handle_call(seen, _From, Count) -> {reply, Count, Count}. handle_cast(_Msg, Count) -> {noreply, Count}. handle_info(_Message, Count) -> {noreply, Count + 1}.
erlc pinger.erl
erl -noshell -eval 'pinger:main(), halt().'
info messages: 2
The count is two even though the call arrived third, because messages from one process to another keep their order: both plain messages were handled before the call. A server that ignores a message it does not know answers {noreply, State} and keeps the state; it should not crash just because somebody sent it an extra term.
The server that is not there
The first mistake a reader makes is the call before the start. A call needs a live process behind the name, and when there is none, gen_server raises the noproc exit in the caller. It is an exit, not an {error, ...} tuple, so a caller that wants to survive it catches the class:
no_server.erl
-module(no_server). -export([main/0]). main() -> Result = try gen_server:call(counter, value) of N -> {ok, N} catch exit:Reason -> {exit, Reason} end, io:format("~p~n", [Result]).
erlc no_server.erl
erl -noshell -eval 'no_server:main(), halt().'
{exit,{noproc,{gen_server,call,[counter,value]}}}
The term names the missing process and the call that wanted it, which is exactly what a log line needs. The supervisors lesson removes the cause: the server is a child of a supervisor, so it is running before any caller that the supervisor serves.
A call that waits too long
A call waits five seconds by default and then exits with timeout. The server is not killed by that exit: it is still working, and its reply arrives later, to a caller that no longer waits. A client that cannot afford five seconds passes its own timeout as the third argument, and a server that is slow by design is worth a longer one:
slow.erl
-module(slow). -behaviour(gen_server). -export([start_link/0, work/0, main/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2]). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, 0, []). work() -> gen_server:call(?MODULE, work, 50). main() -> {ok, _Pid} = start_link(), Result = try work() of Reply -> {ok, Reply} catch exit:Reason -> {exit, Reason} end, io:format("~p~n", [Result]), ok = gen_server:stop(?MODULE). init(State) -> {ok, State}. handle_call(work, _From, State) -> timer:sleep(200), {reply, done, State}. handle_cast(_Message, State) -> {noreply, State}. handle_info(_Message, State) -> {noreply, State}.
erlc slow.erl
erl -noshell -eval 'slow:main(), halt().'
{exit,{timeout,{gen_server,call,[slow,work,50]}}}
Fifty milliseconds is shorter than the two hundred the handler sleeps, so the caller gave up first. The fix is not to raise the timeout until the failure disappears: a handler that sleeps blocks every other request behind it, and the applications lesson shows what a supervisor does with a server that stops answering. Either the work is fast enough to be a call, or it belongs in another process with a reply of its own.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a GenServer?
Answer
A behaviour whose loop the runtime owns
You fill in the callbacks;
gen_serverruns the receive loop and the protocol around them. -
What does
init/1answer?Answer
{ok, State}The initial state comes back inside an ok tuple, and the loop starts with it.
-
What does
{local, ?MODULE}instart_link/0do?Answer
Registers the server under the module name
The name lets the API functions send to the atom
counterwithout keeping a pid. -
What does
handle_call/3answer for a successful request?Answer
{reply, Value, NewState}One value goes back to the waiting caller and one state goes back to the loop.
-
Does
counter:increment()wait for the state to change?Answer
No, a cast is asynchronous
gen_server:cast/2sends and returns at once; the state changes when the server handles the message. -
What does this module print?
-module(q1). -behaviour(gen_server). -export([main/0, init/1, handle_call/3, handle_cast/2, handle_info/2]). main() -> {ok, Pid} = gen_server:start(?MODULE, 0, []), gen_server:cast(Pid, add), gen_server:cast(Pid, add), io:format("~p~n", [gen_server:call(Pid, value)]). init(State) -> {ok, State}. handle_call(value, _From, State) -> {reply, State, State}. handle_cast(add, State) -> {noreply, State + 1}. handle_info(_Message, State) -> {noreply, State}.Answer
2Both casts are handled before the call, and each one adds one to the state.
-
What does this module print?
-module(q2). -behaviour(gen_server). -export([main/0, init/1, handle_call/3, handle_cast/2, handle_info/2]). main() -> {ok, Pid} = gen_server:start(?MODULE, 0, []), Pid ! ping, Pid ! ping, io:format("~p~n", [gen_server:call(Pid, seen)]). init(State) -> {ok, State}. handle_call(seen, _From, Count) -> {reply, Count, Count}. handle_cast(_Message, Count) -> {noreply, Count}. handle_info(_Message, Count) -> {noreply, Count + 1}.Answer
2Both plain messages reach
handle_info/2before the call, and each one adds one. -
What does this module print?
-module(q3). -behaviour(gen_server). -export([main/0, init/1, handle_call/3, handle_cast/2, handle_info/2]). main() -> {ok, Pid} = gen_server:start(?MODULE, 0, []), Result = try gen_server:call(Pid, slow, 10) of Answer -> Answer catch exit:{timeout, _Call} -> timeout end, io:format("~p~n", [Result]). init(State) -> {ok, State}. handle_call(slow, _From, State) -> timer:sleep(200), {reply, done, State}. handle_cast(_Message, State) -> {noreply, State}. handle_info(_Message, State) -> {noreply, State}.Answer
timeoutThe caller waits ten milliseconds and the handler sleeps two hundred, so the call exits with a timeout.
-
What does this module print?
-module(q4). -behaviour(gen_server). -export([main/0, init/1, handle_call/3, handle_cast/2, handle_info/2]). main() -> {ok, _Pid} = gen_server:start({local, q4_server}, ?MODULE, 0, []), ok = gen_server:stop(q4_server), io:format("~p~n", [whereis(q4_server)]). init(State) -> {ok, State}. handle_call(_Request, _From, State) -> {reply, ok, State}. handle_cast(_Message, State) -> {noreply, State}. handle_info(_Message, State) -> {noreply, State}.Answer
undefinedStopping the server removes the registered name, so
whereis/1answersundefined. -
Where does a plain message sent with
!arrive in a GenServer?Answer
handle_info/2Everything that is not a call or a cast is handled by
handle_info/2, timeouts and monitor messages included.
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