@MQuy
Full Stack Web Developer at RingMD

Topic: Caching on Rails

Why Using Caching?



  • Your app becomes faster for the users.

  • The cost is lower than non-caching system.

Caching Strategies


  1. HTTP Caching

  2. Page Caching

  3. Fragment Caching

  4. Low-level Caching

1. HTTP Caching


1. Http Caching

class HomeController < ApplicationController

  def index
    @schedules = Schedule.all
    if stale? @schedules
      respond_to do |format|
        format.html
      end
    end
  end
end

2. Page Caching

 

2. Page Caching

class HomeController < ApplicationController
  caches_page :about
  
  def about; end
end

  • Url query params will be ignored
/feedback?search=hello => /feedback

3. Fragment Caching

 

3. Fragment Caching


3. Fragment Caching

class BlogController < ApplicationController
  def index
    @articles = Article.publish
  end
end
%h2 Blog
.grid_11
  - cache @articles do
    - @articles do |article|
      %article
        .date
          .month= article.month
          .year= article.year
        %div
          .title= article.title
          .content= article.content
        %div
          - cache @article.comments do |comment|
            %span= comment.name
.grid_4
  %h4 Tìm kiếm

4. Low-level Caching

class Article < ActiveRecord::Base
  def self.cached_published
    Rails.cache.fetch [name, "publish"] do
      published.to_a
    end
  end
end

  • Rails.cache is instance of Cache Stores through  cache_store
  • Can access anywhere

4. Low-level Caching

  • Clear cache means that we clear rails session.
  • Can not do operation like: list all keys, get matched...
  • Not OOP

class Article < ActiveRecord::Base
  def self.cached_published
    Rails.cache.fetch [name, "publish"] do
      published.to_a
    end
  end

  def flush_cache
    Rails.cache.delete([self.class.name, "publish"])
  end
end



4. Low-Level Caching

class Article < ActiveRecord::Base 
  def self.cached_published
    Rails.cache.fetch [name, "publish"] do 
      published.to_a 
    end
  end

  def flush_cache
    Rails.cache.delete([self.class.name, "publish"])
  end
end
Acticle.cached.published
Article.delete_cached.published

Gem Munna

  • Built on top of Rails.cache

  • Support cache analytics

  • Clear cache without effect on other rails caches.

class User < ActionRecord::Base
  def self.list_vip_users
    cached {
      where(:type => 'vip')
        .order('rank')
    }
  end
end
Check on Github            

Caching Strategies


  1. HTTP Caching

  2. Page Caching

  3. Fragment Caching

  4. Low-level Caching

Best Practices

  • Use HTTP caching as much as you can

  • Use Russian doll approach when rendering complex view

  • Use Rails.cache or Munna inside model to improve performance

  • Set expiring cache key for everything




Question?

Server Caching

By Minh Quy

Server Caching

  • 1,726