Skip to content
Elixir

GenServer

Build stateful server processes with GenServer behaviour.

By EZ4Code Team
genserverotpstate

Code

defmodule Counter do
  use GenServer

  # Client API
  def start_link(initial \ 0), do: GenServer.start_link(__MODULE__, initial, name: __MODULE__)
  def increment, do: GenServer.cast(__MODULE__, :inc)
  def value, do: GenServer.call(__MODULE__, :value)

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

  @impl true
  def handle_cast(:inc, state), do: {:noreply, state + 1}

  @impl true
  def handle_call(:value, _from, state), do: {:reply, state, state}
end

# Usage
{:ok, _} = Counter.start_link(0)
Counter.increment()
Counter.increment()
IO.puts(Counter.value())  # 2

Explanation

GenServer is the OTP behaviour for stateful server processes. Client API (synchronous call / asynchronous cast) sends messages to a server loop that handles init/handle_call/handle_cast. The state is threaded through each callback. This pattern abstracts the receive loop, provides supervision, and integrates with the broader OTP tree.

More Elixir Snippets