State in a process
A functional language has no variable that a function changes, so where does a counter live? The answer is a process with a loop that carries the value as an argument. Each message runs one step of the loop with a new argument, and the caller sees a value that changes between calls. This is the mutable cell of Elixir, and it is the idea behind Agent, GenServer and every server in OTP.
A loop with an argument
The loop is a private function that never returns while the process should live. It waits in receive, handles one message, and calls itself with the next state. A stack is the smallest useful example: a list is the state, and each message is a push or a pop:
stack.exs
defmodule Stack do def start, do: spawn(fn -> loop([]) end) def push(pid, item), do: send(pid, {:push, item}) def pop(pid) do send(pid, {:pop, self()}) receive do {:value, value} -> value :empty -> :empty end end defp loop(items) do receive do {:push, item} -> loop([item | items]) {:pop, from} -> case items do [head | tail] -> send(from, {:value, head}) loop(tail) [] -> send(from, :empty) loop([]) end end end end pid = Stack.start() Stack.push(pid, :a) Stack.push(pid, :b) IO.inspect(Stack.pop(pid)) IO.inspect(Stack.pop(pid)) IO.inspect(Stack.pop(pid))
elixir stack.exs
:b
:a
:empty
The pushes are messages that arrive before the pops, and the mailbox keeps their order. The caller never touches the list: it sends a tuple and waits for the answer, and the loop owns the value. The functions start/0, push/2 and pop/1 are the public surface, and loop/1 is private.
The counter behind three functions
A counter is the same shape with an integer. The message that asks for the value carries the pid of the caller, because the loop has to send the answer somewhere:
counter.exs
defmodule Counter do def start, do: spawn(fn -> loop(0) end) def add(pid, n), do: send(pid, {:add, n}) def get(pid) do send(pid, {:get, self()}) receive do {:count, n} -> n end end defp loop(n) do receive do {:add, k} -> loop(n + k) {:get, from} -> send(from, {:count, n}) loop(n) end end end pid = Counter.start() Counter.add(pid, 2) Counter.add(pid, 3) IO.puts(Counter.get(pid))
elixir counter.exs
5
The two additions are messages in the mailbox, and the question comes after them, so the answer is 5. The same program with an Agent is three lines because the agent writes this loop for you; the loop is still the mechanism underneath, and seeing it once makes the agent less magical.
A call and a cast
The two messages above are the two kinds of communication a server offers. A call sends a question, waits for the reply, and is synchronous: get/1 is a call. A cast sends a message and returns the message at once, without an answer: add/2 is a cast. A call needs a timeout when the other side may be gone; a cast cannot tell the sender that anything went wrong.
- A call is right when the caller needs the result to continue.
- A cast is right when the work can happen later and nobody waits for it.
- A cast to a dead process is accepted and dropped, as the processes lesson showed.
The state dies with the process
The value lives in the loop, so it disappears when the loop ends. Nothing else keeps a copy, and a new process starts from the argument of start/0, not from the old state:
cell.exs
defmodule Cell do def start, do: spawn(fn -> loop(0) end) def add(pid, n), do: send(pid, {:add, n}) def stop(pid), do: send(pid, :stop) def get(pid) do send(pid, {:get, self()}) receive do {:count, n} -> n end end defp loop(n) do receive do {:add, k} -> loop(n + k) :stop -> :ok {:get, from} -> send(from, {:count, n}) loop(n) end end end pid = Cell.start() Cell.add(pid, 5) IO.puts(Cell.get(pid)) Cell.stop(pid) Process.sleep(50) IO.inspect(Process.alive?(pid))
elixir cell.exs
5
false
The false is the point: a crash or a stop takes the value with it. A supervisor starts a new cell with the initial state, which is why the state of a supervised server is not a backup; a value that must survive a crash belongs in a database or in ETS, and the ETS lesson shows the table that outlives a process.
The mistake: a loop that keeps the old state
The loop is the only place that changes the state, and a recursive call with the old argument silently throws the new value away. The program below looks right and answers 0:
badstate.exs
defmodule Bad do def start, do: spawn(fn -> loop(0) end) def bump(pid), do: send(pid, :bump) def get(pid) do send(pid, {:get, self()}) receive do {:value, n} -> n end end defp loop(n) do receive do :bump -> loop(n) {:get, from} -> send(from, {:value, n}) loop(n) end end end pid = Bad.start() Bad.bump(pid) IO.puts(Bad.get(pid))
elixir badstate.exs
0
The :bump clause calls loop(n) where it should call loop(n + 1), so the message did arrive and nothing changed. A server written by hand has this bug until a test reads the value back after a cast, which is one of the reasons a GenServer with its callback names is easier to get right.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Where does the state of a hand-written server live?
Answer
In the argument of the loop that the process runs
The loop carries the value as an argument and calls itself with the next one.
-
Why does the loop call itself with the new argument instead of changing a variable?
Answer
Because Elixir has no mutable variables
A functional language binds new values; the loop passes the new state to the next call.
-
What is the difference between a call and a cast?
Answer
A call waits for a reply, a cast does not
A call is synchronous and returns the answer; a cast sends the message and returns at once.
-
What happens to the state when the process that holds it ends?
Answer
It is gone, and a new process starts from its initial value
The state lives in the process; a restart begins with the initial argument, not the old value.
-
What does this program print?
defmodule S do def start, do: spawn(fn -> loop([]) end) def push(pid, x), do: send(pid, {:push, x}) def all(pid) do send(pid, {:all, self()}) receive do {:items, items} -> items end end defp loop(items) do receive do {:push, x} -> loop([x | items]) {:all, from} -> send(from, {:items, items}); loop(items) end end end pid = S.start() S.push(pid, 1) S.push(pid, 2) IO.inspect(S.all(pid))Answer
[2, 1]
Each push prepends to the list, so the last pushed item is the head.
-
What does this program print?
defmodule C do def start, do: spawn(fn -> loop(2) end) def add(pid, n), do: send(pid, {:add, n}) def get(pid) do send(pid, {:get, self()}) receive do {:value, n} -> n end end defp loop(n) do receive do {:add, k} -> loop(n + k) {:get, from} -> send(from, {:value, n}); loop(n) end end end pid = C.start() C.add(pid, 3) IO.puts(C.get(pid))Answer
5
The loop starts at 2, adds 3 and answers 5.
-
What does this program print?
defmodule B do def start, do: spawn(fn -> loop(0) end) def bump(pid), do: send(pid, :bump) def get(pid) do send(pid, {:get, self()}) receive do {:value, n} -> n end end defp loop(n) do receive do :bump -> loop(n) {:get, from} -> send(from, {:value, n}); loop(n) end end end pid = B.start() B.bump(pid) IO.puts(B.get(pid))Answer
0
The bump clause keeps the old argument, so the counter never advances.
-
What does this program print?
pid = spawn(fn -> receive do :stop -> :ok end end) send(pid, :stop) Process.sleep(50) IO.inspect(Process.alive?(pid))Answer
false
The loop returns on :stop, the process ends, and alive? answers false.
-
Why does a call to a server carry a timeout?
Answer
Because a dead or busy server would make the caller wait forever
A call waits for an answer; the limit is what turns a missing answer into a failure.
-
Which tool writes the receive loop for a single value, with get and update?
Answer
Agent
An Agent is the small server for one value; Task is for one computation.
Article author: Arthur Isaev