How do we know if a cached item is valid or invalid ?

Could someone please let me know how to check if a cached item is valid invalid?

Consider the following scenario :

Suppose that we have a database that stores "key:value" pairs and we have a cache layer before this database.

Now assume the "value" of one of the items present in the database is updated by a write operation, then this makes the entry present in cache "invalid"; in this case how the next read request will get to know that the value present in the cache is invalid and it needs to access value from the database.

The approaches which I could think of are listed below; please let me know if any of these are correct; if not, what is the right way ?


Approach 1:
Whenever a write is issued for a particular key :

[a] We check if the "key" is present in cache.
[b] If yes, we block any read / write requests for that key, update the "value" in cache, and then update it in DB, then let the blocked requests proceed. Though the downside of this approach is that it will perform badly if the service is read / write intensive.
[c] If the "key" is not present in cache, update the "value" in DB and add this "key:value" entry to the cache.

Approach 2:
Whenever a write is issued for a particular key, update the key in the DB an update the "value" in the cache through some routine that will be triggered after every fixed interval and update all the "values" in cache which are updated in DB. This will provide eventual consistency but not strong consistency.


Any inputs are very much appriciated :)
Last edited on
It depends on the needs of the application. I think it's mostly a question of whether you need strong consistency.

If you need absolute consistency, then something like approach 1 is more likely, but I suspect you'd usually just invalidate the key in the cache so the next read will update it from the database. Note that you must make this "invalidate cache and update database" atomic if you need consistency.

If you don't need strong consistency then just put it in the database and wait for the cache item to timeout.
Topic archived. No new replies allowed.