Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 48 ยท Concurrency and OTP

GenServer

Learn GenServer in Elixir: init, handle_call, handle_cast, handle_info, naming, timeouts and state design, with a JavaScript stand-in to experiment.

In the previous lesson you wrote a counter with a hand-made receive loop, a message protocol and reply references. That pattern is so common that Erlang/OTP turned it into a standard building block: the GenServer (generic server). You supply a module with a few callbacks that say how to start, what each message does and what the new state is. GenServer supplies the loop, the request/response plumbing, timeouts, name registration and the hooks supervisors need.

Elixir cannot run on this site, so the GenServer code below is read-only. The editors contain a small JavaScript GenServer-like runtime that behaves the same way for the basics. It is a teaching model, not OTP. If you have not yet seen raw processes and state loops, read those first.

The GenServer contract

init Build the starting state.
handle_call Synchronous request, reply expected.
handle_cast Asynchronous, no reply.
handle_info Any other message.

Each callback returns the next state.

1 / 2

A first GenServer

Here is a stack, written as a GenServer:

ELIXIR
defmodule Stack do
  use GenServer

  # Client API

  def start_link(initial \\ []) do
    GenServer.start_link(__MODULE__, initial, name: __MODULE__)
  end

  def push(item), do: GenServer.cast(__MODULE__, {:push, item})
  def pop, do: GenServer.call(__MODULE__, :pop)
  def size, do: GenServer.call(__MODULE__, :size)

  # Server callbacks

  @impl true
  def init(initial), do: {:ok, initial}

  @impl true
  def handle_call(:pop, _from, []), do: {:reply, :empty, []}
  def handle_call(:pop, _from, [head | tail]), do: {:reply, {:ok, head}, tail}
  def handle_call(:size, _from, stack), do: {:reply, length(stack), stack}

  @impl true
  def handle_cast({:push, item}, stack), do: {:noreply, [item | stack]}
end

And a session using it:

ELIXIR
{:ok, _pid} = Stack.start_link()
Stack.push(:a)
Stack.push(:b)
IO.inspect(Stack.pop())    # {:ok, :b}
IO.inspect(Stack.size())   # 1

The module has two halves in one file. The client API (push/1, pop/0, size/0) runs in the caller's process and hides the message format. The callbacks (init/1, handle_call/3, handle_cast/2) run in the server process. Putting both in one module keeps the protocol in a single place. Notice how the callbacks use multiple function clauses and pattern matching: pop on an empty stack is just another clause.

The callbacks in detail

init/1 receives the argument given to start_link and returns {:ok, state}. It runs before start_link returns, so keep it quick. If you need slow setup, return {:ok, state, {:continue, :load}} and implement handle_continue/2, which runs right after init without blocking the starter.

handle_call/3 handles GenServer.call/3. It receives the message, the caller (from) and the state, and usually returns {:reply, reply, new_state}. The caller waits for the reply, so calls are synchronous.

handle_cast/2 handles GenServer.cast/2, which returns :ok immediately whether or not the server is even alive. It returns {:noreply, new_state}. Use casts for "fire and forget" and calls whenever the caller needs a result or a guarantee that the work was done.

handle_info/2 receives every message that did not come from call or cast: raw send/2 messages, :DOWN messages from monitors, {:EXIT, ...} from trapped links, and timers.

ELIXIR
@impl true
def handle_info(:tick, state) do
  Process.send_after(self(), :tick, 1_000)   # schedule the next tick
  {:noreply, state + 1}
end

Process.send_after/3 sends a message to a process later, which makes periodic work easy: handle the tick, then schedule the next one.

You can also stop a server from a callback: {:stop, :normal, state} or {:stop, reason, reply, state} from a call. A GenServer that stops with a reason other than :normal (or :shutdown) is treated as a crash, and a supervisor may restart it depending on its restart setting (see the next lesson).

Always add @impl true before callbacks. The compiler then warns if a function does not match the behaviour's callbacks, which catches misspelled names such as handle_calls.

