F3.08 · part 2 of 3
Synchronous call, asynchronous cast
Two ways to message a GenServer. GenServer.call sends a request and
blocks until the server replies, returning the value — a round trip. GenServer.cast
sends a request and returns :ok at once, without waiting — fire and forget.
call routes to handle_call, cast to
handle_cast.
Choose based on whether the caller needs an answer. A read wants call;
a fire-and-forget update wants cast. Select each and watch where it routes and what the
client gets back.
Where each one routes
call makes the caller wait for the server's reply; cast lets
it move on immediately. The cost of call is the wait: if the server does not reply
within the timeout, the caller exits. Select each and follow both lanes.
The client request · select one
A cast is faster for the caller but tells you nothing — not even
that the server is alive. A call confirms the work and returns a value, at the price of
waiting. The choice is about whether you need the answer, not about speed alone.
A clean client API
Callers should not write GenServer.call and raw message tags themselves. Wrap them
in named functions on the module, so the public surface reads as Tally.get/1 and
Tally.inc/1 and the call-versus-cast choice stays an implementation detail.
defmodule Portal.Tally do # ... use GenServer, init, handle_call, handle_cast ... def get(pid), do: GenServer.call(pid, :get) # sync: returns the count def inc(pid), do: GenServer.cast(pid, :inc) # async: returns :ok end Tally.inc(tally) # => :ok (fire and forget) Tally.inc(tally) # => :ok Tally.get(tally) # => 2 (waits for the reply)
The idea
Ask and wait for an answer, or tell and move on without one.
In Elixir
call → handle_call → a reply; cast → handle_cast → :ok.
Next: supervisors and restart strategies — what keeps the server alive when it crashes.
References
Primary sources for this lesson, and where it connects in the course.
Sources
GenServer— Elixir documentation — the stateful server behaviour,callandcast.- Mix & OTP: GenServer — Elixir documentation — building one step by step.
Supervisor— Elixir documentation — fault tolerance and restarts.