When to use Agent instead of GenServer in Elixir
Asked Answered
K

2

7

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.

Kaiulani answered 19/7, 2019 at 7:14 Comment(0)
N
12

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
Nowhere answered 19/7, 2019 at 7:58 Comment(0)
N
0

One UseCase I faced where you would want to use plain GenServer instead of an Agent is if you have millions of operations.

I faced this performance issue when solving some leetcode/AdventOfCode problems.

Agent would give me a Time Limit Exceeded output while GenServer would pass (on leetcode)

One ex: https://leetcode.com/problems/insert-delete-getrandom-o1/solutions/2858527/elixir-genserver-2-maps/?envType=daily-question&envId=2024-01-16

Nicholson answered 16/1 at 7:1 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Haskell

© 2022 - 2024 — McMap. All rights reserved.