Skip to content

Erlang OTP — gen_server Behaviours

DodaTech Updated 2026-06-29 1 min read

In this tutorial, you will learn about Erlang OTP. We cover key concepts, practical examples, and best practices to help you master this topic.

gen_server is the most commonly used OTP behaviour. It provides a standardized way to create stateful server processes with call, cast, and info message handling.

gen_server Template

-module(counter).
-behaviour(gen_server).

%% API
-export([start_link/1, increment/0, value/0]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, terminate/2]).

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

increment() ->
    gen_server:call(?MODULE, increment).

value() ->
    gen_server:call(?MODULE, value).

init(Initial) ->
    {ok, Initial}.

handle_call(increment, _From, State) ->
    {reply, State + 1, State + 1};
handle_call(value, _From, State) ->
    {reply, State, State}.

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

terminate(_Reason, _State) ->
    ok.

%% Usage:
%% counter:start_link(0),
%% counter:increment(),  %% => 1
%% counter:value().      %% => 1

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro