SlideShare uma empresa Scribd logo
1 de 59
Caching Up and Down
the Stack
Long Island/Queens Django Meetup 5/20/14
Hi, I’m Dan Kuebrich
● Software engineer, python fan
● Web performance geek
● Founder of Tracelytics, now part of AppNeta
● Once (and future?) Queens resident
DJANGO
What is “caching”?
● Caching is avoiding doing expensive work
o by doing cheaper work
● Common examples?
o On repeat visits, your browser doesn’t download
images that haven’t changed
o Your CPU caches instructions, data so it doesn’t
have to go to RAM… or to disk!
What is “caching”?
Uncached
Client
Data Source
What is “caching”?
Client
Data Source
Uncached Cached
Cache Intermediary
Client
Data Source
What is “caching”?
Client
Data Source
Uncached Cached
Cache Intermediary
Client
Data Source
Fast!
Slow...
“Latency Numbers Every Programmer Should Know”
Systems Performance: Enterprise and the Cloud by Brendan Gregg
http://books.google.com/books?id=xQdvAQAAQBAJ&pg=PA20&lpg=PA20&source=bl&ots=hlTgyxdrnR&sig=CCjddHrY1H6muMVW9BFcbdO7DDo&hl=en&sa=X&ei=dS7oUquhOYr9oAT9oYGoDw&ved=0CCkQ6AEwAA#v=onepage
&q&f=false
A whole mess of caching:
● Browser cache
● CDN
● Proxy / optimizer
● Application-based
o Full-page
o Fragment
o Object cache
● Database
o Query cache
o Denormalization
Closer to the user
Closer to the data
Caching in Django apps: Frontend
● Client-side assets
● Full pages
Client-side assets
Client-side assets
Client-side assets
● Use HTTP caches!
o Browser
o CDN
o Intermediate proxies
● Set policy with cache headers
o Cache-Control / Expires
o ETag / Last-Modified
HTTP Cache-Control and Expires
● Stop the browser from even asking for it
● Expires
o Pick a date in the future, good til then
● Cache-control
o More flexible
o Introduced in HTTP 1.1
o Use this one
HTTP Cache-Control and Expires
dan@JLTM21:~$ curl -I https://login.tv.appneta.com/cache/tl-layouts_base_unauth-
compiled-162c2ceecd9a7ff1e65ab460c2b99852a49f5a43.css
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: max-age=315360000
Content-length: 5955
Content-Type: text/css
Date: Tue, 20 May 2014 23:12:16 GMT
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Last-Modified: Fri, 16 May 2014 20:51:19 GMT
Server: nginx
Connection: keep-alive
HTTP Cache Control in Django
https://docs.djangoproject.com/en/dev/topics/cache/
ETag + Last-Modified
ETag + Last-Modified
dan@JLTM21:~$ curl -I www.appneta.com/stylesheets/styles.css
HTTP/1.1 200 OK
Last-Modified: Tue, 20 May 2014 05:52:50 GMT
ETag: "30854c-1c3d3-4f9ce7d715080"
Vary: Accept-Encoding
Content-Type: text/css
...
ETag + Last-Modified
dan@JLTM21:~$ curl -I www.appneta.com/stylesheets/styles.css --header 'If-None-
Match: "30854c-1c3d3-4f9ce7d715080"'
HTTP/1.1 304 Not Modified
Last-Modified: Tue, 20 May 2014 05:52:50 GMT
ETag: "30854c-1c3d3-4f9ce7d715080"
Vary: Accept-Encoding
Content-Type: text/css
Date: Tue, 20 May 2014 23:21:12 GMT
...
ETag vs Last-Modified
● Last-Modified is date-based
● ETag is content-based
● Most webservers generate both
● Some webservers (Apache) generate etags
that depend on local state
o If you have a load-balanced pool of servers working
here, they might not be using the same etags!
A whole mess of caching:
● Browser cache
● CDN
● Proxy / optimizer
● Application-based
o Full-page
o Fragment
o Object cache
● Database
o Query cache
o Denormalization
CDNs
● Put content closer to your end-users
o and offload HTTP requests from
your servers
● Best for static assets
● Same cache control policies apply
Full-page caching
Client
Data Source
Varnish
No internet
standards
necessary!
Full-page caching: mod_pagespeed
Client
Data Source
mod_pagespeed
● Dynamically rewrites
pages with frontend
optimizations
● Caches rewritten pages
A whole mess of caching:
● Browser cache
● CDN
● Proxy / optimizer
● Application-based
o Full-page
o Fragment
o Object cache
● Database
o Query cache
o Denormalization
Full-page caching in Django
Wait, where is this getting cached?
● Django makes it easy to configure
o In-memory
o File-based
o Memcached
o etc.
Full-page caching: dynamic pages?
Full-page caching: dynamic pages?
Fragment caching
Full-page caching: dynamic pages?
Full-page caching: the ajax solution
Object caching
def get_item_by_id(key):
# Look up the item in our database
return session.query(User)
.filter_by(id=key)
.first()
Object caching
def get_item_by_id(key):
# Check in cache
val = mc.get(key)
# If exists, return it
if val:
return val
# If not, get the val, store it in the cache
val = return session.query(User)
.filter_by(id=key)
.first()
mc.set(key, val)
return val
Object caching
@decorator
def cache(expensive_func, key):
# Check in cache
val = mc.get(key)
# If exists, return it
if val:
return val
# If not, get the val, store it in the cache
val = expensive_func(key)
mc.set(key, val)
return val
Object caching
@cache
def get_item_by_id(key):
# Look up the item in our database
return session.query(User)
.filter_by(id=key)
.first()
Object caching in Django
A whole mess of caching:
● Browser cache
● CDN
● Proxy / optimizer
● Application-based
o Full-page
o Fragment
o Object cache
● Database
o Query cache
o Denormalization
Query caching
Client
Actual tables
Database
Query
Cache
Cached?
Query caching
mysql> select SQL_CACHE count(*) from traces;
+----------+
| count(*) |
+----------+
| 3135623 |
+----------+
1 row in set (0.56 sec)
mysql> select SQL_CACHE count(*) from traces;
+----------+
| count(*) |
+----------+
| 3135623 |
+----------+
1 row in set (0.00 sec)
Query caching
Query caching
Uncached
Cached
Denormalization
mysql> select table1.x, table2.y from table1 join table2 on table1.z = table2.q
where table1.z > 100;
mysql> select table1.x, table1.y from table1 where table1.z > 100;
A whole mess of caching:
● Browser cache
● CDN
● Proxy / optimizer
● Application-based
o Full-page
o Fragment
o Object cache
● Database
o Query cache
o Denormalization
Caching: what can go wrong?
● Invalidation
● Fragmentation
● Stampedes
● Complexity
Invalidation
Client
Data Source
Cache Intermediary
Update!
Write
Invalidate
Invalidation on page-scale
● Browser cache
● CDN
● Proxy / optimizer
● Application-based
o Full-page
o Fragment
o Object cache
● Database
o Query cache
o Denormalization
More savings,
generally more invalidation...
Smaller savings,
generally less invalidation
Fragmentation
● What if I have a lot of different things to
cache?
o More misses
o Potential cache eviction
Fragmentation
Your pages / objects
FrequencyofAccess
Fragmentation
Your pages / objects
FrequencyofAccess
Stampedes
● On a cache miss extra work is done
● The result is stored in the cache
● What if multiple simultaneous misses?
Stampedes
http://allthingsd.com/20080521/stampede-facebook-opens-its-profile-doors/
Complexity
● How much caching do I need, and where?
● What is the invalidation process
o on data update? on release?
● What happens if the caches fall over?
● How do I debug it?
Takeaways
● The ‘how’ of caching:
o What are you caching?
o Where are you caching it?
o How bad is a cache miss?
o How and when are you invalidating?
Takeaways
● The ‘why’ of caching:
o Did it actually get faster?
o Is speed worth extra complexity?
o Don’t guess – measure!
o Always use real-world conditions.
Questions?
?
Thanks!
● Interested in measuring your Django app’s
performance?
o Free trial of TraceView:
www.appneta.com/products/traceview
● See you at Velocity NYC this fall?
● Twitter: @appneta / @dankosaur
Resources
● Django documentation on caching: https://docs.djangoproject.com/en/dev/topics/cache/
● Varnish caching, via Disqus: http://blog.disqus.com/post/62187806135/scaling-django-to-8-
billion-page-views
● Django cache option comparisons: http://codysoyland.com/2010/jan/17/evaluating-django-
caching-options/
● More Django-specific tips: http://www.slideshare.net/csky/where-django-caching-bust-at-the-
seams
● Guide to cache-related HTTP headers: http://www.mobify.com/blog/beginners-guide-to-http-
cache-headers/
● Google PageSpeed: https://developers.google.com/speed/pagespeed/module

