Shekhar Jadhav
Shekhar Jadhav

Reputation: 1035

How to keep the cache in sync with the database?

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.

  1. How should I keep my database in sync with cache(cache should update as database updated)?
  2. How should I know when database is updated?

Upvotes: 2

Views: 8073

Answers (2)

Mohsin Nasir
Mohsin Nasir

Reputation: 11

There are multiple ways to synchronize your cache with your database but it depends upon the cache you are using. In distributed caching following are the ways to ensure valid data in cache.

  1. Using expirations(Still wont gaurantee data validity) (Feature supported by Redis, NCache, Apache Ignite...)
  2. Using SQL, Oracle dependency (Features supported by NCache)
  3. Using Custom Dependency based on notification like Cosmos and mongo db provides db change notifications (Features Supported by NCache)

Upvotes: 0

Louis Jacomet
Louis Jacomet

Reputation: 14510

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.

Upvotes: 7

Related Questions