SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
Rails Caching Secrets: 
From the Edge! 
Michael May | @ohaimmay | austinonrails | 10/28/2014
We’re Hiring! 
Distributed Systems! Ruby C Go Perl JS
We are here 
• Rails caching best practices 
• Dynamic content 
• Edge caching / Content Delivery Networks 
• Edge caching dynamic content with Rails
Rails caching 
• Query/SQL 
• Page/Action (removed from Rails 4 core!) 
• Asset 
• Fragment
Rails caching 
config.action_controller.perform_caching = true
Query caching 
• Automagically done by rails when 
perform_caching = true 
• Not cached between requests! 
• Could just store the query result in a variable
Custom Query Caching 
class Product < MyActiveModel 
def self.latest 
Rails.cache.fetch("latest", expires_in: 8.hours) do 
Product.last(50) 
end 
end 
end
Asset Pipeline 
• Serve static assets from nginx or apache 
• config.serve_static_assets = false 
• Enable Compression* 
• config.assets.compress = true 
• # Rails 4 
config.assets.css_compressor = :yui 
config.assets.js_compressor = :uglifier 
• Asset Digests 
• config.assets.digest = true
Enable Compression* 
Compress all responses with gzip, deflate, etc. 
# in application.rb 
module FastestAppEver 
class Application < Rails::Application 
config.middleware.use Rack::Deflater 
end 
end 
* http://robots.thoughtbot.com/content-compression-with-rack-deflater
$ curl -sv -H “Accept-Encoding: deflate”  
http://fast.mmay.rocks/catz.json 
* Connected to fast.mmay.rocks (127.0.0.1) port 666 
> GET /catz.json HTTP/1.1 
> User-Agent: curl 
> Host: fast.mmay.rocks:666 
> Accept-Encoding: deflate,gzip 
> 
< HTTP/1.1 200 OK 
< Content-Type: application/json; charset=utf-8 
< Vary: Accept-Encoding 
< Content-Encoding: deflate 
< Cache-Control: max-age=60, s-maxage=3600 
< Transfer-Encoding: chunked 
< 
* magical encoded bytes* 
V*.I,)-VRJ-*RN@ ɥEEy%9
Before 
After
Asset Caching 
• Configure an asset host if needed 
• config.action_controller.asset_host = 
ENV[‘FASTLY_CDN_URL'] 
• Cache-Control like a pro 
• config.static_cache_control = 
'public, s-maxage=15552000, maxage=2592000'
HTTP Headers 
RFC 2616 Section 14
Cache-Control HTTP Header 
“public, maxage=2592000, s-maxage=15552000” 
public 
“please cache me” 
maxage=2592000 
“keep me for 30 days” 
s-maxage=15552000 
“PROXIES ONLY! - Keep me for 180 days”
Bonus Cache-Control 
Directives! 
• stale-while-revalidate 
• Serve the cached (stale) content for n seconds while you re-fetche the new content in 
the background 
• Cache-Control: maxage=604800, stale-while-revalidate=3600 
• “Serve stale for up to an hr while you fetch the latest behind the scenes” 
• stale-if-error 
• If the re-fetch fails within n seconds of the content becoming stale, serve the cached 
content 
• Cache-Control: max-age=604800, stale-if-error=86400 
• “Serve stale for up to an hr if origin responds with 4xx or 5xx”
ETags 
• Automatically added into requests with 
Rack::ETag 
• Rails renders response every time to calculate 
etag 
• Override default with Conditional GETs 
• stale?(@model) 
• fresh_when(@model)
The Vary HTTP Header 
• Change response base on the value of another 
HTTP Header 
• Example: 
“Vary: Accept-Encoding” 
Accept-Encoding: gzip => Serve Response A 
Accept-Encoding: deflate => Serve Response B 
• “This response changes for different values of 
the Accept-Encoding header”
Vary Best Practices 
• Please do not Vary on User-Agent 
• There are THOUSANDS of these! 
• Limits caching benefits - almost Impossible to 
serve the same response more than once! 
• In general, avoid varying on anything other than 
content encoding
Dynamic Content 
• Changes are unpredictable! 
• User driven events 
• Can’t just set a Time To Live (TTL) 
• Frequently, but not continuously changing 
• Actually static for short periods of time (we 
can cache static things)!
Dynamic Content Caching 
• Usually don’t (╯°□°)╯︵ ┻━┻ 
• Edge Side Includes (ESI) 
• Dynamic Site Acceleration (DSA)
Fragment Caching 
The rails answer to caching dynamic HTML 
# products/index.html.erb 
<% cache(cache_key_for_products) do %> 
<% Product.all.each do |p| %> 
<%= link_to p.name, product_url(p) %> 
<% end %> 
<% end %> 
# products_controller.rb 
def update 
… 
expire_fragment(cache_key_for_products) 
… 
end
Nested Fragment Caching 
<% cache(cache_key_for_products) do %> 
All available products: 
<% Product.all.each do |p| %> 
<% cache(p) do %> 
<%= link_to p.name, product_url(p) %> 
<% end %> 
<% end %> 
<% end %>
Nested Fragment 
• Tedious 
• Comb through (probably terrible) view code 
• Cache keys are weird 
• “A given key should always return the same content.” - Rails 
• But I like “A given key should always return the most up-to-date 
content” - like a DB primary key 
• Hacking around cache limitations 
• Memcache and wildcard purging
Nested Fragment 
• Garbage left in the cache 
• Defaults writing to disk 
• What about dynamic API caching? 
• “The caching itself happens in the views based 
on partials rendering the objects in question” 
• Take control over your cached data!
Edge Caching 
with things like CDNs
Edge Caches 
• Geographically distributed 
• Highly optimized storage and network 
(nanoseconds count) 
• Move content physically closer to end-users 
• DECREASE LATENCY! 
(speed of light sux lol)
#cachemoney 
• Less requests/bandwidth back to your origin 
server 
• Avoid complex or less efficient strategies 
• Edge Side Includes (ESI) 
• Fragment view caching
Edge caching 
dynamic content
Our approach to dynamic 
content 
• Tag content with Surrogate-Key HTTP headers 
• Programmatically purge (~150ms globally) 
• By Surrogate-Key 
• By resource path 
• Real-time analytics and log streaming 
• Optimize the pieces of the network we control
Tagging responses 
with Surrogate-Keys
class ProductsController < ApplicationController 
# set Cache-Control, strip Set-Cookie 
before_filter :set_cache_control_headers,only [:index,:show] 
def index 
@products = Product.last(10) 
# set Surrogate-Key: products 
set_surrogate_key_header @products.table_key 
respond_with @products 
end 
def show 
@product = Products.find(params[:id]) 
# set Surrogate-Key: product/666 
set_surrogate_key_header @product.record_key 
respond_with @product 
end 
end
Purge on updates
class ProductsController < ApplicationController 
def create 
@product = Product.new(params) 
if @product.save 
# purge Surrogate-Key: products 
@product.purge_all 
render @product 
end 
end 
...
def update 
@product = Product.find(params[:id]) 
if @product.update(params) 
# purge Surrogate-Key: product/666 
@product.purge 
render @product 
end 
end
fastly-rails 
github.com/fastly/fastly-rails
Edge caching in 
practice
Watch out for Set-Cookie! 
• Nothing with a Set-Cookie header is cached (by 
default) 
• Authentication frameworks/middleware might 
inject Set-Cookie after the rails stack removes it 
• Avoid caching pains by knowing when, where, 
and how you use Set-Cookie
Edge scripting with VCL 
(varnish config lang)
VCL 
• Fastly VCL Extensions 
• date/time, geoip, hashing, strings, etc. 
• Do application logic at the CDN edge
URL Rewriting 
• Filter bad requests 
• Normalize or block paths 
• Apache, nginx 
• if ($invalid_referer) { return 403; } 
• You can do this at the edge!
Synthetic Responses
What can we do better? 
• Add better caching defaults? 
• Cache-Control, stale-while-revalidate, stale-if-error 
• Re-use existing rails cache interfaces for edge 
caching? 
• ActiveSupport::Cache::EdgeStore 
• Better integration with HTTP accelerators like 
Varnish?
Takeaways 
• Take advantage of Rails built-in caching 
• Get fancy with Cache-Control directives 
• Use Google PageSpeed Insights (chrome plugin 
adds it to dev tools) 
• Dynamic edge caching is all about the power of 
purge! 
• Similar school of thought to rails action caching
Questions? 
Michael May || @ohaimmay 
cool links: 
fastly-rails - github.com/fastly/fastly-rails 
surrogate keys - fastly.com/blog/surrogate-keys-part-1 
cache-control tutorial - docs.fastly.com/guides/tutorials/cache-control-tutorial 
serve stale cache-control - fastly.com/blog/stale-while-revalidate 
vary header best practices - fastly.com/blog/best-practices-for-using-the-vary-header 
caching like & share buttons - fastly.com/blog/caching-like-and-share-buttons 
pagespeed insights - developers.google.com/speed/pagespeed

Contenu connexe

Tendances

Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014Barney Hanlon
 
DrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalabilityDrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalabilitycherryhillco
 
Aem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAshokkumar T A
 
JSR107 Come, Code, Cache, Compute!
JSR107 Come, Code, Cache, Compute! JSR107 Come, Code, Cache, Compute!
JSR107 Come, Code, Cache, Compute! Payara
 
Configuring Apache Servers for Better Web Perormance
Configuring Apache Servers for Better Web PerormanceConfiguring Apache Servers for Better Web Perormance
Configuring Apache Servers for Better Web PerormanceSpark::red
 
Silverstripe at scale - design & architecture for silverstripe applications
Silverstripe at scale - design & architecture for silverstripe applicationsSilverstripe at scale - design & architecture for silverstripe applications
Silverstripe at scale - design & architecture for silverstripe applicationsBrettTasker
 
Drupal High Availability High Performance 2012
Drupal High Availability High Performance 2012Drupal High Availability High Performance 2012
Drupal High Availability High Performance 2012Amazee Labs
 
A Tale of 2 Systems
A Tale of 2 SystemsA Tale of 2 Systems
A Tale of 2 SystemsDavid Newman
 
Magento performance feat. core Hacks
Magento performance feat. core HacksMagento performance feat. core Hacks
Magento performance feat. core HacksDaniel Niedergesäß
 
Supercharge JavaEE applications using JCache
Supercharge JavaEE applications using JCacheSupercharge JavaEE applications using JCache
Supercharge JavaEE applications using JCachePayara
 
Performance and scalability with drupal
Performance and scalability with drupalPerformance and scalability with drupal
Performance and scalability with drupalRonan Berder
 
Leveraging Docker and CoreOS to provide always available Cassandra at Instacl...
Leveraging Docker and CoreOS to provide always available Cassandra at Instacl...Leveraging Docker and CoreOS to provide always available Cassandra at Instacl...
Leveraging Docker and CoreOS to provide always available Cassandra at Instacl...DataStax
 
Ansible for large scale deployment
Ansible for large scale deploymentAnsible for large scale deployment
Ansible for large scale deploymentKarthik .P.R
 
Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010Jason Ragsdale
 
Load Balancing and Scaling with NGINX
Load Balancing and Scaling with NGINXLoad Balancing and Scaling with NGINX
Load Balancing and Scaling with NGINXNGINX, Inc.
 
Ruby Driver Explained: DataStax Webinar May 5th 2015
Ruby Driver Explained: DataStax Webinar May 5th 2015Ruby Driver Explained: DataStax Webinar May 5th 2015
Ruby Driver Explained: DataStax Webinar May 5th 2015DataStax
 
HTML5 Hacking - Yahoo! Open Hack Day
HTML5 Hacking - Yahoo! Open Hack DayHTML5 Hacking - Yahoo! Open Hack Day
HTML5 Hacking - Yahoo! Open Hack DayTed Drake
 
Squeezing Performance out of Hazelcast
Squeezing Performance out of HazelcastSqueezing Performance out of Hazelcast
Squeezing Performance out of HazelcastHazelcast
 

Tendances (20)

Improve Magento Performance
Improve Magento PerformanceImprove Magento Performance
Improve Magento Performance
 
Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014
 
DrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalabilityDrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalability
 
Aem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAem dispatcher – tips & tricks
Aem dispatcher – tips & tricks
 
JSR107 Come, Code, Cache, Compute!
JSR107 Come, Code, Cache, Compute! JSR107 Come, Code, Cache, Compute!
JSR107 Come, Code, Cache, Compute!
 
Configuring Apache Servers for Better Web Perormance
Configuring Apache Servers for Better Web PerormanceConfiguring Apache Servers for Better Web Perormance
Configuring Apache Servers for Better Web Perormance
 
Silverstripe at scale - design & architecture for silverstripe applications
Silverstripe at scale - design & architecture for silverstripe applicationsSilverstripe at scale - design & architecture for silverstripe applications
Silverstripe at scale - design & architecture for silverstripe applications
 
Drupal High Availability High Performance 2012
Drupal High Availability High Performance 2012Drupal High Availability High Performance 2012
Drupal High Availability High Performance 2012
 
A Tale of 2 Systems
A Tale of 2 SystemsA Tale of 2 Systems
A Tale of 2 Systems
 
Magento performance feat. core Hacks
Magento performance feat. core HacksMagento performance feat. core Hacks
Magento performance feat. core Hacks
 
Supercharge JavaEE applications using JCache
Supercharge JavaEE applications using JCacheSupercharge JavaEE applications using JCache
Supercharge JavaEE applications using JCache
 
Performance and scalability with drupal
Performance and scalability with drupalPerformance and scalability with drupal
Performance and scalability with drupal
 
Leveraging Docker and CoreOS to provide always available Cassandra at Instacl...
Leveraging Docker and CoreOS to provide always available Cassandra at Instacl...Leveraging Docker and CoreOS to provide always available Cassandra at Instacl...
Leveraging Docker and CoreOS to provide always available Cassandra at Instacl...
 
Ansible for large scale deployment
Ansible for large scale deploymentAnsible for large scale deployment
Ansible for large scale deployment
 
Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010Caching: A Guided Tour - 10/12/2010
Caching: A Guided Tour - 10/12/2010
 
Load Balancing and Scaling with NGINX
Load Balancing and Scaling with NGINXLoad Balancing and Scaling with NGINX
Load Balancing and Scaling with NGINX
 
Ruby Driver Explained: DataStax Webinar May 5th 2015
Ruby Driver Explained: DataStax Webinar May 5th 2015Ruby Driver Explained: DataStax Webinar May 5th 2015
Ruby Driver Explained: DataStax Webinar May 5th 2015
 
Performance out
Performance outPerformance out
Performance out
 
HTML5 Hacking - Yahoo! Open Hack Day
HTML5 Hacking - Yahoo! Open Hack DayHTML5 Hacking - Yahoo! Open Hack Day
HTML5 Hacking - Yahoo! Open Hack Day
 
Squeezing Performance out of Hazelcast
Squeezing Performance out of HazelcastSqueezing Performance out of Hazelcast
Squeezing Performance out of Hazelcast
 

Similaire à Rails Caching: Secrets From the Edge

Similaire à Rails Caching: Secrets From the Edge (20)

Accelerating Rails with edge caching
Accelerating Rails with edge cachingAccelerating Rails with edge caching
Accelerating Rails with edge caching
 
Caching your rails application
Caching your rails applicationCaching your rails application
Caching your rails application
 
Mini-Training: To cache or not to cache
Mini-Training: To cache or not to cacheMini-Training: To cache or not to cache
Mini-Training: To cache or not to cache
 
Azure appfabric caching intro and tips
Azure appfabric caching intro and tipsAzure appfabric caching intro and tips
Azure appfabric caching intro and tips
 
More Cache for Less Cash (DevLink 2014)
More Cache for Less Cash (DevLink 2014)More Cache for Less Cash (DevLink 2014)
More Cache for Less Cash (DevLink 2014)
 
NGINX High-performance Caching
NGINX High-performance CachingNGINX High-performance Caching
NGINX High-performance Caching
 
Day 7 - Make it Fast
Day 7 - Make it FastDay 7 - Make it Fast
Day 7 - Make it Fast
 
ASP.NET Scalability - DDD7
ASP.NET Scalability - DDD7ASP.NET Scalability - DDD7
ASP.NET Scalability - DDD7
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cache
 
ASP.NET Scalability - VBUG London
ASP.NET Scalability - VBUG LondonASP.NET Scalability - VBUG London
ASP.NET Scalability - VBUG London
 
Nginx caching
Nginx cachingNginx caching
Nginx caching
 
JCache Using JCache
JCache Using JCacheJCache Using JCache
JCache Using JCache
 
ASP.NET Scalability - NxtGen Oxford
ASP.NET Scalability - NxtGen OxfordASP.NET Scalability - NxtGen Oxford
ASP.NET Scalability - NxtGen Oxford
 
Advanced Apache Cayenne
Advanced Apache CayenneAdvanced Apache Cayenne
Advanced Apache Cayenne
 
Rails caching
Rails cachingRails caching
Rails caching
 
AppFabric Velocity
AppFabric VelocityAppFabric Velocity
AppFabric Velocity
 
ASP.NET Scalability - WebDD
ASP.NET Scalability - WebDDASP.NET Scalability - WebDD
ASP.NET Scalability - WebDD
 
Caching in Kentico 11
Caching in Kentico 11Caching in Kentico 11
Caching in Kentico 11
 
Supercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSupercharging Content Delivery with Varnish
Supercharging Content Delivery with Varnish
 
awergaezrg
awergaezrgawergaezrg
awergaezrg
 

Plus de Fastly

Revisiting HTTP/2
Revisiting HTTP/2Revisiting HTTP/2
Revisiting HTTP/2Fastly
 
Altitude San Francisco 2018: Preparing for Video Streaming Events at Scale
Altitude San Francisco 2018: Preparing for Video Streaming Events at ScaleAltitude San Francisco 2018: Preparing for Video Streaming Events at Scale
Altitude San Francisco 2018: Preparing for Video Streaming Events at ScaleFastly
 
Altitude San Francisco 2018: Building the Souther Hemisphere of the Internet
Altitude San Francisco 2018: Building the Souther Hemisphere of the InternetAltitude San Francisco 2018: Building the Souther Hemisphere of the Internet
Altitude San Francisco 2018: Building the Souther Hemisphere of the InternetFastly
 
Altitude San Francisco 2018: The World Cup Stream
Altitude San Francisco 2018: The World Cup StreamAltitude San Francisco 2018: The World Cup Stream
Altitude San Francisco 2018: The World Cup StreamFastly
 
Altitude San Francisco 2018: We Own Our Destiny
Altitude San Francisco 2018: We Own Our DestinyAltitude San Francisco 2018: We Own Our Destiny
Altitude San Francisco 2018: We Own Our DestinyFastly
 
Altitude San Francisco 2018: Scale and Stability at the Edge with 1.4 Billion...
Altitude San Francisco 2018: Scale and Stability at the Edge with 1.4 Billion...Altitude San Francisco 2018: Scale and Stability at the Edge with 1.4 Billion...
Altitude San Francisco 2018: Scale and Stability at the Edge with 1.4 Billion...Fastly
 
Altitude San Francisco 2018: Moving Off the Monolith: A Seamless Migration
Altitude San Francisco 2018: Moving Off the Monolith: A Seamless MigrationAltitude San Francisco 2018: Moving Off the Monolith: A Seamless Migration
Altitude San Francisco 2018: Moving Off the Monolith: A Seamless MigrationFastly
 
Altitude San Francisco 2018: Bringing TLS to GitHub Pages
Altitude San Francisco 2018: Bringing TLS to GitHub PagesAltitude San Francisco 2018: Bringing TLS to GitHub Pages
Altitude San Francisco 2018: Bringing TLS to GitHub PagesFastly
 
Altitude San Francisco 2018: HTTP Invalidation Workshop
Altitude San Francisco 2018: HTTP Invalidation WorkshopAltitude San Francisco 2018: HTTP Invalidation Workshop
Altitude San Francisco 2018: HTTP Invalidation WorkshopFastly
 
Altitude San Francisco 2018: HTTP/2 Tales: Discovery and Woe
Altitude San Francisco 2018: HTTP/2 Tales: Discovery and WoeAltitude San Francisco 2018: HTTP/2 Tales: Discovery and Woe
Altitude San Francisco 2018: HTTP/2 Tales: Discovery and WoeFastly
 
Altitude San Francisco 2018: How Magento moved to the cloud while maintaining...
Altitude San Francisco 2018: How Magento moved to the cloud while maintaining...Altitude San Francisco 2018: How Magento moved to the cloud while maintaining...
Altitude San Francisco 2018: How Magento moved to the cloud while maintaining...Fastly
 
Altitude San Francisco 2018: Scaling Ethereum to 10B requests per day
Altitude San Francisco 2018: Scaling Ethereum to 10B requests per dayAltitude San Francisco 2018: Scaling Ethereum to 10B requests per day
Altitude San Francisco 2018: Scaling Ethereum to 10B requests per dayFastly
 
Altitude San Francisco 2018: Authentication at the Edge
Altitude San Francisco 2018: Authentication at the EdgeAltitude San Francisco 2018: Authentication at the Edge
Altitude San Francisco 2018: Authentication at the EdgeFastly
 
Altitude San Francisco 2018: WebAssembly Tools & Applications
Altitude San Francisco 2018: WebAssembly Tools & ApplicationsAltitude San Francisco 2018: WebAssembly Tools & Applications
Altitude San Francisco 2018: WebAssembly Tools & ApplicationsFastly
 
Altitude San Francisco 2018: Testing with Fastly Workshop
Altitude San Francisco 2018: Testing with Fastly WorkshopAltitude San Francisco 2018: Testing with Fastly Workshop
Altitude San Francisco 2018: Testing with Fastly WorkshopFastly
 
Altitude San Francisco 2018: Fastly Purge Control at the USA TODAY NETWORK
Altitude San Francisco 2018: Fastly Purge Control at the USA TODAY NETWORKAltitude San Francisco 2018: Fastly Purge Control at the USA TODAY NETWORK
Altitude San Francisco 2018: Fastly Purge Control at the USA TODAY NETWORKFastly
 
Altitude San Francisco 2018: WAF Workshop
Altitude San Francisco 2018: WAF WorkshopAltitude San Francisco 2018: WAF Workshop
Altitude San Francisco 2018: WAF WorkshopFastly
 
Altitude San Francisco 2018: Logging at the Edge
Altitude San Francisco 2018: Logging at the Edge Altitude San Francisco 2018: Logging at the Edge
Altitude San Francisco 2018: Logging at the Edge Fastly
 
Altitude San Francisco 2018: Video Workshop Docs
Altitude San Francisco 2018: Video Workshop DocsAltitude San Francisco 2018: Video Workshop Docs
Altitude San Francisco 2018: Video Workshop DocsFastly
 
Altitude San Francisco 2018: Programming the Edge
Altitude San Francisco 2018: Programming the EdgeAltitude San Francisco 2018: Programming the Edge
Altitude San Francisco 2018: Programming the EdgeFastly
 

Plus de Fastly (20)

Revisiting HTTP/2
Revisiting HTTP/2Revisiting HTTP/2
Revisiting HTTP/2
 
Altitude San Francisco 2018: Preparing for Video Streaming Events at Scale
Altitude San Francisco 2018: Preparing for Video Streaming Events at ScaleAltitude San Francisco 2018: Preparing for Video Streaming Events at Scale
Altitude San Francisco 2018: Preparing for Video Streaming Events at Scale
 
Altitude San Francisco 2018: Building the Souther Hemisphere of the Internet
Altitude San Francisco 2018: Building the Souther Hemisphere of the InternetAltitude San Francisco 2018: Building the Souther Hemisphere of the Internet
Altitude San Francisco 2018: Building the Souther Hemisphere of the Internet
 
Altitude San Francisco 2018: The World Cup Stream
Altitude San Francisco 2018: The World Cup StreamAltitude San Francisco 2018: The World Cup Stream
Altitude San Francisco 2018: The World Cup Stream
 
Altitude San Francisco 2018: We Own Our Destiny
Altitude San Francisco 2018: We Own Our DestinyAltitude San Francisco 2018: We Own Our Destiny
Altitude San Francisco 2018: We Own Our Destiny
 
Altitude San Francisco 2018: Scale and Stability at the Edge with 1.4 Billion...
Altitude San Francisco 2018: Scale and Stability at the Edge with 1.4 Billion...Altitude San Francisco 2018: Scale and Stability at the Edge with 1.4 Billion...
Altitude San Francisco 2018: Scale and Stability at the Edge with 1.4 Billion...
 
Altitude San Francisco 2018: Moving Off the Monolith: A Seamless Migration
Altitude San Francisco 2018: Moving Off the Monolith: A Seamless MigrationAltitude San Francisco 2018: Moving Off the Monolith: A Seamless Migration
Altitude San Francisco 2018: Moving Off the Monolith: A Seamless Migration
 
Altitude San Francisco 2018: Bringing TLS to GitHub Pages
Altitude San Francisco 2018: Bringing TLS to GitHub PagesAltitude San Francisco 2018: Bringing TLS to GitHub Pages
Altitude San Francisco 2018: Bringing TLS to GitHub Pages
 
Altitude San Francisco 2018: HTTP Invalidation Workshop
Altitude San Francisco 2018: HTTP Invalidation WorkshopAltitude San Francisco 2018: HTTP Invalidation Workshop
Altitude San Francisco 2018: HTTP Invalidation Workshop
 
Altitude San Francisco 2018: HTTP/2 Tales: Discovery and Woe
Altitude San Francisco 2018: HTTP/2 Tales: Discovery and WoeAltitude San Francisco 2018: HTTP/2 Tales: Discovery and Woe
Altitude San Francisco 2018: HTTP/2 Tales: Discovery and Woe
 
Altitude San Francisco 2018: How Magento moved to the cloud while maintaining...
Altitude San Francisco 2018: How Magento moved to the cloud while maintaining...Altitude San Francisco 2018: How Magento moved to the cloud while maintaining...
Altitude San Francisco 2018: How Magento moved to the cloud while maintaining...
 
Altitude San Francisco 2018: Scaling Ethereum to 10B requests per day
Altitude San Francisco 2018: Scaling Ethereum to 10B requests per dayAltitude San Francisco 2018: Scaling Ethereum to 10B requests per day
Altitude San Francisco 2018: Scaling Ethereum to 10B requests per day
 
Altitude San Francisco 2018: Authentication at the Edge
Altitude San Francisco 2018: Authentication at the EdgeAltitude San Francisco 2018: Authentication at the Edge
Altitude San Francisco 2018: Authentication at the Edge
 
Altitude San Francisco 2018: WebAssembly Tools & Applications
Altitude San Francisco 2018: WebAssembly Tools & ApplicationsAltitude San Francisco 2018: WebAssembly Tools & Applications
Altitude San Francisco 2018: WebAssembly Tools & Applications
 
Altitude San Francisco 2018: Testing with Fastly Workshop
Altitude San Francisco 2018: Testing with Fastly WorkshopAltitude San Francisco 2018: Testing with Fastly Workshop
Altitude San Francisco 2018: Testing with Fastly Workshop
 
Altitude San Francisco 2018: Fastly Purge Control at the USA TODAY NETWORK
Altitude San Francisco 2018: Fastly Purge Control at the USA TODAY NETWORKAltitude San Francisco 2018: Fastly Purge Control at the USA TODAY NETWORK
Altitude San Francisco 2018: Fastly Purge Control at the USA TODAY NETWORK
 
Altitude San Francisco 2018: WAF Workshop
Altitude San Francisco 2018: WAF WorkshopAltitude San Francisco 2018: WAF Workshop
Altitude San Francisco 2018: WAF Workshop
 
Altitude San Francisco 2018: Logging at the Edge
Altitude San Francisco 2018: Logging at the Edge Altitude San Francisco 2018: Logging at the Edge
Altitude San Francisco 2018: Logging at the Edge
 
Altitude San Francisco 2018: Video Workshop Docs
Altitude San Francisco 2018: Video Workshop DocsAltitude San Francisco 2018: Video Workshop Docs
Altitude San Francisco 2018: Video Workshop Docs
 
Altitude San Francisco 2018: Programming the Edge
Altitude San Francisco 2018: Programming the EdgeAltitude San Francisco 2018: Programming the Edge
Altitude San Francisco 2018: Programming the Edge
 

Dernier

VVIP Pune Call Girls Mohammadwadi WhatSapp Number 8005736733 With Elite Staff...
VVIP Pune Call Girls Mohammadwadi WhatSapp Number 8005736733 With Elite Staff...VVIP Pune Call Girls Mohammadwadi WhatSapp Number 8005736733 With Elite Staff...
VVIP Pune Call Girls Mohammadwadi WhatSapp Number 8005736733 With Elite Staff...SUHANI PANDEY
 
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...SUHANI PANDEY
 
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...roncy bisnoi
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtrahman018755
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersDamian Radcliffe
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubaikojalkojal131
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...SUHANI PANDEY
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.soniya singh
 
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts ServiceReal Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts ServiceEscorts Call Girls
 
Enjoy Night⚡Call Girls Samalka Delhi >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Samalka Delhi >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Samalka Delhi >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Samalka Delhi >༒8448380779 Escort ServiceDelhi Call girls
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...SUHANI PANDEY
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Delhi Call girls
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)Delhi Call girls
 
