Memcache Sessions in Rails

Linux, Rails, Ruby

UPDATE FOR RAILS 3:

https://awesomerails.wordpress.com/2011/08/23/rails-3-memcached-session-store/


Does rails scale? No! But memcached does!

Ok ok, you aren’t probably going to need memcache for caching huge queries yet.  But it is useful for storing your user’s session data server side and not having to worry about filling up cookies or clearing out files in your tmp directory or your database.

So I’ve been designing a single sign on system for the interanl applications at CI.  And I need apps on all kinds of different servers to talk to the same memcache instance(s) for their sessions.  I did follow this article on err.the_blog to get started but I only got so far and ran into some issues that got hard to debug.

The default memcached session store hits localhost:11211 which is generally fine for most applications but I needed a clustered approach and could not for the life of me figure it out.  Turns out like most things with rails it was really easy.

Pre-req’s:
1. Memcached installed on your machine or whatever machine you want to use for sessions
1a. Top Funky has a really simple shell script that will work on os x and another that works on ubuntu
2. You will need the memcache-client gem, you know what to do.

In environment.rb in my rails app I needed to do a few things:

1. Setup the connection to the memcache server

2. Tell rails to use memcache for sessions

3. Setup rails to drop all its sessions stuff into the memcache server we setup

Alright so 1:
require 'memcache'
CACHE = MemCache.new(:namespace => "your_app")
CACHE.servers = 'some_ip_address:some_port', 'another_ip_address_if_you_need_it:some_port'

and then 2(pretty easy)
config.action_controller.session_store = :mem_cache_store

and then 3 (this is where you can set the session timeout and then pass in the memcached object CACHE)

config.action_controller.session = {
:session_key => '_your_app_session',
:secret      => 'someotherkindofsecretthatnooneknows',
:cache       => CACHE,
:expires=>900  }

I think if memcache doesn’t find the session on one server it’ll look on the others you put in the CACHE.servers list.  However if your memcache instance goes down your rails app is hosed and starts throwing up 500 errors all over itself.

You can actually throw alot of this config into a gem if you are going to have several apps that are all going to use the same config (setup the CACHE stuff in your gem and then just do step 3 in your apps)  That way if you need to switch or add servers to your memcache setup you don’t have to make changes in 20 places.