Rails cache busting

Using key based cache frees us from writing observers to manually purge the cache. When record is updated it’s cache_key changes, new content is cached and old one is eventually purged using TTL. Here is my previous post about various uses of caching.

We cache comments_count and use touch: true to update Article timestamp when new Comment is created/updated/deleted. The problem is it busts cached data for ALL Article methods and view cache as well. We might not want that.

In such cases instead of touch: true we can implement callbacks on the child record to delete specific cached data for the parent record.

This will not impact Article timestamp and leave the other cached data in place. We do need to be more careful with this approach as it could lead to situations where only some cached data is deleted but some remains stale until default application TTL removes it. But this can be a useful solution where there is unnecessary cache purging and recreation.