Dubai Call Girls Milky O525547819 Call Girls Dubai Soft Dating
Dubai Call Girls Milky O525547819 Call Girls Dubai Soft DatingDubai Call Girls Milky O525547819 Call Girls Dubai Soft Dating
Dubai Call Girls Milky O525547819 Call Girls Dubai Soft Datingkojalkojal131
 
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.soniya singh
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLimonikaupta
 

Dernier (20)

VVIP Pune Call Girls Mohammadwadi WhatSapp Number 8005736733 With Elite Staff...
VVIP Pune Call Girls Mohammadwadi WhatSapp Number 8005736733 With Elite Staff...VVIP Pune Call Girls Mohammadwadi WhatSapp Number 8005736733 With Elite Staff...
VVIP Pune Call Girls Mohammadwadi WhatSapp Number 8005736733 With Elite Staff...
 
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
Call Girls Sangvi Call Me 7737669865 Budget Friendly No Advance BookingCall G...
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
 
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts ServiceReal Escorts in Al Nahda +971524965298 Dubai Escorts Service
Real Escorts in Al Nahda +971524965298 Dubai Escorts Service
 
Enjoy Night⚡Call Girls Samalka Delhi >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Samalka Delhi >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Samalka Delhi >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Samalka Delhi >༒8448380779 Escort Service
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
Dubai Call Girls Milky O525547819 Call Girls Dubai Soft Dating
Dubai Call Girls Milky O525547819 Call Girls Dubai Soft DatingDubai Call Girls Milky O525547819 Call Girls Dubai Soft Dating
Dubai Call Girls Milky O525547819 Call Girls Dubai Soft Dating
 
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
 

