Home > Caching, Operations > Cache Segmentation for Rails Apps

Cache Segmentation for Rails Apps


Problem: Cache Correctness vs. Cache Persistence
In many Rails apps, there are two caching requirements: Cache as much static data as possible, Flush any cached content that varies with each release (cached models, for example).  Many simple deployment strategies flush all cache data to prevent serialization conflicts with models, but this can cause an expensive penalty in cache misses until your cache is warmed up again.

At PatientsLikeMe, we faced both of these problems.  We have a high volume of action-cached data with a long shelf-life that’s difficult to pre-cache.  We also have a number of volatile model based caches that need to be flushed every time we deploy.

Solution: Segment Stable vs. Volatile Caches
I built this simple segmented cache strategy to meet our needs: a stable memcache namespace for any data that should persist between deploys, and a volatile cache namespace that’s swapped on every deploy.

Rails Cache Configuration Example

revision_file = Rails.root.join('REVISION')
if File.exist?(revision_file)
  revision = File.read(revision_file).match /[a-f,0-9]{6}$/
config.cache_store = :mem_cache_store, memcache_host, { :namespace => "volatile-#{ revision ? revision[0] : '0' }" }
config.action_controller.cache_store = :mem_cache_store, memcache_host, { :namespace => 'stable' }

EDIT: Thanks to Jeremy for the refactoring for this sample.

You’ll notice this sets one Cache object for the default Rails cache (used by models and most things) and a custom, stable Cache object for anything in a Controller (Action and Fragment Caches).

Categories: Caching, Operations
  1. 11/23/2010 at 9:26 pm

    Clever! Where does the REVISION file come from? Are the contents the latest Git commit SHA, written by the deploy script?

    You could tighten the code up a bit: Rails.root.join(‘REVISION’)

    • 11/23/2010 at 9:41 pm

      The REVISION file is a capistrano artifact of a deploy, which has the last Git SHA or SVN revision #.

      I like the suggestion on the code cleanup, thanks for that.

      In other news, I wish there was a way to embed a Gist in hosted WordPress, this sucks. I’ll edit the sample with your idea.

      • 08/21/2011 at 7:45 pm

        Wait, I cannot fathom it being so stragihftworard.

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: