Posted by
gdurelle
on
July 25, 2010
Using the cache will speed up your application response time a lot. In fact, when people will request your pages, rails won't be requested, apache will serve the cached pages, thus double advantage : Faster pages response time Lower charge on your server
Caching is really simple, see page caching.
In your production.rb file add :
config.action_controller.perform_caching = true
config.action_controller.cache_store = :file_store, RAILS_ROOT+"/tmp/cache/"
config.action_controller.page_cache_directory = RAILS_ROOT+"/public/cache/"
And in the controllers where you want to activate page caching just add :
caches_page :index, :help, :home, :faq
And that's it ! Next time you'll access the cached pages without requesting your rails server.
For more advanced info just read the guide :

Comments
Also use something like fresh_when which sets HTTP headers with good last_modified and ETag support. Using this and you can often skip the view rendering.
Set a Expires HTTP header and you can prevent requests to your server. Put this app in front of something like Varnish (setup by default on Heroku) and different clients will get the non-expired page causing nobody to hit your page.
Page/action/fragment caching is nice. But often simply good HTTP headers can prevent a lot of unnecessary processing.
Use Memcache and NoSQL storages for ActiveRecord data sets and collections can be identified by unique key (Rails.cache.delete doesn't support of many cache storage)
I didn't mentionned it, but at some point Sweepers will be mandatory...
mkdir app/sweepers/
touch faq_sweeper.rb
def after_save, def after_destroy, def expire_cache, def expire_fragment
expire_cache(...)
environment.rb :
config.load_paths << "#{RAILS_ROOT}/app/sweppers"
Can sweepers be considered as best practice ? You do not need it in most of apps... my cached pages are erased at each deployement...
Sorry if you try to read last comment... ;)
Caching, and especially when it comes to invalidation, makes your app design more complex and hard to maintain. It shouldn't be the first thing you need to worry about during the slowdowns. The reality is that in most cases your app won't need any fine tuning at all either because its life cycle has come to an end or because the traffic is low. It's way better to focus on the goal and deliver fast than spend nights debugging weird problems (why do I update the profile, but others see no changes?).
Often people attempt to mask the code design inefficiencies with caching, thinking if the page renders 20 seconds, it's times to start Memcached. In 99% of cases, you need to do quite the opposite -- disable the caches and see what's gone awry.
When you have some static pages accessed a lot of time (homepage, tour pages, etc...) biding your server's resources for people using it should be a minimum.