Issue
We have database which is updating regularly. I am using ehcache and mysql database.
Now, as soon as the database is updated we need to extract some information from database depending on the update and publish it to cache.
- How should I keep my database in sync with cache(cache should update as database updated)?
- How should I know when database is updated?
Solution
This is the classical issue introduced by caching. The moment you duplicate data - in the database and in the cache - you introduce consistency issues.
There is no single answer to this problem.
For 1, the answer depends on how important it is to prevent stale data to be served from the cache. In some situations, this is not a problem and working with a short expiry time will solve it. In other cases, you must have up to date data in the cache and then you will have to make sure cached entries are invalidated.
Note that doing this in a fully safe way is hard, this is why Hibernate has so many second level cache strategies, safer and safer, but slower and slower as well.
For question 2, this is erally specific to your application. If only your application updates the database, then you know when to invalidate the cache. If the database is updated externally, you will have to make that system aware of your application - or at least the caches - so that it can send invalidations.
Answered By - Louis Jacomet