Top Banner
Caching in Rails Vysakh Sreenivasan
23

Caching in rails

Jan 28, 2018

Download

Software

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Caching in rails

Caching in RailsVysakh Sreenivasan

Page 2: Caching in rails

Only 2 hard Problems in CS

● Naming

● Cache invalidation

Page 3: Caching in rails

Caching in a web app● Prevent hitting databases.

● Cache the html responses.

● Help browser implement caching.

Page 4: Caching in rails

Before implementing caching we need a cache server

Page 5: Caching in rails

Memcached is the popular cache server

sudo apt-get install memcached

Page 6: Caching in rails

Before implementing caching in Rails we need to configure

Page 7: Caching in rails

config.action_controller.perform_caching = true

Page 8: Caching in rails

Using memcached with Rails 4.0

● gem ‘dalli’

● config.cache_store = :mem_cache_store

Page 9: Caching in rails

Lets get to the implementation

Page 10: Caching in rails

#1 Model level caching

Page 11: Caching in rails

Rails.cache.fetch

● First time, it can’t fetch a cache, so it will write a cache.

● Then it reads those caches.

Page 12: Caching in rails

Rails.cache.delete

● When passed an argument, it deletes the specific cache.

● You can clear caches in hooks like after_save

Page 13: Caching in rails

You can also use this to cache API results

Page 14: Caching in rails

#2 Fragment caching

Page 15: Caching in rails

<% cache @post do %>

<h3> <%= @post.title %> </h3>

<% end %>

cache_key: views/posts/1-201505056193031061005000/bea67108094918eeba42cd4a6e786901

based on @post.cache_key which is based on updated_at

md5 hash based on the view’s contents

Page 16: Caching in rails

Cache key changes when

● the record is updated -> a new cache_key is formed

● the view is changed -> a new md5 key is generated

The old keys will be there, which will be removed

automatically by memcached

Page 17: Caching in rails

#3 http caching

Page 18: Caching in rails

e-tag & 304 not modified

Page 19: Caching in rails

fresh_when(@post)

# or

fresh_when(etag: @post , last_modified: @post.updated_at)

based on @post.cache_key which is based on updated_at

Page 20: Caching in rails

if stale?(@post)

respond_to do |f|

end

end

Alternate syntax. Especially when using respond_to

Page 21: Caching in rails

def show

@post = Post.first

expires_in 5.minutes

end

Cache control: max_age

Page 22: Caching in rails

Recap1 Model level

● Rails.cache.fetch

● Rails.cache.delete

2 Fragment

<% cache @post do %>

<% end %>

3. etags

if stale?(@post)

Page 23: Caching in rails

Resources

● Docs: http://guides.rubyonrails.org/caching_with_rails.html

● Railscasts episodes on http caching, low level caching,

cache digests, dalli gem.