Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing Cache Invalidation

Tags:

caching

Just wondering how you guys manage your cache invalidations. Given that there might objects (hundreds and thousands) in the cache that might be triggered by different algorithms or rules. How do you keep track of it all?

Is there anyway you can reference the relationships from a table in the database and enforce it somehow?

Do bear with me as I've never done any caching before.

like image 271
super9 Avatar asked Nov 10 '09 20:11

super9


People also ask

What happens when cache is invalidated?

Cache invalidation describes the process of actively invalidating stale cache entries when data in the source of truth mutates. If a cache invalidation gets mishandled, it can indefinitely leave inconsistent values in the cache that are different from what's in the source of truth.

Why is cache invalidation a hard problem?

Cache invalidation is hard because: Everything in life we want to know, changes. Those changes are non-deterministic.


1 Answers

The purpose of your cache layer should be pretty much that : reflecting the corresponding data in your database, but providing it faster than the database would, or at least providing it without keeping the database busy.

To achieve this, you have two solutions :

  1. know the exact lifespan of everything you store in cache
  2. keep your cache up-to-date with your database

The first is pretty rare, but pretty easy to deal with : just update your cache on a regular basis.

The second point is what you'll most likely deal with in your projects : just update your cache when your database is updated. It's simpler than you'd think :

  • Add a new object to your cache right after you successfully added it to your database.
  • Update an object in your cache right after you successfully updated it in your database.
  • Delete an object from your cache right after you successfully deleted it in your database.

If your code is clean enough, it should be easy to implement an efficient cache policy on top of it. There's a little more about caching and how to do it well in that answer I posted some times ago. Hopefully this all will help you :)

like image 93
Nicolas Avatar answered Oct 17 '22 07:10

Nicolas