Caching with Rails: An overview
This guide will teach you what you need to know about avoiding that expensive round-trip to your database and returning what you need to return to the web clients in the shortest time possible.
After reading this guide, you should be able to use and configure:
- Page, action, and fragment caching
- Alternative cache stores
- Conditional GET support
This is an introduction to the three types of caching techniques that Rails provides by default without the use of any third party plugins.
To start playing with testing you’ll want to ensure that is set to if you’re running in development mode. This flag is normally set in the corresponding and caching is disabled by default for development and test, and enabled for production.
config.action_controller.perform_caching = true
Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. apache or nginx), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can’t be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.
So, how do you enable this super-fast cache behavior? Simple, let’s say you have a controller called and an action that lists all the products
class ProductsController < ActionControllercaches_page :index def index @products = Products.all end
The first time anyone requests , Rails will generate a file called and the webserver will then look for that file before it passes the next request for to your Rails application.
By default, the page cache directory is set to (which is usually set to the folder) and this can be configured by changing the configuration setting . Changing the default from helps avoid naming conflicts, since you may want to put other static html in , but changing this will require web server reconfiguration to let the web server know where to serve the cached files from.
The Page Caching mechanism will automatically add a extension to requests for pages that do not have an extension to make it easy for the webserver to find those pages and this can be configured by changing the configuration setting .
In order to expire this page when a new product is added we could extend our example controller like this:
class ProductsController < ActionControllercaches_page :index def index @products = Products.all end def create expire_page :action => :index end
If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers.
Note: Page caching ignores all parameters. For example will be written out to the filesystem as with no reference to the parameter. Thus, if someone requests later, they will get the cached first page. Be careful when page caching GET parameters in the URL!
INFO: Page caching runs in an after filter. Thus, invalid requests won’t generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows authentication and other restriction to be run while still serving the result of the output from a cached copy.
Clearing the cache works in the exact same way as with Page Caching.
Let’s say you only wanted authenticated users to call actions on .
class ProductsController < ActionControllerbefore_filter :authenticate caches_action :index def index @products = Product.all end def create expire_action :action => :index end
You can also use (or ) to pass a Proc that specifies when the action should be cached. Also, you can use to cache without layout so that dynamic information in the layout such as logged in user info or the number of items in the cart can be left uncached. This feature is available as of Rails 2.2.
You can modify the default action cache path by passing a option. This will be passed directly to . This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance.
Finally, if you are using memcached, you can also pass . In fact, all parameters not used by are sent to the underlying cache store.
INFO: Action caching runs in an after filter. Thus, invalid requests won’t generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently Rails provides a mechanism called Fragment Caching.
Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.
As an example, if you wanted to show all the orders placed on your website in real time and didn’t want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
<% Order.find_recent.each do |o| >
<= o.buyer.name > bought < o.product.name >
< end %>
<% cache do >
All available products:
< Product.all.each do |p| >
<= link_to p.name, product_url(p) >
< end >
< end %>
The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an to the cache call:
<% cache(:action => ‘recent’, :action_suffix => ‘all_products’) do %>
All available products:
and you can expire it using the method, like so:
expire_fragment(:controller => ‘products’, :action => ‘recent’, :action_suffix => ‘all_products’)
If you don’t want the cache block to bind to the action that called it, You can also use globally keyed fragments by calling the method with a key, like so:
<% cache(‘all_available_products’) do >
All available products:
< end %>
This fragment is then available to all actions in the using the key and can be expired the same way:
Cache sweeping is a mechanism which allows you to get around having a ton of calls in your code. It does this by moving all the work required to expire cached content into an subclass. This class is an observer and looks for changes to an object via callbacks, and when a change occurs it expires the caches associated with that object in an around or after filter.
Continuing with our Product controller example, we could rewrite it with a sweeper like this:
class ProductSweeper < ActionController::Caching::Sweeper
observe Product # This sweeper is going to keep an eye on the Product model
- If our sweeper detects that a Product was created call this
- If our sweeper detects that a Product was updated call this
- If our sweeper detects that a Product was deleted call this
- Expire the index page now that we added a new product
expire_page(:controller => ‘products’, :action => ‘index’)
- Expire a fragment
You may notice that the actual product gets passed to the sweeper, so if we were caching the edit action for each product, we could add an expire method which specifies the page we want to expire:expire_action(:controller => ‘products’, :action => ‘edit’, :id => product)
Then we add it to our controller to tell it to call the sweeper when certain actions are called. So, if we wanted to expire the cached content for the list and edit actions when the create action was called, we could do the following:
class ProductsController < ActionControllerbefore_filter :authenticate caches_action :index cache_sweeper :product_sweeper def index @products = Product.all end
Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
class ProductsController < ActionControllerdef index
- Run a find query
@products = Product.all
- Run the same query again
@products = Product.all
The second time the same query is run against the database, it’s not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it’s pulled from memory.
However, it’s important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. If you’d like to store query results in a more persistent fashion, you can in Rails by using low level caching.
Rails provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk.
Rails 2.1 and above provide which can be used to cache strings. Some cache store implementations, like , are able to cache arbitrary Ruby objects, but don’t count on every cache store to be able to do that.
The default cache stores provided with Rails include:
1) : A cache store implementation which stores everything into memory in the same process. If you’re running multiple Ruby on Rails server processes (which is the case if you’re using mongrel_cluster or Phusion Passenger), then this means that your Rails server process instances won’t be able to share cache data with each other. If your application never performs manual cache item expiry (e.g. when you‘re using generational cache keys), then using is ok. Otherwise, consider carefully whether you should be using this cache store.
is not only able to store strings, but also arbitrary Ruby objects.
is not thread-safe. Use instead if you need thread-safety.
ActionController::Base.cache_store = :memory_store
2) : Cached data is stored on the disk, this is the default store and the default path for this store is . Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If does not exist, the default store becomes .
ActionController::Base.cache_store = :file_store, “/path/to/cache/directory”
3) : Cached data is stored in a separate shared DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process.
ActionController::Base.cache_store = :drb_store, “druby://localhost:9192”
4) : Works like , but uses Danga’s instead. Rails uses the bundled gem by default. This is currently the most popular cache store for production websites.
- Clustering and load balancing. One can specify multiple memcached servers, and will load balance between all available servers. If a server goes down, then will ignore it until it goes back online.
- Time-based expiry support. See and the option.
- Per-request in memory cache for all communication with the server(s).
It also accepts a hash of additional options:
- : specifies a string that will automatically be prepended to keys when accessing the memcached store.
- : a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
- : a boolean value that adds thread safety to read/write operations – it is unlikely you’ll need to use this option as the Rails threadsafe! method offers the same functionality.
The read and write methods of the accept an options hash too. When reading you can specify to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to before being returned to you.)
When writing to the cache it is also possible to specify means the value is not passed to before being stored in the cache (by default this is false).
The write method also accepts an flag which determines whether the memcached add (when true) or set (when false) method is used to store the item in the cache and an option that specifies the time-to-live for the cached item in seconds.
ActionController::Base.cache_store = :mem_cache_store, “localhost”
5) : Like but thread-safe.
ActionController::Base.cache_store = :synchronized_memory_store
6) : Works just like the regular but uses GZip to decompress/compress on read/write.
ActionController::Base.cache_store = :compressed_mem_cache_store, “localhost”
7) Custom store: You can define your own cache store (new in Rails 2.1).
ActionController::Base.cache_store = MyOwnStore.new(“parameter”)
NOTE: can be used in place of in your block in
In addition to all of this, Rails also adds the method that generates a key using the class name, and timestamp (if available).
You can access these cache stores at a low level for storing queries and other objects. Here’s an example:
Rails.cache.read(“city”) # => nil
Rails.cache.read(“city”) # => “Duckburgh”
Conditional GET support
Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn’t changed since the last request and can be safely pulled from the browser cache.
They work by using the and headers to pass back and forth both a unique content identifier and the timestamp of when the content was last changed. If the browser makes a request where the content identifier (etag) or last modified since timestamp matches the server’s version then the server only needs to send back an empty response with a not modified status.
It is the server’s (i.e. our) responsibility to look for a last modified timestamp and the if-none-match header and determine whether or not to send back the full response. With conditional-get support in Rails this is a pretty easy task:
class ProductsController < ApplicationControllerdef show @product = Product.find(params[:id])
- If the request is stale according to the given timestamp and etag value
- (i.e. it needs to be processed again) then execute this block
if stale?(:last_modified => @product.updated_at.utc, :etag => @product)
respond_to do |wants|
- … normal response processing
- If the request is fresh (i.e. it’s not modified) then you don’t need to do
- anything. The default render checks for this using the parameters
- used in the previous call to stale? and will automatically send a
- :not_modified. So that’s it, you’re done.
If you don’t have any special response processing and are using the default rendering mechanism (i.e. you’re not using respond_to or calling render yourself) then you’ve got an easy helper in fresh_when:
class ProductsController < ApplicationController
- This will automatically send back a :not_modified if the request is fresh,
- and will render the default template (product.*) if it’s stale.
- Scaling Rails Screencasts
- RailsEnvy, Rails Caching Tutorial, Part 1
- RailsEnvy, Rails Caching Tutorial, Part 2
- ActiveSupport::Cache documentation
- Rails 2.1 integrated caching tutorial
- May 02, 2009: Formatting cleanups
- April 26, 2009: Clean up typos in submitted patch
- April 1, 2009: Made a bunch of small fixes
- February 22, 2009: Beefed up the section on cache_stores
- December 27, 2008: Typo fixes
- November 23, 2008: Incremental updates with various suggested changes and formatting cleanup
- September 15, 2008: Initial version by Aditya Chadha