Mais conteúdo relacionado

Mais procurados

ELK stack at weibo.com
ELK stack at weibo.comELK stack at weibo.com
ELK stack at weibo.com琛琳 饶
 
Aaron Mildenstein - Using Logstash with Zabbix
Aaron Mildenstein - Using Logstash with ZabbixAaron Mildenstein - Using Logstash with Zabbix
Aaron Mildenstein - Using Logstash with ZabbixZabbix
 
Application Logging With The ELK Stack
Application Logging With The ELK StackApplication Logging With The ELK Stack
Application Logging With The ELK Stackbenwaine
 
Logstash family introduction
Logstash family introductionLogstash family introduction
Logstash family introductionOwen Wu
 
Debugging Distributed Systems - Velocity Santa Clara 2016
Debugging Distributed Systems - Velocity Santa Clara 2016Debugging Distributed Systems - Velocity Santa Clara 2016
Debugging Distributed Systems - Velocity Santa Clara 2016Donny Nadolny
 
Testing Wi-Fi with OSS Tools
Testing Wi-Fi with OSS ToolsTesting Wi-Fi with OSS Tools
Testing Wi-Fi with OSS ToolsAll Things Open
 
Advanced troubleshooting linux performance
Advanced troubleshooting linux performanceAdvanced troubleshooting linux performance
Advanced troubleshooting linux performanceForthscale
 
