Content Caching in Rails

Scott Laird

http://scottstuff.net

Introduction

Three different caches

Page Cache

Page Cache 2

Page Cache Example

  class ArticleController < ApplicationController
    cache_sweeper :article_sweeper
    caches_page :index, :permalink, :category, :view_page
    
    def index
      ...
    end
    
    def permalink
      ...
    end
    
    ...
  end

Page Cache Sweeper

class BlogSweeper < ActionController::Caching::Sweeper
  observe Article, Comment
    
  def after_save(record)
    expire_page(:controller => 'article', :action => 'index')
    expire_page(:controller => 'article', :action => 'view_page', 
               :id => record.id)
    record.categories.each do |category|
     expire_page(:controller => 'article', :action => 'category', 
                  :id => category)
     end
   end
end

Page Cache .htaccess

RewriteRule ^$ index.html [QSA]
RewriteRule ^([^.]+)$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

Page Cache 3

Page Cache Problems

Page Cache: Query strings

Page Cache: Authentication

Page Cache: Multiple paths

Page Cache: Complex sweeping

Page Cache: Complex sweeping with Typo

When an Article changed, we needed to invalidate:

Page Cache: Sweeping 3

Page Cache: Scaling

Page Cache: Summary

Action Cache

Action Cache: example

class ArticleController < ApplicationController
  cache_sweeper :article_sweeper
  caches_action :index, :permalink, :category, :view_page
  
  def index
    ...
  end
  
  def permalink
    ...
  end
  
  ...
end

Action Cache part 2

Action Cache: problems

Action Cache: invalidation

Action Cache: query strings

Fragment Cache

Fragment Cache: example

From the Sparklines code in Typo:

fragment_cache = read_fragment(fragmentname)

if(not fragment_cache)
  fragment_cache = Sparklines.plot(ary,params)
  write_fragment(fragmentname,fragment_cache)
end

send_data(fragment_cache,
          :disposition => 'inline',
          :type => 'image/png')

Fragment Cache: backends

Fragment Cache: summary

Recommendations