Fun With Rails and High-Performance Caching Mechanisms (Memcached)
Since it’s Spring break for University of Michiganers, I’ve had some free time to mess around with learning stuff I don’t have time for when school is in session. Something I’ve been meaning to try out is memcached, which is an uber-efficient way to cache stuff in memory so you don’t end up hitting the database a lot for redundant queries.
I installed memcached on my mediatemple machine using some directions I found online specifically for centos. I don’t have yum or rpm or whatever people use for putting new stuff onto their linux boxes. I just wget, untar, and make/make install. I had to make a symbolic link for the libevent thing that I installed as well since the path wasn’t set up correctly. I’m still trying to get memcached to run automatically as a daemon when I boot up. I tried sticking a line in the /etc/init.d/ or something rc.local but it hasn’t really worked. Oh well.
I’m using memcached right now along with a rails gem called “Cached Model” that does a pretty good job of automating the caching process. What’s important to know is that the gem only caches Active Records that are found via a simple find on id. It won’t cache more complex queries. Right now I have it running on my Animenano site caching a bunch of objects. I’ve seen a small though noticeable difference.
Memcached isn’t without its caveats, however. For one thing, your initial db hit is going to take longer than normal since you’re going to be checking memcached, then grabbing the data from the db, then saving the data into memory. From reading the logs, this doesn’t really take that much extra time. The time saved is likely more worthwhile.
I’m always trying to squeeze more performance out of my sites. Periodically I’ll go check out my log files and see if there’s anything taking an insane amount of time to render (like, .1 seconds or so). I’ve caught a few bad algorithm decisions that I had made in the past, and I think for the most part my sites run pretty efficiently. Memcached is a pretty fun way to slice some time off of the page rendering times for Anime Nano.
If you have a few spare hours to kill and a rails app that seems to be a little slow, it might be worthwhile to install memcached and see if caching your Active Record objects will speed things up. I’m seeing a speedup of maybe 1/2 (it takes half as long to load a page) vs running without memcached. That’s totally non-empirical observation, though.