Guide to Caching in Rails using Memcache

Guide to Caching in Rails using Memcache 1

The post intends to cover the topics and tools that can help in implementing Memcache as caching store in Rails and debugging issues with it.

To help newbies grasp it from start, it also provides references to installing and validating the memcache install without Rails too.

"Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering"

Installing Memcache

  • Mac OS X Snow Leopard
    • brew install memcached
  • Ubuntu
    • sudo apt-get install memcached

More information about Installing Memcache can be found here

Starting Memcache

  • memcached -vv

-v option controls verbosity to STDOUT/STDERR. Multiple -v's increase verbosity. Memcache Settings can be inspected in detail using echo "stats settings" | nc localhost 11211. Get the thirst quenched more at http://linux.die.net/man/1/memcached or man memcached for all options.

Connecting to Memcache Server through Telnet

  • telnet localhost 11211 can be used to connect locally to run/inspect memcache data store
  • Its recommended to follow Using Memcache Commands to get a full hang of memcache commands
  • For the sake of completeness, here are three main commands (store/retrieve/remove key/values)
    • Write to Memcache (Value need to be entered in new line)
      • set abc 0 60 5 # where abc is the key, 60 is duration in seconds and 5 is length of data
      • hello # data to store in abc key
    • Read from Memcache
      • get abc
    • Delete from Memcache
      • delete abc

Implementing and Using in Rails

Installing Dalli (Memcache Client)

Configure Memcache as cache store in Rails

  • Set perform_caching and specify cache_store in the environment file (e.g. RAILS_ROOT/config/environments/production.rb)
    • config.action_controller.perform_caching = true
    • config.cache_store = :dalli_store, { :namespace => "my_project", :expires_in => 1.day, :socket_timeout => 3, :compress => true }
      • Detailed explanation of Dalli Client options can be found here

Getting Ready for the Fight/Debugging

  • IRB as always helps us get started:
    • require 'rubygems'
    • require 'dalli'
    • CACHE = Dalli::Client.new('127.0.0.1', { :namespace => "my_project", :expires_in => 3600, :socket_timeout => 3, :compress => true }) # Options are self-explanatory
    • CACHE.set('key', 'value', 180) # last option is expiry time in seconds
    • CACHE.get('key') 2
  • Memcache does not provide any command to list all keys present but at times seeing the keys and their expiry time can be a life saviour. Here is a Ruby Script to list all memcache keys

    Sample Output:

    id expires bytes cache_key
    1 2014-01-22 19:05:09 +0530 5 my_project:key
    ...

Using Memcache to store expensive calculations and avoid recalculations

  • We can store expensive calculations in memcache and retrieve it next time if expensive calculation expected to return the same result else recalculate and store again.
  • Rails provides helpers like Rails.cache.read to read cache, Rails.cache.write to write in cache and Rails.cache.fetch to return result if present in cache else write in cache and return the result
  • Code Snippet to pass a block to evaluate if key not present in cache, else return the value of key

    
    
  • Using data_cache helper created in last step in application_controller.rb

    
    

Clearing Cache

Auto-Expire after a specified time

  • Memcache accepts an expiration time 3 option with the key to write and only returns the stored result if key has not expired yet, else returns nothing.
    • Rails.cache.write(key, value, {expires_in: time})
    • Rails.cache.fetch(key, {expires_in: time}) { # Block having expensive calculations }

Faking Regex based Expiry

  • Unfortunately, Memcache does not allow listing of all keys so, apparently, there is no way to partially expire a subset of keys. Memcache only provides a delete method for the specified key restricting us to, beforehand, know the key to delete.
  • But, there is a nice trick to partially expire a subset of keys Faking Regex Based Cache keys in Rails 4.
    • To achieve it, we have to focus more on keyword subset and defining subset is the Nirvana to crack the problem.
    • Introduce a dynamic component in all the keys which we want to treat as subset
    • Have a way to control the change of dynamic component
    • When dynamic component changes, a new key is created and stored in Memcache which would be referred for data from now.
    • The old key still remains in memcache and has still not expired but it stores the stale data and fresh data is hold by new key which we are referring in all of our interactions.
    • Memcache would eventually kick the old key with stale data out (uses LRU algorithm to allocate space for new data)
    • In the snippet below, we have added dynamic component last_cache_refreshed_at in Category which can be selectively changed to expire cache of particular categories instead of all

      
      

Writing Test Cases

Gotchas

  • Using touch command to update expiry cache time (Fixed in Memcache 1.4.14)
  • Check Memcache Version using telnet client
    • Execute stats
    • Look for STAT version 1.4.13

  1. Caching Expensive Api Requests Results

  2. If Object is saved in Memcache, Cache.get('key') might raise

    Dalli::UnmarshalError: Unable to unmarshal value: undefined class/module <model_name>

    Use require_dependency "app/models/.rb"

  3. Expiry Time of 0 makes the key stays for indefinite time only limited by Memcache clearing it out in case of cleaning up

  4. Scoped Expiration AND Reload Namespace using a Proc