Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 48 ยท Concurrency and OTP

Keeping State in a Process

Learn how Elixir keeps changing state with immutable data: recursive receive loops, request/response messages, Agent and Task, with JS stand-ins.

Elixir data is immutable, yet programs need state: a counter, a shopping cart, the current score of a game. The answer is that state lives in a process. A process holds a value in its own arguments, handles one message at a time, and when it wants to "change" the state it simply calls itself again with a new value.

In this lesson you will build a stateful process by hand with a recursive receive loop, add request/response messages, and then meet the two small abstractions Elixir provides for common cases, Agent and Task. Real Elixir blocks are read-only here; the editors model the same ideas with JavaScript async functions. If processes are new to you, read Processes and Message Passing first.

State without mutation

Loop The process calls itself with new state.
One message at a time No two updates ever overlap.
Private Only messages can reach the state.

State is just an argument to the loop.

1 / 2

A recursive receive loop

Here is a counter process in plain Elixir:

ELIXIR
defmodule Counter do
  def start(initial \\ 0) do
    spawn(fn -> loop(initial) end)
  end

  defp loop(count) do
    receive do
      :increment ->
        loop(count + 1)

      {:get, caller} ->
        send(caller, {:count, count})
        loop(count)

      :stop ->
        :ok
    end
  end
end

loop/1 waits for a message. For :increment it calls itself with count + 1: the "new" state is simply the next argument. Because the call is the last thing in the clause, it is a tail call (see Recursion and Tail Calls), so the loop runs forever without growing the stack. The :stop clause does not call loop, so the process ends.

Using it:

ELIXIR
pid = Counter.start()
send(pid, :increment)
send(pid, :increment)
send(pid, {:get, self()})

receive do
  {:count, n} -> IO.puts("count is #{n}")
end

This prints count is 2. Messages from one sender arrive in order, so both increments are handled before the :get.

Why is this safe? The process handles one message at a time. Two clients can send :increment at the same moment and the updates cannot interleave, because the mailbox is a queue and the loop is single-threaded. You get the effect of a lock without writing one.

Request and response

Notice that a client has to send its own pid so the server can reply. A reply and a request can be mixed up when several are in flight, so the usual pattern tags each request with a unique reference:

ELIXIR
def get(pid) do
  ref = make_ref()
  send(pid, {:get, self(), ref})

  receive do
    {:reply, ^ref, value} -> value
  after
    5_000 -> exit(:timeout)
  end
end

The server answers send(caller, {:reply, ref, count}). The client matches on the pinned ref, so it only accepts the reply to its own question, and the after clause stops it from waiting forever. This is exactly what GenServer.call/3 does for you, with a 5-second default timeout.

sequenceDiagram
    participant C as Client
    participant S as Counter process
    C->>S: {:get, client_pid, ref}
    Note over S: handles one message,<br/>keeps count
    S->>C: {:reply, ref, 2}

A synchronous request is a message plus a tagged reply.

A JavaScript actor stand-in

The editor below imitates the loop in JavaScript. Each "process" has a mailbox and an async loop that awaits one message at a time. It is a model, not the BEAM: JavaScript runs on one thread and switches only at await, whereas real processes run in parallel and are preempted by the VM.

JS A counter process with call and cast (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The three increment messages are cast-style (no reply). The get is call-style: the caller waits for an answer and gets exactly the value the loop held when it processed that message.

Agent: state without writing the loop

Most simple state does not need a custom message protocol. Agent wraps the loop and offers functions instead:

ELIXIR
{:ok, agent} = Agent.start_link(fn -> %{} end)

Agent.update(agent, fn cart -> Map.put(cart, :apple, 3) end)
Agent.update(agent, fn cart -> Map.update(cart, :apple, 1, &(&1 + 2)) end)

IO.inspect(Agent.get(agent, fn cart -> cart end))   # %{apple: 5}
  • Agent.start_link/1 starts the process with an initial state returned by a function.
  • Agent.get/2 reads the state through a function and returns its result.
  • Agent.update/2 replaces the state with the result of a function.
  • Agent.get_and_update/2 does both in one step; its function returns {reply, new_state}.

Each function runs inside the agent process, so keep them short, since a slow function blocks every other client. Do not do expensive work there, and do not send huge state back to callers if a small answer will do.

The point to see in the next editor is that an update is serialized. A naive shared variable updated across await points loses writes, because every task reads the old value before any of them writes. The agent never loses one.

JS Why a process beats a shared variable (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The naive version prints 1: all 100 tasks read 0 before the first write. The agent version prints 100 because each update sees the result of the previous one. The agent version takes longer (about 100 sleeps in a row); that is the price of serialization, and it is why you should not funnel a hot, slow path through one process.

Task: one piece of async work

When you do not need long-lived state, only to run something in the background and collect the answer, use Task:

ELIXIR
task = Task.async(fn -> expensive_calculation() end)

# ... do other things ...

result = Task.await(task)

Task.async/1 starts a linked process and returns a task handle; Task.await/2 waits for its reply (5 seconds by default, then it exits the caller). Always await a task started with async from the same process that started it. For fire-and-forget work use Task.start/1, and for many tasks at once see Tasks and Parallel Work.

Never keep unbounded data in a process "just in case". The state of a process lives on its heap for as long as it runs, and a single busy agent can become a bottleneck for the whole application, since it handles requests one at a time.

Design notes

  • Put state in a process only when it must change over time and be shared. Pure data and pure functions need no process.
  • Wrap the message protocol in a module with a public API (Counter.increment(pid)), so callers never see raw send.
  • Keep handlers fast; offload long computations to tasks.
  • Next, GenServer gives you this loop with call, cast, timeouts and supervision built in. Agents and Tasks are small special cases of it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a recursive receive loop, how does a process 'change' its state?

    Values are immutable, so the loop passes the next state as an argument in a tail call.
  2. 2. Why does a client include a reference (make_ref/0) in a request?

    Matching on a unique pinned reference ensures the client only accepts the reply to its own request.
  3. 3. Where do the functions passed to Agent.update/2 run?

    The agent executes each function inside itself, which serializes updates but also means slow functions block other clients.
  4. 4. What should the process that starts a Task.async/1 do with the result?

    Task.async links the task to the caller and sends the reply to it, so the same process should await the result.

Summary

  • State lives in a process and is passed along as a loop argument; a process handles one message at a time.
  • Use tagged references (and an after timeout) for request/response messages.
  • Agent wraps the loop for simple state; Task.async/await runs one piece of work concurrently.
  • Keep process handlers fast and do not make one process a bottleneck.
  • The JavaScript editors are stand-ins for the actor model, not the real scheduler.

Next up: GenServer.