Barack Obama - Change Can Happen!
 
Obama '08
art

geek

howto

music

politics

Home » Uncategorized

Speed up Ruby-on-Rails with memcached

Submitted by fak3r on Thursday, 11 May 2006Comments

RubyOnRailsToday I learned about memcached, which I’d heard of before, but never really investigated. From the project’s site, ”memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.” So, even though I don’t have a huge amount of traffic, I still have dynamic sites, and I’m always looking at ways to speed up my Typo blog (this site not anymore). So, using memcached, you can get a big performance boost in databases calls, which sold me on giving it a go. I read two posts today, one about howto set this up in Freebsd, along with howto modify the source code for a boost over the default setting, and how to make Ruby-on-Rails take advantage of it. Below are steps compiled from both sites, and used on my FreeBSD 6.0 server, but most of the steps should work as well in Linux. Read more for the steps.

First let’s get memcached installed

cd /usr/ports/databases/memcached/

We only want it to get past the configure step before we modify code

make configure

Now it’s time to modify the code (NOTE: the howto linked to above was specific to a FreeBSD issue, if using Linux you may not need to make this modification)

vi work/memcached-1.1.12/memcached.c

Find this line

#include "memcached.h"

Add the undef line below it and save

#include "memcached.h"
#undef TCP_NOPUSH

Now we want it to compile and install

make install

Once that’s complete, we want to enable memcached in rc.conf

echo "memcached_enable="YES"" >> /etc/rc.conf

Then we’ll start memcached

/usr/local/etc/rc.d/memcached.sh start

Next we’ll install the ruby-memcache client

cd ../ruby-memcache/
make install

Finally we’ll modify our Ruby-on-Rails app’s environment to use memcache as its session store (make a backup first!)

cp config/environment.rb config/environment.rb.dist
vi config/environment.rb

Find the line that tells session_store to use the database instead of the file system

#config.action_controller.session_store = :active_record_store

Modify it so it tells it to use memcached, and save

config.action_controller.session_store = :mem_cache_store

Stop Typo, and then manually clear the cache

rake sweep_cache

Now restart your Typo server, and you’re done! It should now be storing all session data via memcached instead of your database.

Related posts