Interactive Memcached Debugging with Rails

Posted on June 20, 2009

The memcached support in Rails is great, but it’s a bit difficult to see what the heck is going on in a production environment. The first problem is, by default Rails doesn’t keep a list of all memcached keys that are available on the system. So, you have to use a plugin like memcache_store_with_delete_matched to have memcache itself store a list of all available keys.

You can install this plugin with the typical script/plugin command.

script/plugin install git://github.com/lacomartincik/memcache-store-with-delete_matched.git

Then, you configure memcached in your environment.rb like this.

mem_cache_options = {
    :c_threshold => 10000,
    :compression => true,
    :debug => false,
    :timeout => false,
    :namespace => 'app',
    :readonly => false,
    :urlencode => false
  }
  config.action_controller.cache_store = :mem_cache_store_with_delete_matched, ['127.0.0.1:11211'], mem_cache_options

The other benefit to using memcache_store_with_delete_matched is that regular expressions within expire_fragment works.

expire_fragment(%r!/index_user_.*!)

So, down to debugging. If you want to see all keys in a script/console, you can do the following.

YAML.load(ActionController::Base.cache_store.fetch("memcached_store_key_list"))

You can select certain keys from the memcached_store_keylist.

YAML.load(ActionController::Base.cache_store.fetch("memcached_store_key_list")) .detect{ |k| k.match(/index/) }

Once you have the list of keys, you can plug them into a fetch command.

ActionController::Base.cache_store.fetch("app/blog/index")

You can also manually expire keys from a console.

c = ApplicationController.new
c.expire_fragment(/index/)