Elixir GenServer
GenServer ("generic server") is the most important building block of OTP. It is a process with a state and a receive loop, like the hand-written Counter in the Processes lesson, but with all the hard parts done for you: synchronous calls with replies and timeouts, asynchronous casts, naming, supervision, debugging and clean shutdown. You only write callbacks that say what to do with each message.
The two halves of a GenServer module
A GenServer module usually has:
- a client API: ordinary functions (
start_link/1,push/2,pop/1) that run in the caller's process and send messages; - server callbacks:
init/1,handle_call/3,handle_cast/2,handle_info/2, which run inside the GenServer process.
defmodule Stack do
use GenServer
# Client API
def start_link(items), do: GenServer.start_link(__MODULE__, items)
def push(pid, item), do: GenServer.cast(pid, {:push, item})
def pop(pid), do: GenServer.call(pid, :pop)
def size(pid), do: GenServer.call(pid, :size)
# Server callbacks
@impl true
def init(items), do: {:ok, items}
@impl true
def handle_call(:pop, _from, [top | rest]), do: {:reply, {:ok, top}, rest}
def handle_call(:pop, _from, []), do: {:reply, :empty, []}
def handle_call(:size, _from, items), do: {:reply, length(items), items}
@impl true
def handle_cast({:push, item}, items), do: {:noreply, [item | items]}
end
{:ok, stack} = Stack.start_link([:c])
Stack.push(stack, :b)
Stack.push(stack, :a)
IO.inspect(Stack.size(stack))
IO.inspect(Stack.pop(stack))
IO.inspect(Stack.pop(stack))
IO.inspect(Stack.pop(stack))
IO.inspect(Stack.pop(stack))3
{:ok, :a}
{:ok, :b}
{:ok, :c}
:empty
@impl true marks a function as a callback implementation; the compiler then warns if you misspell a callback name.
call, cast and info
| Message type | Sent with | Handled by | Returns to caller |
|---|---|---|---|
| synchronous request | GenServer.call(server, msg) |
handle_call(msg, from, state) |
the reply (waits, 5 s timeout by default) |
| asynchronous request | GenServer.cast(server, msg) |
handle_cast(msg, state) |
:ok immediately |
| any other message | send/2, timers, monitors |
handle_info(msg, state) |
nothing |
The callbacks return instruction tuples:
| Return value | Meaning |
|---|---|
{:ok, state} (from init) |
start with this state |
{:reply, reply, new_state} |
answer the caller and continue |
{:noreply, new_state} |
continue without answering |
{:stop, reason, new_state} |
stop the server |
Use call when the caller needs an answer or must know that the work is done (it also provides back-pressure: a slow server slows its callers down instead of piling up messages). Use cast for fire-and-forget notifications.
A named server with handle_info
Giving the server a name: registers it, so callers can use the module name instead of a PID. handle_info/2 receives plain messages, for example from Process.send_after/3, the standard way to schedule periodic work:
defmodule RateLimiter do
use GenServer
@limit 3
def start_link(_), do: GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
def allow?(user), do: GenServer.call(__MODULE__, {:allow?, user})
def reset, do: send(__MODULE__, :reset)
@impl true
def init(counts), do: {:ok, counts}
@impl true
def handle_call({:allow?, user}, _from, counts) do
used = Map.get(counts, user, 0)
if used < @limit do
{:reply, true, Map.put(counts, user, used + 1)}
else
{:reply, false, counts}
end
end
@impl true
def handle_info(:reset, _counts) do
IO.puts("(window reset)")
{:noreply, %{}}
end
end
{:ok, _} = RateLimiter.start_link([])
answers = for _ <- 1..4, do: RateLimiter.allow?("maya")
IO.inspect(answers)
IO.inspect(RateLimiter.allow?("tom"))
RateLimiter.reset()
IO.inspect(RateLimiter.allow?("maya"))[true, true, true, false]
true
(window reset)
true
In production the reset would be scheduled in init/1 with Process.send_after(self(), :reset, 60_000) and rescheduled in handle_info/2. Here it is sent by hand to keep the output deterministic. The :reset message is guaranteed to be processed before the next allow? call because both come from the same process.
Timeouts and errors in calls
GenServer.call/3 takes a timeout (default 5000 ms). If the server doesn't reply in time, the caller exits. You can catch that exit:
defmodule Slow do
use GenServer
def start_link, do: GenServer.start_link(__MODULE__, :ok)
@impl true
def init(:ok), do: {:ok, nil}
@impl true
def handle_call(:work, _from, state) do
Process.sleep(200)
{:reply, :done, state}
end
end
{:ok, pid} = Slow.start_link()
IO.inspect(GenServer.call(pid, :work, 1_000))
try do
GenServer.call(pid, :work, 50)
catch
:exit, {:timeout, _} -> IO.puts("call timed out after 50 ms")
end:done
call timed out after 50 ms
catch :exit, reason catches exits (signals), which are different from raised exceptions; the Errors lesson explains the difference.
Tips
- Keep callbacks fast. Long work inside a GenServer blocks everyone waiting on it; hand it to a
Taskif needed. - A GenServer serialises access to its state. That is a feature (no race conditions) and a possible bottleneck (one process). For read-heavy shared data, consider ETS.
- Don't create a GenServer just to organise code. Modules and functions do that. Use a process when you need state, concurrency or fault isolation.
Test yourself
Which callback handles GenServer.cast(pid, :tick)?
handle_call/3handle_cast/2handle_info/2init/1
What must handle_call/3 return to answer the caller and keep running?
{:ok, reply}{:reply, reply, new_state}{:noreply, state}reply
In which process do the client API functions like Stack.push/2 run?
- In the GenServer process
- In the caller's process
- In a new process per call
- In the supervisor