How to invalidate cache on change of database#table?

I’m using ets for Caching articles, categories, etc. And I have some external app which can modify the appropriate tables in the database. An external app isn’t written in Erlang or Elixir.

Is there a way to make Elixir automatically remove an appropriate entity from cache once a corresponding table has been changed in the db?


If you are postgres, you might be able to use database triggers with LISTEN/NOTIFY to make some process listen for and receive the changes via postgrex.

1 Like

How would it remove data from cache/ets?

Your Elixir application listens via PostgreSQL’s LISTEN directive. Your external application sends a NOTIFY via PostgreSQL. When the LISTEN returns, discard or update the ETS cache.

All the cache? What if I want to remove only a single article? How to send a key to be removed from cache?

What portion of the cache you discard is up to you, I don’t know your business logic and constraints.

Regarding how to identify the data to discard: NOTIFY accepts a payload which can be received by LISTEN. You could send a short JSON string describing the object to be discarded.

etc is a property of Elixir. Cache is stored in it. It’s not aware of Postgres.

What does your solution have to do with invalidating or removing cache items in etc?


@idi527 and my proposed solution was: set up an Elixir process. Make that process LISTEN in a channel via postgrex. Let your external software send a NOTIFY to that channel. This makes your Elixir process aware of the change. Discard the appropriate portion of the ets cache.