Search code examples
erlangelixirgen-server

When to use Agent instead of GenServer in Elixir


While reading the documentation of both GenServer and Agent I wondered what are the Use Cases the Agent solves that GenServer cannot? So, when to prefer Agent over GenServer?

I know that functions defined in your own agents get executed on the agent process itself, so that is a big difference for sure.


Solution

  • While reading the documentation of both GenServer and Agent I wondered what are the Use Cases the Agent solves that GenServer cannot?

    None that GenServer cannot, because Agent is implemented on top of GenServer (and quite simply, just look at the source).

    So, when to prefer Agent over GenServer?

    When the special case implemented by Agent is sufficient. For example: No async replies, no distinction between calls and casts, etc.

    I know that functions defined in your own agents get executed on the agent process itself

    It isn't functions "defined in your own agents", but those which are passed as arguments to Agent.get/update/etc.

    Example from the docs:

    # Compute in the agent/server
    def get_something(agent) do
      Agent.get(agent, fn state -> do_something_expensive(state) end)
    end
    
    # Compute in the agent/client
    def get_something(agent) do
      Agent.get(agent, & &1) |> do_something_expensive()
    end