flowchart LR
    C["Caller process"] -- "GenServer.call(pid, :pop)" --> L["GenServer loop"]
    L --> H["handle_call(:pop, from, state)"]
    H -- "{:reply, reply, new_state}" --> L
    L -- "reply" --> C

A call goes through the loop, runs a callback and sends a reply.

Naming and finding a server

start_link returns {:ok, pid}. You can pass the pid around, but for a process that exists once per application you register a name: name: __MODULE__ registers a local atom, as in the stack above, so GenServer.call(Stack, :pop) works from anywhere on the node. Other options are {:global, term} (cluster-wide) and {:via, module, term} (for example with a Registry, covered in ETS, Registry and Application State).

Starting a second server with a name that is already taken returns {:error, {:already_started, pid}}.

Timeouts

GenServer.call(server, msg) waits up to 5000 ms. If no reply arrives, the caller exits with a timeout, even though the server may still be working. Pass a third argument for another limit: GenServer.call(Stack, :pop, 10_000) or :infinity. Keep in mind:

  • A timeout does not cancel the work in the server, and a late reply arrives as a stray message in the caller's mailbox.
  • A slow callback blocks every other caller, so move long work to a Task and reply later (using GenServer.reply/2 with {:noreply, state}).
  • An inactivity timeout is different: {:reply, answer, state, 30_000} makes the server send itself :timeout to handle_info/2 after 30 seconds of silence.

Designing the state

  • Keep the state small and plain: a map, struct or tuple. A struct documents its shape.
  • Let the callbacks be thin; put logic in pure functions that return the new data, and test them without any process.
  • A GenServer is a bottleneck by design, since it serves one message at a time. Do not use one just to organize code. Use a module of functions unless you need state over time, serialized access or a place to hold resources.
  • Never call your own client API from inside a callback: GenServer.call(self(), ...) deadlocks.

A JavaScript GenServer stand-in

This model has start with an init function, call and cast that dispatch to the callbacks, a name registry, and a callTimeout. The callbacks return objects that mimic the Elixir tuples. Everything runs on one JavaScript thread, so scheduling is not like the BEAM, and error handling is far simpler than OTP's.

JS A tiny GenServer runtime (JavaScript stand-in)

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

No output.

Both casts return immediately, but the calls come after them in the mailbox, so they see the pushes. That is the ordering guarantee between one sender and one receiver at work.

The second stand-in shows a call timeout. The caller gives up after a limit while the server keeps working, as in the real thing.

JS Call timeouts (JavaScript stand-in)

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

No output.

The third call is fast on its own but has to wait for the abandoned slow one, which shows why a timeout does not make a busy server less busy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which callback handles messages sent with plain send/2 to a GenServer?

    Anything that is not a call or a cast, including raw messages, monitor DOWN messages and timers, arrives in handle_info/2.
  2. 2. What is the default timeout of GenServer.call/2?

    The default is 5000 ms. When it expires, the calling process exits, although the server may still be working.
  3. 3. Which is the right choice when the caller needs to know the work was done?

    call is synchronous and returns the reply. cast returns :ok immediately without any guarantee that the work ran or even that the server exists.
  4. 4. Why does GenServer.call(self(), :msg) inside a callback hang until timeout?

    The server handles one message at a time. It cannot process the call it sent itself until the current callback returns, so it deadlocks.
  5. 5. What does the init/1 callback return on success?

    init returns {:ok, state}, optionally with a timeout or {:continue, term}.

Summary

  • A GenServer is a process with a standard loop; you write the callbacks and the client API.
  • init/1 builds state; handle_call/3 replies, handle_cast/2 does not, handle_info/2 handles everything else.
  • Register a name for a single shared server, and mind {:error, {:already_started, pid}}.
  • call times out after 5 seconds by default; the server keeps working when the caller gives up.
  • Keep state small, logic in pure functions, and callbacks quick. Never call yourself synchronously.
  • The JavaScript runtime is a stand-in that models the shape of OTP, not its behavior in detail.

Next up: Supervisors and Supervision Trees.