At the Forge - Memcached Integration in Rails

Integrating memcached into your Rails application is easy and fast, with big benefits.
Expiration

Now, it's all well and good that we have cached information about each person in memcached. Our database certainly will thank us for that. But, what happens when data about the person changes? The way we've written this application, we're out of luck. Updated information will make its way to the database, but the cache will continue to give us the data it stored long ago. Even if this weren't the case, we still would want to empty the cache on occasion, allowing data to expire if we haven't used it in a while.

To solve the second problem, we can invoke our cache function in a slightly different way, indicating how long we want it to stick around in a second (and optional) argument:

@person = cache(['Person', params[:id]],
                :expires_in => 30.minutes) do
  Person.find(params[:id])
end

The :expires_in parameter accepts a number of seconds, which we either can enter by hand or via one of the super-convenient Rails extensions to the Fixnum class.

The second problem, one of expiring data manually, requires that we use a less beautiful, but also convenient, way of accessing the cache storage system:

Rails.cache.delete(['controller', 'Person', 
 ↪params[:id]].join('/'))

Basically, we access the cache system using the Rails.cache object and invoke the delete method on it. That method accepts a memcached key. As you might remember, we previously saw that the elements of our key array (as used by the helpful cache method) were joined by slashes and prefixed with controller. Thus, the above works, even though it's not quite as nice as I might have liked. We can see that this is the case in the memcached logs:


<7 delete controller/Person/1 0
>7 DELETED

And, sure enough, we then find that our next invocation of show for person 1 retrieves the information from the database and caches it in memcached.

Conclusion

Caching has long been an excellent way to improve performance in the computer industry, from the hardware level all the way up to operating systems and applications. Rails programmers have incorporated memcached into their applications over the last few years, but I believe that its complete integration in version 2.1 will make it even easier, and more widespread, to find memcached-enabled Rails applications. As you can see, adding just a few lines of configuration and application code can speed up an application by many times, without having to sacrifice accuracy.

Reuven M. Lerner, a longtime Web/database developer and consultant, is a PhD candidate in learning sciences at Northwestern University, studying on-line learning communities. He recently returned (with his wife and three children) to their home in Modi'in, Israel, after four years in the Chicago area.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Thanks for the write up but

Anonymous's picture

Thanks for the write up but i seem to be having a bit of problem when i refresh my browser. I was expecting to see "undefined class/module Person" as stated but instead i get a different error message "undefined method `cache' for #

Good article.

bggy's picture

Thanks for the nice write-up!

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState