Rails Model Caching with Redis

Originally published at: http://www.sitepoint.com/rails-model-caching-redis/

Model level caching is something that’s often ignored, even by seasoned developers. Much of it’s due to the misconception that, when you cache the views, you don’t need to cache at the lower levels. While it’s true that much of a bottleneck in the Rails world lies in the View layer, that’s not always the case.

Lower level caches are very flexible and can work anywhere in the application. In this tutorial, I’ll demonstrate how to cache your models with Redis.

Continue reading this article on SitePoint

Thanks for the article, caching requires a lot of effort, it seems you have to figure out a lot of things without any framework, just using creativity, to know what to cache, how to cache, what and when to invalidate.

In your article, if application is too big you could use a Struct to not to have to change views, is that possible? or does ruby(array of objects) → cache(string), then cache(string) → ruby(array of objects) consumes more resources than cache(string) → ruby(array of hashes)?

Would you cache just one model? or maybe expire just the updated model? why? what if the database has a lot of records? you might require a paginated cache, right?

Caching always makes me thing in a lot of questions.

Hi Vasu,

I think you are definitely on the right track but you have missed a trick which will make your code much cleaner, namely Rails.cache.

This rails class ties in to the config.cache_store that you set earlier and allows you to access the cache by using Rails.cache in your code so you no longer need to set up the $redis initializer and any time you want to swap out your cache backend you can easily do so.

This also means that you know have access to Rails.cache.fetch which takes a key and then any optional options and then a value or a block. In the case of a block, calling Rails.cache.fetch will first check the cache using the key provided and it doesn’t find anything in the cache then it executes the do block and sets the cache to whatever the block yields.

So your helper would be reduced to something like the following.

@categories = Rails.cache.fetch("categories") do

To add a time based expiry you just add in the time as an option.

@categories = Rails.cache.fetch("categories", expires_in: 5.minutes) do

You can also clear the specific cache by passing in the key.


I would defintely recommend checking out http://guides.rubyonrails.org/caching_with_rails.html for more information.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.