I am a Sr. Software Developer at Oracle Cloud. The opinions expressed here are my own and not necessarily those of my employer.
Rails cache with variable TTL
Method level caching can be a useful tool to scale our applications. When the underlying data changes we need to bust cache by creating new cache_key
. But the old cached content still remains in RAM (Redis or Memcached) until it is purged with TTL.
We do not want to set TTL too long because it will waste RAM. At the same time we do not want to set it too short because it will purge valid cache. That cache will then need to be regenerated.
We can start with simple application level configuration where we set default TTL of 1 hour.
We then adjust it for different methods.
We are also customizing Redis cache key by appending method name to it. This avoids cache_key collision in the same model.
But sometimes data attributes change less frequently for different records of the same class. How can we change our TTL depending on circumstances? For example, users may be active
or inactive
. When they are active
their data changes often and we want shorter TTL. When they become inactive the data is not updated and can be cached for longer.
We can wrap this logic in a private method:
This will allow us to make much better use of our Redis RAM for caching purposes.
Links
- Previous post on cache busting.
- Previous post on cache pre-generating.
- https://redis.io/topics/lru-cache
- http://antirez.com/news/109