💧 Elixir Beginner

What is GenServer in Elixir?

Answer

GenServer (Generic Server) is an OTP behavior for implementing stateful server processes. It abstracts the common patterns of process lifecycle, state management, and message handling. Define a GenServer: defmodule Counter do; use GenServer; def start_link(initial), do: GenServer.start_link(__MODULE__, initial); def init(state), do: {:ok, state}; def handle_call(:get, _from, state), do: {:reply, state, state}; def handle_cast(:increment, state), do: {:noreply, state + 1}; end. handle_call: synchronous request-response. handle_cast: asynchronous fire-and-forget. handle_info: handle arbitrary messages (e.g., timeouts, exits). Client API: GenServer.call(pid, :get), GenServer.cast(pid, :increment). GenServers are the workhorse of Elixir applications — used for caches, connection pools, background workers, state machines, and any stateful component that needs lifecycle management and fault tolerance.