So, we needed to clear out memcached. You don’t always want to do this when you deploy, but sometimes layout changes, stream changes, or other major application changes require flushing memcached on production. The logical solution is to put this in the same place as the other stuff you do when you deploy, or otherwise “sometimes.”

To do that, I set up a Rake task. Using Rake has a few advantages – you can use the Rails environment and the Rails configuration info, so you don’t have to make assumptions about where memcached is located or how it’s accessed (init.d vs service). Also, you can clear out application caches – pages rendered to the filesystem, caches stored in the db, or other weird stuff your app might do.

My rake task looks like this:

namespace :cache do
  desc 'Clear memcache'
  task :clear => :environment do
    Rails.cache.clear
    CACHE.flush
  end
end

Then, I set up a Capistrano action to run the rake task on our production servers. I put it in a shared.rb file so it applies to any environment in our deploy scheme – you might want to put it directly in your Capfile, or in the appropriate environment file in config/deploy if you use capistrano-ext. Here’s my cap action:

Capistrano::Configuration.instance(:must_exist).load do
  namespace :memcached do
    desc "Flush memcached"
    task :clear, :roles => [:cache], :only => {:memcached => true} do
      run "cd #{deploy_to}/current && /usr/bin/env rake cache:clear RAILS_ENV=#{stage}"
    end
  end
end

Remember, you have to cd into the directory of your deployed rails app in order to use rake, you must have rake installed on the target machine, and you must set RAILS_ENV to the appropriate setting. Since we’re using multistage, I used the stage variable, but you might want to hard-code production if your deployment setup is more simple.

Feel free to leave questions in the comments!