Volker Fröhlich - How to Debug Common Agent Issues
Volker Fröhlich - How to Debug Common Agent IssuesVolker Fröhlich - How to Debug Common Agent Issues
Volker Fröhlich - How to Debug Common Agent IssuesZabbix
 
Logstash-Elasticsearch-Kibana
Logstash-Elasticsearch-KibanaLogstash-Elasticsearch-Kibana
Logstash-Elasticsearch-Kibanadknx01
 
Frontera распределенный робот для обхода веба в больших объемах / Александр С...
Frontera распределенный робот для обхода веба в больших объемах / Александр С...Frontera распределенный робот для обхода веба в больших объемах / Александр С...
Frontera распределенный робот для обхода веба в больших объемах / Александр С...Ontico
 
Don’t turn your logs into cuneiform
Don’t turn your logs into cuneiformDon’t turn your logs into cuneiform
Don’t turn your logs into cuneiformAndrey Rebrov
 
Collect distributed application logging using fluentd (EFK stack)
Collect distributed application logging using fluentd (EFK stack)Collect distributed application logging using fluentd (EFK stack)
Collect distributed application logging using fluentd (EFK stack)Marco Pas
 
(Fios#02) 2. elk 포렌식 분석
(Fios#02) 2. elk 포렌식 분석(Fios#02) 2. elk 포렌식 분석
(Fios#02) 2. elk 포렌식 분석INSIGHT FORENSIC
 
{{more}} Kibana4
{{more}} Kibana4{{more}} Kibana4
{{more}} Kibana4琛琳 饶
 
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016Zabbix
 

Mais procurados (20)

Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
ELK stack at weibo.com
ELK stack at weibo.comELK stack at weibo.com
ELK stack at weibo.com
 
Thanos - Prometheus on Scale
Thanos - Prometheus on ScaleThanos - Prometheus on Scale
Thanos - Prometheus on Scale
 
Aaron Mildenstein - Using Logstash with Zabbix
Aaron Mildenstein - Using Logstash with ZabbixAaron Mildenstein - Using Logstash with Zabbix
Aaron Mildenstein - Using Logstash with Zabbix
 
Application Logging With The ELK Stack
Application Logging With The ELK StackApplication Logging With The ELK Stack
Application Logging With The ELK Stack
 
Logstash family introduction
Logstash family introductionLogstash family introduction
Logstash family introduction
 
Logstash
LogstashLogstash
Logstash
 
Debugging Distributed Systems - Velocity Santa Clara 2016
Debugging Distributed Systems - Velocity Santa Clara 2016Debugging Distributed Systems - Velocity Santa Clara 2016
Debugging Distributed Systems - Velocity Santa Clara 2016
 
Testing Wi-Fi with OSS Tools
Testing Wi-Fi with OSS ToolsTesting Wi-Fi with OSS Tools
Testing Wi-Fi with OSS Tools
 
Advanced troubleshooting linux performance
Advanced troubleshooting linux performanceAdvanced troubleshooting linux performance
Advanced troubleshooting linux performance
 
Volker Fröhlich - How to Debug Common Agent Issues
Volker Fröhlich - How to Debug Common Agent IssuesVolker Fröhlich - How to Debug Common Agent Issues
Volker Fröhlich - How to Debug Common Agent Issues
 
Logstash-Elasticsearch-Kibana
Logstash-Elasticsearch-KibanaLogstash-Elasticsearch-Kibana
Logstash-Elasticsearch-Kibana
 
Web::Scraper
Web::ScraperWeb::Scraper
Web::Scraper
 
Frontera распределенный робот для обхода веба в больших объемах / Александр С...
Frontera распределенный робот для обхода веба в больших объемах / Александр С...Frontera распределенный робот для обхода веба в больших объемах / Александр С...
Frontera распределенный робот для обхода веба в больших объемах / Александр С...
 
Don’t turn your logs into cuneiform
Don’t turn your logs into cuneiformDon’t turn your logs into cuneiform
Don’t turn your logs into cuneiform
 
On Centralizing Logs
On Centralizing LogsOn Centralizing Logs
On Centralizing Logs
 
Collect distributed application logging using fluentd (EFK stack)
Collect distributed application logging using fluentd (EFK stack)Collect distributed application logging using fluentd (EFK stack)
Collect distributed application logging using fluentd (EFK stack)
 
(Fios#02) 2. elk 포렌식 분석
(Fios#02) 2. elk 포렌식 분석(Fios#02) 2. elk 포렌식 분석
(Fios#02) 2. elk 포렌식 분석
 
{{more}} Kibana4
{{more}} Kibana4{{more}} Kibana4
{{more}} Kibana4
 
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
 

Destaque

Li-fi Presentation by Debika sadhukhan
Li-fi Presentation by Debika sadhukhanLi-fi Presentation by Debika sadhukhan
Li-fi Presentation by Debika sadhukhanAmrit Mandal
 
Network layer - design Issues
Network layer - design IssuesNetwork layer - design Issues
Network layer - design Issuesقصي نسور
 
Types of Networks,Network Design Issues,Design Tools
Types of Networks,Network Design Issues,Design ToolsTypes of Networks,Network Design Issues,Design Tools
Types of Networks,Network Design Issues,Design ToolsSurabhi Gosavi
 

Destaque (6)

Lifi ppt
Lifi pptLifi ppt
Lifi ppt
 
Li-fi Presentation by Debika sadhukhan
Li-fi Presentation by Debika sadhukhanLi-fi Presentation by Debika sadhukhan
Li-fi Presentation by Debika sadhukhan
 
Lifi Technology
Lifi TechnologyLifi Technology
Lifi Technology
 
Lifi ppt
Lifi pptLifi ppt
Lifi ppt
 
Network layer - design Issues
Network layer - design IssuesNetwork layer - design Issues
Network layer - design Issues
 
Types of Networks,Network Design Issues,Design Tools
Types of Networks,Network Design Issues,Design ToolsTypes of Networks,Network Design Issues,Design Tools
Types of Networks,Network Design Issues,Design Tools
 

Semelhante a Caching Up and Down the Stack

Less and faster – Cache tips for WordPress developers
Less and faster – Cache tips for WordPress developersLess and faster – Cache tips for WordPress developers
Less and faster – Cache tips for WordPress developersSeravo
 
Transients are good for you - WordCamp London 2016
Transients are good for you - WordCamp London 2016Transients are good for you - WordCamp London 2016
Transients are good for you - WordCamp London 2016Boiteaweb
 
Ajax to the Moon
Ajax to the MoonAjax to the Moon
Ajax to the Moondavejohnson
 
Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011Wim Godden
 
Caching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourCaching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourWim Godden
 
Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Wim Godden
 
Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018Thijs Feryn
 
ITB2017 - Nginx Effective High Availability Content Caching
ITB2017 - Nginx Effective High Availability Content CachingITB2017 - Nginx Effective High Availability Content Caching
ITB2017 - Nginx Effective High Availability Content CachingOrtus Solutions, Corp
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalabilityWim Godden
 
Using NGINX as an Effective and Highly Available Content Cache
Using NGINX as an Effective and Highly Available Content CacheUsing NGINX as an Effective and Highly Available Content Cache
Using NGINX as an Effective and Highly Available Content CacheKevin Jones
 
Magento Performance Optimization 101
Magento Performance Optimization 101Magento Performance Optimization 101
Magento Performance Optimization 101Angus Li
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxbobmcwhirter
 
JavaScript performance patterns
JavaScript performance patternsJavaScript performance patterns
JavaScript performance patternsStoyan Stefanov
 
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Wim Godden
 
JUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleJUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleGeoffrey De Smet
 
Clug 2012 March web server optimisation
Clug 2012 March   web server optimisationClug 2012 March   web server optimisation
Clug 2012 March web server optimisationgrooverdan
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Studyhernanibf
 
ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!Chang W. Doh
 

Semelhante a Caching Up and Down the Stack (20)

Less and faster – Cache tips for WordPress developers
Less and faster – Cache tips for WordPress developersLess and faster – Cache tips for WordPress developers
Less and faster – Cache tips for WordPress developers
 
Transients are good for you - WordCamp London 2016
Transients are good for you - WordCamp London 2016Transients are good for you - WordCamp London 2016
Transients are good for you - WordCamp London 2016
 
Ajax to the Moon
Ajax to the MoonAjax to the Moon
Ajax to the Moon
 
Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011
 
Please dont touch-3.6-jsday
Please dont touch-3.6-jsdayPlease dont touch-3.6-jsday
Please dont touch-3.6-jsday
 
Caching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourCaching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTour
 
Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012
 
Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018
 
ITB2017 - Nginx Effective High Availability Content Caching
ITB2017 - Nginx Effective High Availability Content CachingITB2017 - Nginx Effective High Availability Content Caching
ITB2017 - Nginx Effective High Availability Content Caching
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
Using NGINX as an Effective and Highly Available Content Cache
Using NGINX as an Effective and Highly Available Content CacheUsing NGINX as an Effective and Highly Available Content Cache
Using NGINX as an Effective and Highly Available Content Cache
 
Magento Performance Optimization 101
Magento Performance Optimization 101Magento Performance Optimization 101
Magento Performance Optimization 101
 
Web-Performance
Web-PerformanceWeb-Performance
Web-Performance
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
JavaScript performance patterns
JavaScript performance patternsJavaScript performance patterns
JavaScript performance patterns
 
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011
 
JUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleJUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by example
 
Clug 2012 March web server optimisation
Clug 2012 March   web server optimisationClug 2012 March   web server optimisation
Clug 2012 March web server optimisation
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Study
 
ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!
 

Último

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 

Último (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Caching Up and Down the Stack

  • 1. Caching Up and Down the Stack Long Island/Queens Django Meetup 5/20/14
  • 2. Hi, I’m Dan Kuebrich ● Software engineer, python fan ● Web performance geek ● Founder of Tracelytics, now part of AppNeta ● Once (and future?) Queens resident
  • 3.
  • 5. What is “caching”? ● Caching is avoiding doing expensive work o by doing cheaper work ● Common examples? o On repeat visits, your browser doesn’t download images that haven’t changed o Your CPU caches instructions, data so it doesn’t have to go to RAM… or to disk!
  • 7. What is “caching”? Client Data Source Uncached Cached Cache Intermediary Client Data Source
  • 8. What is “caching”? Client Data Source Uncached Cached Cache Intermediary Client Data Source Fast! Slow...
  • 9. “Latency Numbers Every Programmer Should Know” Systems Performance: Enterprise and the Cloud by Brendan Gregg http://books.google.com/books?id=xQdvAQAAQBAJ&pg=PA20&lpg=PA20&source=bl&ots=hlTgyxdrnR&sig=CCjddHrY1H6muMVW9BFcbdO7DDo&hl=en&sa=X&ei=dS7oUquhOYr9oAT9oYGoDw&ved=0CCkQ6AEwAA#v=onepage &q&f=false
  • 10. A whole mess of caching: ● Browser cache ● CDN ● Proxy / optimizer ● Application-based o Full-page o Fragment o Object cache ● Database o Query cache o Denormalization Closer to the user Closer to the data
  • 11. Caching in Django apps: Frontend ● Client-side assets ● Full pages
  • 14. Client-side assets ● Use HTTP caches! o Browser o CDN o Intermediate proxies ● Set policy with cache headers o Cache-Control / Expires o ETag / Last-Modified
  • 15. HTTP Cache-Control and Expires ● Stop the browser from even asking for it ● Expires o Pick a date in the future, good til then ● Cache-control o More flexible o Introduced in HTTP 1.1 o Use this one
  • 16. HTTP Cache-Control and Expires dan@JLTM21:~$ curl -I https://login.tv.appneta.com/cache/tl-layouts_base_unauth- compiled-162c2ceecd9a7ff1e65ab460c2b99852a49f5a43.css HTTP/1.1 200 OK Accept-Ranges: bytes Cache-Control: max-age=315360000 Content-length: 5955 Content-Type: text/css Date: Tue, 20 May 2014 23:12:16 GMT Expires: Thu, 31 Dec 2037 23:55:55 GMT Last-Modified: Fri, 16 May 2014 20:51:19 GMT Server: nginx Connection: keep-alive
  • 17. HTTP Cache Control in Django https://docs.djangoproject.com/en/dev/topics/cache/
  • 19. ETag + Last-Modified dan@JLTM21:~$ curl -I www.appneta.com/stylesheets/styles.css HTTP/1.1 200 OK Last-Modified: Tue, 20 May 2014 05:52:50 GMT ETag: "30854c-1c3d3-4f9ce7d715080" Vary: Accept-Encoding Content-Type: text/css ...
  • 20. ETag + Last-Modified dan@JLTM21:~$ curl -I www.appneta.com/stylesheets/styles.css --header 'If-None- Match: "30854c-1c3d3-4f9ce7d715080"' HTTP/1.1 304 Not Modified Last-Modified: Tue, 20 May 2014 05:52:50 GMT ETag: "30854c-1c3d3-4f9ce7d715080" Vary: Accept-Encoding Content-Type: text/css Date: Tue, 20 May 2014 23:21:12 GMT ...
  • 21. ETag vs Last-Modified ● Last-Modified is date-based ● ETag is content-based ● Most webservers generate both ● Some webservers (Apache) generate etags that depend on local state o If you have a load-balanced pool of servers working here, they might not be using the same etags!
  • 22. A whole mess of caching: ● Browser cache ● CDN ● Proxy / optimizer ● Application-based o Full-page o Fragment o Object cache ● Database o Query cache o Denormalization
  • 23. CDNs ● Put content closer to your end-users o and offload HTTP requests from your servers ● Best for static assets ● Same cache control policies apply
  • 24. Full-page caching Client Data Source Varnish No internet standards necessary!
  • 25. Full-page caching: mod_pagespeed Client Data Source mod_pagespeed ● Dynamically rewrites pages with frontend optimizations ● Caches rewritten pages
  • 26. A whole mess of caching: ● Browser cache ● CDN ● Proxy / optimizer ● Application-based o Full-page o Fragment o Object cache ● Database o Query cache o Denormalization
  • 28. Wait, where is this getting cached? ● Django makes it easy to configure o In-memory o File-based o Memcached o etc.
  • 33. Full-page caching: the ajax solution
  • 34. Object caching def get_item_by_id(key): # Look up the item in our database return session.query(User) .filter_by(id=key) .first()
  • 35. Object caching def get_item_by_id(key): # Check in cache val = mc.get(key) # If exists, return it if val: return val # If not, get the val, store it in the cache val = return session.query(User) .filter_by(id=key) .first() mc.set(key, val) return val
  • 36. Object caching @decorator def cache(expensive_func, key): # Check in cache val = mc.get(key) # If exists, return it if val: return val # If not, get the val, store it in the cache val = expensive_func(key) mc.set(key, val) return val
  • 37. Object caching @cache def get_item_by_id(key): # Look up the item in our database return session.query(User) .filter_by(id=key) .first()
  • 39. A whole mess of caching: ● Browser cache ● CDN ● Proxy / optimizer ● Application-based o Full-page o Fragment o Object cache ● Database o Query cache o Denormalization
  • 41. Query caching mysql> select SQL_CACHE count(*) from traces; +----------+ | count(*) | +----------+ | 3135623 | +----------+ 1 row in set (0.56 sec) mysql> select SQL_CACHE count(*) from traces; +----------+ | count(*) | +----------+ | 3135623 | +----------+ 1 row in set (0.00 sec)
  • 44. Denormalization mysql> select table1.x, table2.y from table1 join table2 on table1.z = table2.q where table1.z > 100; mysql> select table1.x, table1.y from table1 where table1.z > 100;
  • 45. A whole mess of caching: ● Browser cache ● CDN ● Proxy / optimizer ● Application-based o Full-page o Fragment o Object cache ● Database o Query cache o Denormalization
  • 46. Caching: what can go wrong? ● Invalidation ● Fragmentation ● Stampedes ● Complexity
  • 48. Invalidation on page-scale ● Browser cache ● CDN ● Proxy / optimizer ● Application-based o Full-page o Fragment o Object cache ● Database o Query cache o Denormalization More savings, generally more invalidation... Smaller savings, generally less invalidation
  • 49. Fragmentation ● What if I have a lot of different things to cache? o More misses o Potential cache eviction
  • 50. Fragmentation Your pages / objects FrequencyofAccess
  • 51. Fragmentation Your pages / objects FrequencyofAccess
  • 52. Stampedes ● On a cache miss extra work is done ● The result is stored in the cache ● What if multiple simultaneous misses?
  • 54. Complexity ● How much caching do I need, and where? ● What is the invalidation process o on data update? on release? ● What happens if the caches fall over? ● How do I debug it?
  • 55. Takeaways ● The ‘how’ of caching: o What are you caching? o Where are you caching it? o How bad is a cache miss? o How and when are you invalidating?
  • 56. Takeaways ● The ‘why’ of caching: o Did it actually get faster? o Is speed worth extra complexity? o Don’t guess – measure! o Always use real-world conditions.
  • 58. Thanks! ● Interested in measuring your Django app’s performance? o Free trial of TraceView: www.appneta.com/products/traceview ● See you at Velocity NYC this fall? ● Twitter: @appneta / @dankosaur
  • 59. Resources ● Django documentation on caching: https://docs.djangoproject.com/en/dev/topics/cache/ ● Varnish caching, via Disqus: http://blog.disqus.com/post/62187806135/scaling-django-to-8- billion-page-views ● Django cache option comparisons: http://codysoyland.com/2010/jan/17/evaluating-django- caching-options/ ● More Django-specific tips: http://www.slideshare.net/csky/where-django-caching-bust-at-the- seams ● Guide to cache-related HTTP headers: http://www.mobify.com/blog/beginners-guide-to-http- cache-headers/ ● Google PageSpeed: https://developers.google.com/speed/pagespeed/module