Should I use Agent for storing data used in multiple different places

Hey guys,
I’m building a cli that communicates with a database. I have this problem that in a few different places I have some logic related to the database’s version that I retrieve by querying the db.

def something() do
  if db_version > 2 do
  else
  end
end

So I don’t want to query the db whenever I need db_version. One solution would be to pass db_version via args but imo it’s not the perfect solution as I’d need to pass it to almost every function :thinking:

Then I thought about using Agent:

https://hexdocs.pm/elixir/1.14/Agent.html

Often in Elixir there is a need to share or store state that must be accessed from different processes or by the same process at different points in time.

Then I could do something like this:


def something() do
  if DBStats.version() > 2 do
  else
  end
end

defmodule DBStats do
  use Agent

  def version do
    # get version from the agent or query db and update the agent's state
  end
end

Is it a good solution? Maybe there is a different (and/or better) way to achieve this?

Is Erlang Term Storage (ETS) not feasible?

https://elixirschool.com/en/lessons/storage/ets

Because I’m curious as well, i.e. when to use one or the other.


And if ETS is internally a secret Agent. :sweat_smile:


Also see:

1 Like

Are you fetching it only once after the app starts?

If so, just use :persistent_term.

2 Likes