Hi, all!
So I’ve been using ETS to cache some data, the result from a series of queries so I don’t have to hit the database so often. The user sends a request, if there is an entry for it on ETS it returns the data and if not, it queries the database, returns it to the user and also adds to an ETS table.
So the solution I had in mind so the user always get the most updated data was to, every time some of the data changes, the update function calls the GenServer that I wrote to interface ETS and deletes everything and so the next user to send a request would get fresh data from the database and repopulate the ETS table with that fresh data.
def update_content(attrs) do
Cache.delete(:key, :table_name)
%Content{}
|> Content.changeset(attrs)
|> Repo.update()
end
The GenServer looks like this:
def delete(key, table) do
GenServer.cast(__MODULE__, {:delete, key, table})
end
def handle_cast({:delete, key, table}, state) do
:ets.delete(table, key)
{:noreply, state}
end
What is happening though is that sometimes the table entry is deleted, sometimes it’s not. The only thing I can think of is some sort of race condition going on, but I have no idea how that would be the case. Any ideas?
Also (except for the fact it’s not doing what I wanted it to do), is there anything wrong/inefficient with this approach?
I’m pretty new to ETS as well as writing my own GenServers, so this could be a very silly question…
Thank you!