Rails Caching: Secrets From the Edge

  • 1. Rails Caching Secrets: From the Edge! Michael May | @ohaimmay | austinonrails | 10/28/2014
  • 2. We’re Hiring! Distributed Systems! Ruby C Go Perl JS
  • 3. We are here • Rails caching best practices • Dynamic content • Edge caching / Content Delivery Networks • Edge caching dynamic content with Rails
  • 4. Rails caching • Query/SQL • Page/Action (removed from Rails 4 core!) • Asset • Fragment
  • 6. Query caching • Automagically done by rails when perform_caching = true • Not cached between requests! • Could just store the query result in a variable
  • 7. Custom Query Caching class Product < MyActiveModel def self.latest Rails.cache.fetch("latest", expires_in: 8.hours) do Product.last(50) end end end
  • 8. Asset Pipeline • Serve static assets from nginx or apache • config.serve_static_assets = false • Enable Compression* • config.assets.compress = true • # Rails 4 config.assets.css_compressor = :yui config.assets.js_compressor = :uglifier • Asset Digests • config.assets.digest = true
  • 9. Enable Compression* Compress all responses with gzip, deflate, etc. # in application.rb module FastestAppEver class Application < Rails::Application config.middleware.use Rack::Deflater end end * http://robots.thoughtbot.com/content-compression-with-rack-deflater
  • 10. $ curl -sv -H “Accept-Encoding: deflate” http://fast.mmay.rocks/catz.json * Connected to fast.mmay.rocks (127.0.0.1) port 666 > GET /catz.json HTTP/1.1 > User-Agent: curl > Host: fast.mmay.rocks:666 > Accept-Encoding: deflate,gzip > < HTTP/1.1 200 OK < Content-Type: application/json; charset=utf-8 < Vary: Accept-Encoding < Content-Encoding: deflate < Cache-Control: max-age=60, s-maxage=3600 < Transfer-Encoding: chunked < * magical encoded bytes* V*.I,)-VRJ-*RN@ ɥEEy%9
  • 11.
  • 13. Asset Caching • Configure an asset host if needed • config.action_controller.asset_host = ENV[‘FASTLY_CDN_URL'] • Cache-Control like a pro • config.static_cache_control = 'public, s-maxage=15552000, maxage=2592000'
  • 14. HTTP Headers RFC 2616 Section 14
  • 15. Cache-Control HTTP Header “public, maxage=2592000, s-maxage=15552000” public “please cache me” maxage=2592000 “keep me for 30 days” s-maxage=15552000 “PROXIES ONLY! - Keep me for 180 days”
  • 16. Bonus Cache-Control Directives! • stale-while-revalidate • Serve the cached (stale) content for n seconds while you re-fetche the new content in the background • Cache-Control: maxage=604800, stale-while-revalidate=3600 • “Serve stale for up to an hr while you fetch the latest behind the scenes” • stale-if-error • If the re-fetch fails within n seconds of the content becoming stale, serve the cached content • Cache-Control: max-age=604800, stale-if-error=86400 • “Serve stale for up to an hr if origin responds with 4xx or 5xx”
  • 17. ETags • Automatically added into requests with Rack::ETag • Rails renders response every time to calculate etag • Override default with Conditional GETs • stale?(@model) • fresh_when(@model)
  • 18. The Vary HTTP Header • Change response base on the value of another HTTP Header • Example: “Vary: Accept-Encoding” Accept-Encoding: gzip => Serve Response A Accept-Encoding: deflate => Serve Response B • “This response changes for different values of the Accept-Encoding header”
  • 19. Vary Best Practices • Please do not Vary on User-Agent • There are THOUSANDS of these! • Limits caching benefits - almost Impossible to serve the same response more than once! • In general, avoid varying on anything other than content encoding
  • 20. Dynamic Content • Changes are unpredictable! • User driven events • Can’t just set a Time To Live (TTL) • Frequently, but not continuously changing • Actually static for short periods of time (we can cache static things)!
  • 21. Dynamic Content Caching • Usually don’t (╯°□°)╯︵ ┻━┻ • Edge Side Includes (ESI) • Dynamic Site Acceleration (DSA)
  • 22. Fragment Caching The rails answer to caching dynamic HTML # products/index.html.erb <% cache(cache_key_for_products) do %> <% Product.all.each do |p| %> <%= link_to p.name, product_url(p) %> <% end %> <% end %> # products_controller.rb def update … expire_fragment(cache_key_for_products) … end
  • 23. Nested Fragment Caching <% cache(cache_key_for_products) do %> All available products: <% Product.all.each do |p| %> <% cache(p) do %> <%= link_to p.name, product_url(p) %> <% end %> <% end %> <% end %>
  • 24. Nested Fragment • Tedious • Comb through (probably terrible) view code • Cache keys are weird • “A given key should always return the same content.” - Rails • But I like “A given key should always return the most up-to-date content” - like a DB primary key • Hacking around cache limitations • Memcache and wildcard purging
  • 25. Nested Fragment • Garbage left in the cache • Defaults writing to disk • What about dynamic API caching? • “The caching itself happens in the views based on partials rendering the objects in question” • Take control over your cached data!
  • 26. Edge Caching with things like CDNs
  • 27. Edge Caches • Geographically distributed • Highly optimized storage and network (nanoseconds count) • Move content physically closer to end-users • DECREASE LATENCY! (speed of light sux lol)
  • 28.
  • 29.
  • 30.
  • 31.
  • 32. #cachemoney • Less requests/bandwidth back to your origin server • Avoid complex or less efficient strategies • Edge Side Includes (ESI) • Fragment view caching
  • 34. Our approach to dynamic content • Tag content with Surrogate-Key HTTP headers • Programmatically purge (~150ms globally) • By Surrogate-Key • By resource path • Real-time analytics and log streaming • Optimize the pieces of the network we control
  • 35. Tagging responses with Surrogate-Keys
  • 36. class ProductsController < ApplicationController # set Cache-Control, strip Set-Cookie before_filter :set_cache_control_headers,only [:index,:show] def index @products = Product.last(10) # set Surrogate-Key: products set_surrogate_key_header @products.table_key respond_with @products end def show @product = Products.find(params[:id]) # set Surrogate-Key: product/666 set_surrogate_key_header @product.record_key respond_with @product end end
  • 38. class ProductsController < ApplicationController def create @product = Product.new(params) if @product.save # purge Surrogate-Key: products @product.purge_all render @product end end ...
  • 39. def update @product = Product.find(params[:id]) if @product.update(params) # purge Surrogate-Key: product/666 @product.purge render @product end end
  • 41. Edge caching in practice
  • 42. Watch out for Set-Cookie! • Nothing with a Set-Cookie header is cached (by default) • Authentication frameworks/middleware might inject Set-Cookie after the rails stack removes it • Avoid caching pains by knowing when, where, and how you use Set-Cookie
  • 43. Edge scripting with VCL (varnish config lang)
  • 44. VCL • Fastly VCL Extensions • date/time, geoip, hashing, strings, etc. • Do application logic at the CDN edge
  • 45. URL Rewriting • Filter bad requests • Normalize or block paths • Apache, nginx • if ($invalid_referer) { return 403; } • You can do this at the edge!
  • 47. What can we do better? • Add better caching defaults? • Cache-Control, stale-while-revalidate, stale-if-error • Re-use existing rails cache interfaces for edge caching? • ActiveSupport::Cache::EdgeStore • Better integration with HTTP accelerators like Varnish?
  • 48. Takeaways • Take advantage of Rails built-in caching • Get fancy with Cache-Control directives • Use Google PageSpeed Insights (chrome plugin adds it to dev tools) • Dynamic edge caching is all about the power of purge! • Similar school of thought to rails action caching
  • 49. Questions? Michael May || @ohaimmay cool links: fastly-rails - github.com/fastly/fastly-rails surrogate keys - fastly.com/blog/surrogate-keys-part-1 cache-control tutorial - docs.fastly.com/guides/tutorials/cache-control-tutorial serve stale cache-control - fastly.com/blog/stale-while-revalidate vary header best practices - fastly.com/blog/best-practices-for-using-the-vary-header caching like & share buttons - fastly.com/blog/caching-like-and-share-buttons pagespeed insights - developers.google.com/speed/pagespeed