OTP Behaviours and gen_server

Article · 5:00

Why nobody writes a receive loop in production, the four callbacks, and which of call, cast and info each message should take.

The counter in phase two works. In production you would not write it.

A hand-rolled receive loop has to re-implement, correctly, a list of things that are the same in every server: synchronous calls with a timeout and a unique reference so replies cannot be confused, handling the case where the caller dies mid-call, system messages for debugging and tracing, code upgrade, clean shutdown, and the supervisor protocol. That is several hundred lines of subtle code, and everybody gets some of it wrong.

A behaviour is OTP's answer: a generic module implements all of that once, and you supply only the parts specific to your server through a set of callbacks. -behaviour(gen_server) declares the contract, and the compiler warns if a required callback is missing.

The four callbacks.

init/1 runs in the new process and returns {ok, State}. Whatever it returns becomes the state, and it is the only place that is guaranteed to have run before any request arrives. Keep it fast - the supervisor is blocked until it returns.

handle_call/3 is synchronous. The caller blocks until you reply, which also gives you back-pressure: a client cannot outrun the server. It receives From, which is the caller's reference, and normally returns {reply, Answer, NewState}. The default timeout is five seconds.

handle_cast/2 is asynchronous: fire and forget, no reply, no back-pressure. Right for genuine notifications; wrong whenever the caller needs to know it worked, and wrong when the sender can produce work faster than the server can consume it, because the mailbox then grows without limit.

handle_info/2 gets everything that arrives not through call or cast - timeouts, {'DOWN', ...} monitor messages, TCP data, anything another process sends directly. Always implement a catch-all clause here. A missing handle_info clause crashes the server, and the message that did it is usually something harmless.

terminate/2 runs on a clean shutdown, and is not guaranteed - it is skipped on a brutal_kill or when the process is not trapping exits. Do not put anything essential in it.

Choosing between call and cast is the decision that matters most, and the rule is simple: use call unless you have a specific reason not to. The back-pressure is a feature.

-module(bank_account).
-behaviour(gen_server).

%% The public interface. Callers use these, never gen_server directly -
%% that is the point of the module: the protocol stays inside it.
-export([start_link/1, deposit/2, withdraw/2, balance/1, stop/1]).

%% The callbacks OTP calls.
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
         terminate/2, code_change/3]).

-record(state, {owner, balance = 0, history = []}).

%% ---------------- The interface ----------------
start_link(Owner) ->
    gen_server:start_link(?MODULE, Owner, []).
    %% start_link, not start: it LINKS to the caller, which is what
    %% lets a supervisor notice the crash. Add {local, Name} as the
    %% first argument to register it.

deposit(Pid, Amount)  -> gen_server:call(Pid, {deposit, Amount}).
withdraw(Pid, Amount) -> gen_server:call(Pid, {withdraw, Amount}).
balance(Pid)          -> gen_server:call(Pid, balance).
stop(Pid)             -> gen_server:stop(Pid).

%% ---------------- init: runs IN the new process ----------------
init(Owner) ->
    %% The supervisor is blocked until this returns, so keep it fast.
    %% Slow work belongs in a handle_continue or a cast to self().
    {ok, #state{owner = Owner}}.
    %% {stop, Reason} here aborts the start.

%% ---------------- handle_call: synchronous, with back-pressure ------
handle_call({deposit, Amount}, _From, State) when Amount > 0 ->
    New = State#state.balance + Amount,
    {reply, {ok, New}, State#state{balance = New}};

handle_call({withdraw, Amount}, _From, State)
        when Amount > 0, Amount =< State#state.balance ->
    New = State#state.balance - Amount,
    {reply, {ok, New}, State#state{balance = New}};

handle_call({withdraw, _}, _From, State) ->
    %% An EXPECTED failure, so it is a reply rather than a crash. The
    %% account is still valid; the request was not.
    {reply, {error, insufficient_funds}, State};

handle_call(balance, _From, State) ->
    {reply, State#state.balance, State};

handle_call(Request, From, State) ->
    %% Unexpected: log it and carry on rather than crashing the server
    %% because somebody sent something odd.
    logger:warning("unexpected call ~p from ~p", [Request, From]),
    {reply, {error, unknown_request}, State}.

%% ---------------- handle_cast: fire and forget ----------------
handle_cast({audit, Entry}, State) ->
    {noreply, State#state{history = [Entry | State#state.history]}};
    %% Prepend, never append - appending to a list is O(n).

handle_cast(_Msg, State) ->
    {noreply, State}.

%% ---------------- handle_info: everything else ----------------
handle_info({'DOWN', _Ref, process, Pid, Reason}, State) ->
    logger:info("watched ~p went down: ~p", [Pid, Reason]),
    {noreply, State};

handle_info(timeout, State) ->
    {noreply, State};

handle_info(Info, State) ->
    %% THE CATCH-ALL. Leave it out and a stray message crashes the
    %% server with a function_clause, which is the most common way a
    %% first gen_server dies in production.
    logger:debug("unexpected info ~p", [Info]),
    {noreply, State}.

%% ---------------- terminate: not guaranteed ----------------
terminate(_Reason, _State) ->
    %% Skipped on brutal_kill, and when not trapping exits. Nothing
    %% essential goes here.
    ok.

code_change(_OldVsn, State, _Extra) -> {ok, State}.

%% ---------------- call or cast? ----------------
%%
%%   call   synchronous. The caller waits, so it knows the result AND
%%          cannot outrun the server. Default timeout 5000 ms; pass
%%          your own, or infinity if you really mean it.
%%
%%   cast   asynchronous. No reply, no back-pressure, no way to know it
%%          arrived. If the sender can produce work faster than the
%%          server consumes it, the mailbox grows without limit and
%%          the node eventually dies.
%%
%% Use call unless you have a specific reason not to.

Discussion

No questions on this topic yet. Sign in to ask the first one.