Tip of the Day: Ruby on Rails caching
Posted by JP Wed, 09 May 2007 17:31:00 GMT
Creating a web application is one thing. Deploying it is another.
On a shared server, resources such as memory and processing time are monitored closely so that a single application doesn't gobble up all available resources. Failure to do so can result in your hosting account being suspended, depending on your hosting provider.
Although Rails is relatively efficient, it's still not comparable to having the web server throw back a cached static page. Doing so bypasses the Ruby interpreter and relieves the database server altogether.
And it proved quite useful, as my World of Warcraft Gemfinder got picked up by World of Warcraft Insider, a well-read site in the gaming community. The mention of my site on that blog led to a peak of almost 40000 page views in a single day. Good thing I had turned on the application's caching the week before that.
Rails caching can work on three different levels. You can cache entire pages, which you can easily do by adding this to a controller:
class CutGemController < ApplicationController
...
caches_page :list
...
end
In this example, the 'list' page will be cached along with the template. Expire your cache with the expire_page command. Make sure you do so in every action which modifies the generated page. If you don't do it, your site will serve an outdated page.
If you still need the template to be dynamic, you can cache just the action. The template will still be rendered dynamically, which is useful if you need dynamic content in the sidebar or elsewhere in your template.
Finally, you can cache page fragments, which is useful for when your application is more dynamic, but you still have parts of the page which are expensive to compute, yet seldom change.
This post isn't a howto and doesn't contain detailed instructions on how to cache using RoR: plenty of sites already explain this in greater details.
I merely wanted to get this point across: Use caching, it's easy, and you never know when you site will get hit by a tsunami of requests. It's a matter of being a good neighbor to the other sites hosted on your server and to keep your site snappy, smooth and responsive.

