Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Fault Tolerance and OTP

gen_server: the OTP generic server

Learn the OTP gen_server behaviour: init, handle_call, handle_cast, handle_info, terminate, start_link, timeouts and a complete key-value server example.

In process loops and state you wrote a server by hand: spawn, loop, receive, reply with a reference, stop. Every server repeats the same plumbing. OTP (the Open Telecom Platform, a library shipped with Erlang) captures that plumbing in behaviours. The most important one is gen_server, a generic server: OTP supplies the loop, timeouts, tracing and system messages; you supply a callback module with the application-specific parts.

The structure

A callback module declares -behaviour(gen_server) and exports callbacks. The two you must always write are init/1 and handle_call/3.

ERLANG
-module(kv).
-behaviour(gen_server).

%% API
-export([start_link/0, put/2, get/1, stop/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]).

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

put(Key, Value) -> gen_server:cast(?MODULE, {put, Key, Value}).
get(Key)        -> gen_server:call(?MODULE, {get, Key}).
stop()          -> gen_server:stop(?MODULE).

init([]) ->
    {ok, #{}}.

handle_call({get, Key}, _From, State) ->
    {reply, maps:find(Key, State), State};
handle_call(_Request, _From, State) ->
    {reply, {error, unknown_call}, State}.

handle_cast({put, Key, Value}, State) ->
    {noreply, State#{Key => Value}};
handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.
ERLANG
1> kv:start_link().
{ok,<0.140.0>}
2> kv:put(color, blue).
ok
3> kv:get(color).
{ok,blue}
4> kv:get(size).
error

(maps:find/2 returns {ok, Value} or error. The pid in your shell will differ.)

The callbacks

Callback Triggered by Typical return
init(Args) start_link {ok, State}, {ok, State, Timeout}, {stop, Reason}, ignore
handle_call(Request, From, State) gen_server:call {reply, Reply, NewState}, {noreply, NewState}, {stop, Reason, Reply, NewState}
handle_cast(Msg, State) gen_server:cast {noreply, NewState}, {stop, Reason, NewState}
handle_info(Info, State) any other message (timeouts, 'DOWN', 'EXIT', raw !) {noreply, NewState}
terminate(Reason, State) server is stopping ignored; clean-up only

call versus cast

  • gen_server:call(Server, Request) is synchronous: it sends, waits for the reply and returns it. It has a default 5-second timeout; on expiry the caller crashes with {timeout, ...}. Use call(Server, Req, Timeout) to change it, but think twice about infinity.
  • gen_server:cast(Server, Msg) is asynchronous and always returns ok, even if the server does not exist. Use it when you do not need confirmation.

Prefer call by default: it gives natural back-pressure, because a client cannot send faster than the server answers. Overusing cast can flood the mailbox.

Starting and stopping

start_link/4 takes the name registration ({local, Name}, {global, Name} or omitted), the callback module, the init argument and options. It links the new server to the caller, which is what lets a supervisor manage it. init/1 runs inside the new process, and start_link does not return until init does, so keep init fast. Slow set-up should be postponed with {ok, State, {continue, setup}} and handled in handle_continue/2.

gen_server:stop/1 shuts it down cleanly and calls terminate/2.

Pitfalls

  • Calling yourself. A handle_call that does gen_server:call(self(), ...) deadlocks and times out.
  • Long work in a callback. The server handles one message at a time; a slow handle_call blocks everyone. Spawn a worker and answer later with gen_server:reply(From, Reply) after returning {noreply, State}.
  • Unknown messages. Raw messages arrive at handle_info/2. Log or ignore them; otherwise the default crash is a surprise.
  • terminate is not guaranteed. It runs on stop and on orderly {stop, ...}, and on crashes only if the server traps exits. Never rely on it for important persistence.

What OTP does for you

The receive loop Written once, tested for years
Request and reply References and timeouts built in
System messages Tracing, state inspection, upgrades
Supervision Starts and restarts it for you

You write only the callbacks.

1 / 2

Run it: a gen_server stand-in

OTP is not available here, so this JavaScript stand-in is not the real gen_server. It shows how the behaviour separates generic machinery (queue, loop, call with timeout) from your callbacks. The kv callbacks mirror the Erlang module above.

JS Stand-in: a tiny gen_server

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Replying later

Returning {noreply, State} from handle_call leaves the caller waiting; you can reply later from any process with gen_server:reply(From, Reply). That lets the server stay responsive while a helper computes:

ERLANG
handle_call({slow, N}, From, State) ->
    spawn_link(fun() ->
        gen_server:reply(From, slow_work(N))
    end),
    {noreply, State}.

Choosing between a gen_server and a plain process

Use gen_server for any long-lived process that holds state, serves requests or must be supervised. Use plain processes (or proc_lib, Task-like helpers) for short-lived, single-purpose workers. Other behaviours follow the same shape: gen_statem for state machines, gen_event for event handlers, supervisor for restarting children, which comes next.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which callbacks does a gen_server callback module have to implement at minimum?

    init/1 sets the state and handle_call/3 serves requests; the others are optional in modern OTP.
  2. 2. What is the default timeout of gen_server:call/2?

    Calls time out after 5000 ms, and the caller exits with a timeout error.
  3. 3. Which function handles a plain Pid ! hello sent to a gen_server?

    Messages that are not call or cast requests arrive at handle_info/2.
  4. 4. Why is cast not always the best choice?

    Casts are asynchronous, so a fast client can flood the server's mailbox.

Summary

  • gen_server implements the generic loop, you write the callbacks (init, handle_call, handle_cast, handle_info, terminate).
  • call is synchronous with a timeout; cast is asynchronous and unconfirmed.
  • Keep init fast and avoid slow work in callbacks; reply later with gen_server:reply/2.
  • start_link links the server to its parent, the foundation for supervision.

Next: Supervisors