TExcelTAD
Home › Elixir › Elixir Agent

Elixir Agent

Writing a receive loop by hand to keep some state works, but it is repetitive: you need a protocol for "get", "update", replies and errors. Agent is a ready-made process whose only job is to hold a value. You give it functions; it applies them to its state.

Function Purpose
Agent.start_link(fun, opts) starts an agent whose initial state is fun.()
Agent.get(agent, fun) returns fun.(state); the state is unchanged
Agent.update(agent, fun) replaces the state with fun.(state)
Agent.get_and_update(agent, fun) fun returns {reply, new_state}
Agent.cast(agent, fun) like update but doesn't wait for it to finish
Agent.stop(agent) stops the agent

A shopping cart

elixir · try it yourself
{:ok, cart} = Agent.start_link(fn -> [] end)

Agent.update(cart, fn items -> ["coffee" | items] end)
Agent.update(cart, fn items -> ["milk" | items] end)
Agent.update(cart, &["bread" | &1])

IO.inspect(Agent.get(cart, & &1))
IO.inspect(Agent.get(cart, &length/1))

removed = Agent.get_and_update(cart, fn [first | rest] -> {first, rest} end)
IO.inspect(removed)
IO.inspect(Agent.get(cart, &Enum.reverse/1))

Agent.stop(cart)
["bread", "milk", "coffee"]
3
"bread"
["coffee", "milk"]

Every call is a message sent to the agent process, which handles them one at a time. That is why an agent is safe to use from many processes: two updates can never interleave.

Concurrency without race conditions

Here 100 processes increment the same counter at once. Because the agent applies each update function in turn, no increment is lost:

elixir · try it yourself
{:ok, counter} = Agent.start_link(fn -> 0 end)

1..100
|> Enum.map(fn _ -> Task.async(fn -> Agent.update(counter, &(&1 + 1)) end) end)
|> Enum.each(&Task.await/1)

IO.inspect(Agent.get(counter, & &1))
100

Task.async/1 starts a process and Task.await/1 waits for it to finish (see the Task lesson).

Warning: A "read, then write" done in two calls is not atomic: n = Agent.get(c, & &1); Agent.update(c, fn _ -> n + 1 end) can lose updates when processes run concurrently. Do the whole change inside one update or get_and_update.

Wrapping an agent in a module

In real code you hide the agent behind a module API. Callers then don't need to know an agent is involved. Registering a name lets callers find it without passing the PID around:

elixir · try it yourself
defmodule PageViews do
  use Agent

  def start_link(_opts \\ []) do
    Agent.start_link(fn -> %{} end, name: __MODULE__)
  end

  def visit(path), do: Agent.update(__MODULE__, &Map.update(&1, path, 1, fn n -> n + 1 end))
  def count(path), do: Agent.get(__MODULE__, &Map.get(&1, path, 0))
  def top(n) do
    Agent.get(__MODULE__, fn views ->
      views |> Enum.sort_by(fn {path, count} -> {-count, path} end) |> Enum.take(n)
    end)
  end
end

{:ok, _pid} = PageViews.start_link()

for path <- ~w(/ /about / /blog / /blog /pricing) do
  PageViews.visit(path)
end

IO.inspect(PageViews.count("/"))
IO.inspect(PageViews.count("/missing"))
IO.inspect(PageViews.top(2))
3
0
[{"/", 3}, {"/blog", 2}]

use Agent adds a child_spec/1 function so the module can be placed under a supervisor (Supervisors lesson). __MODULE__ is the current module's name, here PageViews.

Where the work happens

The function you pass to get or update runs inside the agent process. Expensive work in it blocks every other caller. Compare:

elixir
# The agent does the expensive work: other callers wait
Agent.get(agent, fn state -> expensive_report(state) end)

# The caller does the work: the agent only hands over its state
state = Agent.get(agent, & &1)
expensive_report(state)

The first form copies only the result; the second copies the whole state to the caller. Choose based on which is smaller and which process should do the work.

When to use something else

  • You need to react to messages, timeouts or several kinds of requests: use a GenServer.
  • Many processes read the same data constantly: an ETS table avoids funnelling every read through one process.
  • The state is just configuration that never changes: a module attribute or application config is enough.

Test yourself

What does Agent.get(agent, &length/1) return when the state is [:a, :b]?

  1. [:a, :b]
  2. 2
  3. :ok
  4. {:ok, 2}

Why can't two Agent.update calls from different processes interleave?

  1. Agents use locks
  2. The agent process handles one message at a time
  3. Elixir is single-threaded
  4. Updates are copied into each caller

Which callback function of get_and_update is correct?

  1. fn state -> new_state end
  2. fn state -> {reply, new_state} end
  3. fn state -> {:ok, state} end
  4. fn -> state end