Skip to content

Elixir GenServer patterns

Claude Sonnet 4.6

ME
Explain Elixir GenServer patterns
AI
GenServer is an OTP behaviour for building stateful server processes. Here are the key patterns: **1. Basic GenServer** Use `start_link/1` and `init/1` to start and initialize state. Use `handle_call/3` for synchronous requests and `handle_cast/2` for async. **2. Registry Pattern** Register GenServers by name for easy lookup: `{:via, Registry, {MyRegistry, name}}` **3. Timeout handling** Return `{:reply, response, state, timeout}` to send a `:timeout` message after inactivity. Would you like to see code examples for any of these patterns?
ME
Yes, show me a Registry example
AI
Here's a complete Registry-based GenServer example: ```elixir defmodule MyApp.WorkerRegistry do use GenServer def start_link(name) do GenServer.start_link(__MODULE__, %{}, name: via(name)) end def get_state(name) do GenServer.call(via(name), :get_state) end defp via(name) do {:via, Registry, {MyApp.Registry, name}} end @impl true def init(state), do: {:ok, state} @impl true def handle_call(:get_state, _from, state) do {:reply, state, state} end end ``` Start the registry in your supervision tree and you can spawn named workers on demand!
Temperature: 0.7 Max tokens: 2048