rack::cache snippets

How to setup and use Rack::Cache with Rails

Tagged rack, rails, cache, rack::cache  Languages ruby

Add Rack::Cache to your Gemfile:

gem 'rack-cache', :require => 'rack/cache'

Configure Rails to use Rack::Cache by adding this to config/environment.rb:

config.middleware.use Rack::Cache,
  :verbose => true,
  :metastore   => 'file:/var/cache/rack/meta',
  :entitystore => 'file:/var/cache/rack/body'

This will cache content in /var/cache/rack/meta. Check the documentation for instructions on how to use memcached.

Verify configuration

Verify the configuration:

rake middleware

You should see something like this:

use Rack::Cache, {:metastore=>"file:/var/cache/rack/meta", :entitystore=>"file:/var/cache/rack/body", :verbose=>true}

Tell Rack::Cache to cache your content

Tell Rack to cache data by calling expires_in from your controller's action or from a Rails filter:

expires_in 5.minutes, :public => true

Rails sets cache-control to private by default, Rack::Cache needs public content.

Don't cache private data

Note that you must be careful not to cache private data when a user is signed in. In this case you should set the Cache-Control header to private or completely avoid using expires_in:

fail "Don't cache private data" if signed_in?
expires_in 5.minutes, :public => true

Verify caching

With verbose set to true, you'll see this in the logs:

[cache] trace: cache miss
[cache] trace: fetching response from backend
[cache] trace: store backend response in cache (ttl: 300s)
[cache] trace: storing response in cache
[cache] trace: delivering response ...
[cache] trace: cache hit (ttl: 276s)
[cache] trace: delivering response ...

Caching more than one type of content

Make sure you cache e.g. HTML and JSON separately. You could use the Vary HTTP header to achieve this:

response.headers['Vary'] = 'Accept'

The problem is that almost every browser version has a unique Accept header.

Instead you could try using the cache_key configuration option to generate a cache key per content type:

:cache_key  =>  lambda { |request|
  Rack::Cache::Key.new(request).generate + ":jebus"

You could also add the format request parameter to the URL, e.g. /json-and-html?format=html

Advanced configuration

In production you probably want to disallow reloading of content. This can be done with the following configuration options:

config.middleware.use Rack::Cache,
  :metastore   => 'file:/var/cache/rack/meta',
  :entitystore => 'file:/var/cache/rack/body',
  :allow_reload     => false,
  :allow_revalidate => false,

Read the source (options.rb) for more advanced configuration options (ignore_headers, private_headers, etc).


HTTP RFC - Cache-Control Rack::Cache options documentation Rails expires_in documentation HTTP Vary Header

How to use Rack::Cache with Rails 3

Tagged rack::cache, rails3, rails  Languages ruby

In Gemfile:

# Rails 3 includes rack-cache, so this is not needed.
gem 'rack-cache'

In config/environments/production.rb:

config.action_dispatch.rack_cache = {
    :metastore => "file:tmp/rack-cache/meta",
    :entitystore => "file:tmp/rack-cache/body",
    :verbose => true, # print debug information to log
    :allow_reload     => false, # allow user to force reload?
    :allow_revalidate => false, # allow user to force reload?
    :private_headers  => ['Cookie', 'Set-Cookie', 'Authorization'], # don't store these in the cache!
    :cache_key  =>  lambda { |request|
      Rack::Cache::Key.new(request).generate + ":jebus"
    }, # customize the cache key to make boss happy
    #:metastore   => 'memcached://localhost:11211/meta',
    #:entitystore   => 'memcached://localhost:11211/body'

In app/controllers/application_controller.rb:

class ApplicationController < ActionController::Base
  def cache_for(ttl = 5.minutes)
    response.headers['Vary'] = 'Accept' # We want to cache JSON and HTML separately! NOTE this header varies between browsers, so not optimal...
    expires_in(ttl, :public => true) unless signed_in? # We don't want to cache content if user is signed in!

Now you can cache all you want:

def index
  @data = BigData.all

Reference: * Rack::Cache on Github * Vary Header for RESTful Applications