1 Caching with Rails: An overview
2 ===============================
4 Everyone caches. This guide will teach you what you need to know about
5 avoiding that expensive round-trip to your database and returning what you
6 need to return to those hungry web clients in the shortest time possible.
10 This is an introduction to the three types of caching techniques that Rails
11 provides by default without the use of any third party plugins.
13 To get started make sure config.action_controller.perform_caching is set
14 to true for your environment. This flag is normally set in the
15 corresponding config/environments/*.rb and caching is disabled by default
16 there for development and test, and enabled for production.
19 -----------------------------------------------------
20 config.action_controller.perform_caching = true
21 -----------------------------------------------------
25 Page caching is a Rails mechanism which allows the request for a generated
26 page to be fulfilled by the webserver, without ever having to go through the
27 Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
28 applied to every situation (such as pages that need authentication) and since
29 the webserver is literally just serving a file from the filesystem, cache
30 expiration is an issue that needs to be dealt with.
32 So, how do you enable this super-fast cache behavior? Simple, let's say you
33 have a controller called ProductsController and a 'list' action that lists all
37 -----------------------------------------------------
38 class ProductsController < ActionController
45 -----------------------------------------------------
47 The first time anyone requests products/index, Rails will generate a file
48 called index.html and the webserver will then look for that file before it
49 passes the next request for products/index to your Rails application.
51 By default, the page cache directory is set to Rails.public_path (which is
52 usually set to RAILS_ROOT + "/public") and this can be configured by
53 changing the configuration setting ActionController::Base.page_cache_directory. Changing the
54 default from /public helps avoid naming conflicts, since you may want to
55 put other static html in /public, but changing this will require web
56 server reconfiguration to let the web server know where to serve the
59 The Page Caching mechanism will automatically add a .html exxtension to
60 requests for pages that do not have an extension to make it easy for the
61 webserver to find those pages and this can be configured by changing the
62 configuration setting ActionController::Base.page_cache_extension.
64 In order to expire this page when a new product is added we could extend our
65 example controler like this:
68 -----------------------------------------------------
69 class ProductsController < ActionController
76 expire_page :action => :list
80 -----------------------------------------------------
82 If you want a more complicated expiration scheme, you can use cache sweepers
83 to expire cached objects when things change. This is covered in the section on Sweepers.
85 [More: caching paginated results? more examples? Walk-through of page caching?]
89 One of the issues with Page Caching is that you cannot use it for pages that
90 require to restrict access somehow. This is where Action Caching comes in.
91 Action Caching works like Page Caching except for the fact that the incoming
92 web request does go from the webserver to the Rails stack and Action Pack so
93 that before filters can be run on it before the cache is served, so that
94 authentication and other restrictions can be used while still serving the
95 result of the output from a cached copy.
97 Clearing the cache works in the exact same way as with Page Caching.
99 Let's say you only wanted authenticated users to edit or create a Product
100 object, but still cache those pages:
103 -----------------------------------------------------
104 class ProductsController < ActionController
106 before_filter :authenticate, :only => [ :edit, :create ]
113 expire_page :action => :list
114 expire_action :action => :edit
120 -----------------------------------------------------
122 And you can also use :if (or :unless) to pass a Proc that specifies when the
123 action should be cached. Also, you can use :layout => false to cache without
124 layout so that dynamic information in the layout such as logged in user info
125 or the number of items in the cart can be left uncached. This feature is
126 available as of Rails 2.2.
129 [More: more examples? Walk-through of Action Caching from request to response?
130 Description of Rake tasks to clear cached files? Show example of
131 subdomain caching? Talk about :cache_path, :if and assing blocks/Procs
136 Life would be perfect if we could get away with caching the entire contents of
137 a page or action and serving it out to the world. Unfortunately, dynamic web
138 applications usually build pages with a variety of components not all of which
139 have the same caching characteristics. In order to address such a dynamically
140 created page where different parts of the page need to be cached and expired
141 differently Rails provides a mechanism called Fragment Caching.
143 Fragment Caching allows a fragment of view logic to be wrapped in a cache
144 block and served out of the cache store when the next request comes in.
146 As an example, if you wanted to show all the orders placed on your website
147 in real time and didn't want to cache that part of the page, but did want
148 to cache the part of the page which lists all products available, you
149 could use this piece of code:
152 -----------------------------------------------------
153 <% Order.find_recent.each do |o| %>
154 <%= o.buyer.name %> bought <% o.product.name %>
158 All available products:
159 <% Product.find(:all).each do |p| %>
160 <%= link_to p.name, product_url(p) %>
163 -----------------------------------------------------
165 The cache block in our example will bind to the action that called it and is
166 written out to the same place as the Action Cache, which means that if you
167 want to cache multiple fragments per action, you should provide an action_suffix to the cache call:
170 -----------------------------------------------------
171 <% cache(:action => 'recent', :action_suffix => 'all_products') do %>
172 All available products:
173 -----------------------------------------------------
175 and you can expire it using the expire_fragment method, like so:
178 -----------------------------------------------------
179 expire_fragment(:controller => 'producst', :action => 'recent', :action_suffix => 'all_products)
180 -----------------------------------------------------
182 [More: more examples? description of fragment keys and expiration, etc? pagination?]
186 Cache sweeping is a mechanism which allows you to get around having a ton of
187 expire_{page,action,fragment} calls in your code by moving all the work
188 required to expire cached content into a ActionController::Caching::Sweeper
189 class that is an Observer and looks for changes to an object via callbacks,
190 and when a change occurs it expires the caches associated with that object n
191 an around or after filter.
193 Continuing with our Product controller example, we could rewrite it with a
194 sweeper such as the following:
197 -----------------------------------------------------
198 class StoreSweeper < ActionController::Caching::Sweeper
199 observe Product # This sweeper is going to keep an eye on the Post model
201 # If our sweeper detects that a Post was created call this
202 def after_create(product)
203 expire_cache_for(product)
206 # If our sweeper detects that a Post was updated call this
207 def after_update(product)
208 expire_cache_for(product)
211 # If our sweeper detects that a Post was deleted call this
212 def after_destroy(product)
213 expire_cache_for(product)
217 def expire_cache_for(record)
218 # Expire the list page now that we added a new product
219 expire_page(:controller => '#{record}', :action => 'list')
222 expire_fragment(:controller => '#{record}', :action => 'recent', :action_suffix => 'all_products')
225 -----------------------------------------------------
227 Then we add it to our controller to tell it to call the sweeper when certain
228 actions are called. So, if we wanted to expire the cached content for the
229 list and edit actions when the create action was called, we could do the
233 -----------------------------------------------------
234 class ProductsController < ActionController
236 before_filter :authenticate, :only => [ :edit, :create ]
239 cache_sweeper :store_sweeper, :only => [ :create ]
244 expire_page :action => :list
245 expire_action :action => :edit
251 -----------------------------------------------------
253 [More: more examples? better sweepers?]
257 Query caching is a Rails feature that caches the result set returned by each
258 query so that if Rails encounters the same query again for that request, it
259 will used the cached result set as opposed to running the query against the
265 -----------------------------------------------------
266 class ProductsController < ActionController
268 before_filter :authenticate, :only => [ :edit, :create ]
271 cache_sweeper :store_sweeper, :only => [ :create ]
279 # Run the same query again
284 expire_page :action => :list
285 expire_action :action => :edit
291 -----------------------------------------------------
293 In the 'list' action above, the result set returned by the first
294 Product.find(:all) will be cached and will be used to avoid querying the
295 database again the second time that finder is called.
297 Query caches are created at the start of an action and destroyed at the end of
298 that action and thus persist only for the duration of the action.
302 Rails provides different stores for the cached data for action and fragment
303 caches. Page caches are always stored on disk.
305 The cache stores provided include:
307 1) Memory store: Cached data is stored in the memory allocated to the Rails
308 process, which is fine for WEBrick and for FCGI (if you
309 don't care that each FCGI process holds its own fragment
310 store). It's not suitable for CGI as the process is thrown
311 away at the end of each request. It can potentially also
312 take up a lot of memory since each process keeps all the
316 -----------------------------------------------------
317 ActionController::Base.cache_store = :memory_store
318 -----------------------------------------------------
320 2) File store: Cached data is stored on the disk, this is the default store
321 and the default path for this store is: /tmp/cache. Works
322 well for all types of environments and allows all processes
323 running from the same application directory to access the
328 -----------------------------------------------------
329 ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
330 -----------------------------------------------------
332 3) DRb store: Cached data is stored in a separate shared DRb process that all
333 servers communicate with. This works for all environments and
334 only keeps one cache around for all processes, but requires
335 that you run and manage a separate DRb process.
338 -----------------------------------------------------
339 ActionController::Base.cache_store = :drb_store, "druby://localhost:9192"
340 -----------------------------------------------------
342 4) MemCached store: Works like DRbStore, but uses Danga's MemCache instead.
343 Requires the ruby-memcache library:
344 gem install ruby-memcache.
347 -----------------------------------------------------
348 ActionController::Base.cache_store = :mem_cache_store, "localhost"
349 -----------------------------------------------------
351 5) Custom store: You can define your own cache store (new in Rails 2.1)
354 -----------------------------------------------------
355 ActionController::Base.cache_store = MyOwnStore.new("parameter")
356 -----------------------------------------------------
360 Along with the built-in mechanisms outlined above, a number of excellent
361 plugins exist to help with finer grained control over caching. These include
362 Chris Wanstrath's excellent cache_fu plugin (more info here:
363 http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver's
364 interlock plugin (more info here:
365 http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both
366 of these plugins play nice with memcached and are a must-see for anyone
367 seriously considering optimizing their caching needs.