viphat / til

Today I Learned
http://notes.viphat.work
0 stars 1 forks source link

[PluralSight] - Rails 4.1 Performance Fundamentals - Module 4 - Browser Caching - Max Ages #254

Open viphat opened 6 years ago

viphat commented 6 years ago

expires_in

class HomeController < ApplicationController
  def index
    @courses = Course.order(:id).page(params[:page])
    expires_in 10.minutes
  end
end

So if a single user goes to the same page twice within ten minutes, his browser won't even bother hitting the server to get the page. (Hitting Shift + Refresh can bypass Max Ages)

Disable Middleware that modify the Body

Turn off Rack-Mini-Profiler because it disables caching and ETags in response header. New Relic changes the body on each request causes automatic ETags to be different every time. Fix: Move browser monitoring injection after ETag:

# config/newrelic.yml
browser_monitoring:
  auto_instrument: false

# config/application.rb
require 'new_relic/rack/browswer_monitoring'
config.middleware.delete 'Rack::ETag'
config.middleware.use 'NewRelic::Rack::BrowserMonitoring'
config.middleware.use 'Rack::ETag'

Declarative ETags and the ETagger Gem

Some parts of the response are independent of updated_at:

-> Users might see old flash messages or Users might see some other user's content after logout & login, Users might be unable to submit forms after logout & login, Users might see the right content with stale HTML or CSS.

Using ETagger gem to solve these problems

class ApplicationController < ActionController::Base
  etag { Hash[session] }
  etag { flash }
  etag { current_user.try(:id }
  etag { current_user.try(:name) }
  etag { current_user.try(:email) }
end

Reset all ETags on each deploy (To reset ETags when HTML or CSS changes):

# config/application.rb
ENV['RAILS_CACHE_ID'] = `git rev-parse --short HEAD`.strip