CACHE RULES
EVERYTHING
AROUND MEpresented at
WordCamp Baltimore
September 21 2013
HI, I'M RUSSELL HEIMLICH
(Heimlich, like the maneuver)
Head Cache Invalidator at the Pew Research Center
FOLLOW ALONG
v.gd/wpcream
BUT FIRST A
STORY…
2006 - 2009 I worked at USNews & World Report
MONTHS OF WORK GO IN TO THE
RELEASE OF NEW RANKINGS.
ON LAUNCH DAY WE
ALWAYS SEE A HUGE
TRAFFIC SPIKE
But one year we got lucky…
The marketing/biz dev team managed to get us featured on
the homepage of a major web portal!
(And by featured I mean the f...
WE WERE GOING TO BE
FEATURED ON…
(Before their CEO discovered Adobe Illustrator)
WE WERE EXCITED!
Ok maybe we looked more like this…
The story went live on Yahoo.com and we watched…
The servers started getting slower…
Editors were calling us saying they couldn't get in to the
admin area…
Our servers were completely down…
We had to call Yahoo! and have them remove the story
because we couldn't handle the traffic…
WE LASTED 15 MINUTES.
PERFORMANCE AND UPTIME
ARE IMPORTANT!
And caching can help.
P.S. Don't feel bad for USNews
WHAT IS
CACHING?
CACHE
“a component that transparently stores data
so that future requests for that data can be
served faster.”
— via Wikip...
A cache may contain values computed earlier or duplicate
values stored elsewhere.
A cache hit can complete the request by reading the value
from the cache.
A cache miss has to be recomputed or fetched from
another location which is much slower.
The more requests that can be served from a cache, the
faster the system performs.
The faster the system, the more request...
A REAL-WORLD EXAMPLE
You're taking 5 classes and need to write 5 essays…
You could write 5 separate essays
OR
You could write one essay and use it for all of your classes
THAT'S CACHING!
There are many (potential) layers of caching involved in a
single web request.
HOW DOES A
REQUEST
WORK?
A BASIC REQUEST
A BASIC REQUEST
PHP PAGES
TAKE LONGER
TO SERVE
A PHP PAGE REQUEST
A PHP PAGE REQUEST
A PHP PAGE
WITH MYSQL
DATA TAKES
EVEN MORE
WORK
A PHP/MYSQL PAGE
REQUEST
A PHP/MYSQL PAGE
REQUEST
WE WANT TO MINIMIZE THE
AMOUNT OF WORK DONE
BY OUR SERVER, PHP AND
MYSQL
HTTP HEADERS
“The easiest request to serve is the one never
sent at all.”
I just made this quote up.
Your logo image isn't going to change when going from your
homepage to a single blog post…
So why make the browser even re...
FAR FUTURE EXPIRES
HEADER
Tell the browser how long the copy of the file is valid
Cached files that are valid are not re-d...
WHAT DOES THAT LOOK
LIKE?
Add this to your file:.htaccess
<ifmodulemod_expires.c="">
ExpiresActiveon
ExpiresDefault "acces...
The HTML5 Boiler Plate project's .htaccess file
Read the docs
View the source
BUT WHAT IF THE
IMAGE/JS/CSS FILE
CHANGES?
The browser will keep loading the resource from it's local
cache
>
And then you have to clear the browser cache or hard
refresh the page (Shift + Refresh).
WE NEED CACHE-BUSTING
FILENAMES!
WordPress' and
supports this
wp_enqeue_script() wp_enqueue_style()
wp_enqueue_script($han...
But then every time you update your JavaScript or CSS you
need to change the $vervariable to bust the cache…
SO I WROTE A PLUGIN
CDN Friendly CSS and JS URLs in WordPress
/theme/css/2013-09-12_5:21/my-style.css
maps to
/theme/css/m...
CDNS
CONTENT DELIVERY
NETWORKS (CDNS)
Set of servers in multiple data centers around the world to
serve content with high avail...
CDNs serve their copy of a file, if available, sparing your
server from the traffic.
If the CDN doesn't have a copy of the file, it passes the
request back to the origin.
TWO TYPES OF CDNS
1. Push - assets get uploaded to the CDN manually, you link
directly to it
2. Pull - The CDN is a proxy ...
DNS CHANGES NEEDED FOR
PULL CDNS
cdn.example.com masks ugly CDN URL (CNAME)
DNS CHANGES NEEDED FOR
PULL CDNS
example.com points to origin IP Address (A Record)
The CDN uses the Expires header to determine if cached
asset is stale or not.
Stale requests get passed to the origin serv...
Some CDNs and proxies
. So avoid it if you can.
don't cache URLs with a query
string
BAD
http://www.example.com/js/file.js...
If you cache your HTML via a CDN then if your origin server
goes down your site will still be served. Visitors won't even
...
Distributing content across the world, visitors will download
from a server closer to them.
CDN PROVIDERS
Akamai
EdgeCast
Amazon Cloudfront
MaxCDN
CloudFlare
FULL PAGE
CACHING
Full page caching takes the result of a page request from
WordPress and saves it as a static HTML file that will be
served...
This reduces the load on PHP and MySQL
CACHING PLUGINS
(Advandced, lots of options)
(Easier set-up)
(Multi-server environment)
(For low-resource hosts)
W3 Total ...
CACHING PLUGIN TIPS
Don't cache pages for logged in users
Don't cache POST requests
Do serve cached files from mod_rewrite...
PHP CACHING
WORDPRESS' CACHING APIS
Transients API
WP Object Cache
TRANSIENTS API
Used to store data that can expire at any time
Has an expiration to invalidate the data
Uses the wp_options...
TRANSIENTS API
FUNCTIONS
set_transient()
get_transient()
delete_transient()
MULTISITE TRANSIENTS API
FUNCTIONS
set_site_transient()
get_site_transient()
delete_site_transient()
TRANSIENTS EXAMPLE
$my_transient=get_transient('my_transient');
if($my_transient==false){
//Dosomecomplicatedtaskworthcach...
TIME CONSTANTS
As of WordPress 3.5 several constants were introduced to
easily express time
MINUTE_IN_SECONDS =60(seconds)...
TRANSIENTS API IS IDEAL
FOR…
Fetching RSS feeds
Storing an external API call
Caching a complex query
ANYTHING that needs t...
WP OBJECT CACHE
WordPress' internal class for caching data.
See http://codex.wordpress.org/Class_Reference/WP_Object_Cache
CACHING PERSISTANCE
WP_Object_Cache data isn't saved between page requests
by default.
If an object cache is available, WP...
WP_CACHE FUNCTIONS
Don't call WP_Object_Cache Class directly!
wp_cache_add($key,$data,$group,$expire);
wp_cache_set($key,$...
WHEN SHOULD WE USE
THIS?
OBJECT
CACHING
WHAT IS OBJECT CACHING?
Distributed, in-memory key-value store for
small chunks of data.
(not distributed)
Memcached
Redis...
UH… IN ENGLISH?
Store Transients API and WP Object Cache items in
memory between requests
Make it available to multiple se...
HOW DO I ENABLE OBJET
CACHING?
1. Download and install or or on
your server
2. Add the appropriate object-cache.phpfile to...
OPCODE
CACHING
WHAT DOES OPCODE
CACHING DO?
PHP is written in a human-readable syntax
When run, PHP is compiled to opcode that a computer...
See Scaling WordPress
See Scaling WordPress
OPCODE CACHES
Alternative PHP Cache (APC)
eAccelerator
XCache
Zend Optimizer+
WHICH OPCODE CACHE TO
USE?
Zend Optimizer+ will be bundled with PHP 5.5
See http://halfelf.org/2013/trading-apc-for-zend/
BENCHMARKS
PHP (No Opcode Cache) ~40
APC ~260
Zend Optimizer + ~307
Number of Requests per second
See http://www.ricardcla...
MYSQL
CACHING
MYSQL'S QUERY CACHE
Cache's result for frequently used SELECTstatements
Any INSERT, UPDATE, or DELETEstatement flushes the...
TO SUMMARIZE
Leverage browser caching via HTTP headers
Use a CDN if you can or a full-page caching plugin
WordPress' caching APIs are h...
MORE READING
1. by Zack Tollman
2. by Joseph Scott
3. by Ryan
Burnette
4. by WordPress.com VIP
5.
by Erick Hitter
6. by Sc...
IN
CONCLUSION
THANK YOU!
@kingkool68
Cache Rules Everything Around Me
Cache Rules Everything Around Me
Cache Rules Everything Around Me
Cache Rules Everything Around Me
Cache Rules Everything Around Me
Cache Rules Everything Around Me
Upcoming SlideShare
Loading in …5
×

Cache Rules Everything Around Me

2,546 views

Published on

My presentation about WordPress and caching from WordCamp Baltimore 2013.

See it with funny animated GIFs at http://kingkool68.com/wp-cream/
Fork my slides on GitHub https://github.com/kingkool68/WP-Cache-Rules-Everything-Around-Me

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,546
On SlideShare
0
From Embeds
0
Number of Embeds
15
Actions
Shares
0
Downloads
6
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Cache Rules Everything Around Me

  1. 1. CACHE RULES EVERYTHING AROUND MEpresented at WordCamp Baltimore September 21 2013
  2. 2. HI, I'M RUSSELL HEIMLICH (Heimlich, like the maneuver) Head Cache Invalidator at the Pew Research Center
  3. 3. FOLLOW ALONG v.gd/wpcream
  4. 4. BUT FIRST A STORY…
  5. 5. 2006 - 2009 I worked at USNews & World Report
  6. 6. MONTHS OF WORK GO IN TO THE RELEASE OF NEW RANKINGS.
  7. 7. ON LAUNCH DAY WE ALWAYS SEE A HUGE TRAFFIC SPIKE But one year we got lucky…
  8. 8. The marketing/biz dev team managed to get us featured on the homepage of a major web portal! (And by featured I mean the featured story on their homepage)
  9. 9. WE WERE GOING TO BE FEATURED ON… (Before their CEO discovered Adobe Illustrator)
  10. 10. WE WERE EXCITED!
  11. 11. Ok maybe we looked more like this…
  12. 12. The story went live on Yahoo.com and we watched…
  13. 13. The servers started getting slower…
  14. 14. Editors were calling us saying they couldn't get in to the admin area…
  15. 15. Our servers were completely down…
  16. 16. We had to call Yahoo! and have them remove the story because we couldn't handle the traffic…
  17. 17. WE LASTED 15 MINUTES.
  18. 18. PERFORMANCE AND UPTIME ARE IMPORTANT! And caching can help.
  19. 19. P.S. Don't feel bad for USNews
  20. 20. WHAT IS CACHING?
  21. 21. CACHE “a component that transparently stores data so that future requests for that data can be served faster.” — via Wikipedia, Cache (Computing)
  22. 22. A cache may contain values computed earlier or duplicate values stored elsewhere.
  23. 23. A cache hit can complete the request by reading the value from the cache.
  24. 24. A cache miss has to be recomputed or fetched from another location which is much slower.
  25. 25. The more requests that can be served from a cache, the faster the system performs. The faster the system, the more requests it can handle.
  26. 26. A REAL-WORLD EXAMPLE You're taking 5 classes and need to write 5 essays…
  27. 27. You could write 5 separate essays OR You could write one essay and use it for all of your classes
  28. 28. THAT'S CACHING!
  29. 29. There are many (potential) layers of caching involved in a single web request.
  30. 30. HOW DOES A REQUEST WORK?
  31. 31. A BASIC REQUEST
  32. 32. A BASIC REQUEST
  33. 33. PHP PAGES TAKE LONGER TO SERVE
  34. 34. A PHP PAGE REQUEST
  35. 35. A PHP PAGE REQUEST
  36. 36. A PHP PAGE WITH MYSQL DATA TAKES EVEN MORE WORK
  37. 37. A PHP/MYSQL PAGE REQUEST
  38. 38. A PHP/MYSQL PAGE REQUEST
  39. 39. WE WANT TO MINIMIZE THE AMOUNT OF WORK DONE BY OUR SERVER, PHP AND MYSQL
  40. 40. HTTP HEADERS
  41. 41. “The easiest request to serve is the one never sent at all.” I just made this quote up.
  42. 42. Your logo image isn't going to change when going from your homepage to a single blog post… So why make the browser even request it?
  43. 43. FAR FUTURE EXPIRES HEADER Tell the browser how long the copy of the file is valid Cached files that are valid are not re-downloaded from the server
  44. 44. WHAT DOES THAT LOOK LIKE? Add this to your file:.htaccess <ifmodulemod_expires.c=""> ExpiresActiveon ExpiresDefault "accessplus1month" ExpiresByTypeimage/gif "accessplus1month" ExpiresByTypeimage/jpeg "accessplus1month" ExpiresByTypeimage/png "accessplus1month" </ifmodule>
  45. 45. The HTML5 Boiler Plate project's .htaccess file Read the docs View the source
  46. 46. BUT WHAT IF THE IMAGE/JS/CSS FILE CHANGES? The browser will keep loading the resource from it's local cache
  47. 47. > And then you have to clear the browser cache or hard refresh the page (Shift + Refresh).
  48. 48. WE NEED CACHE-BUSTING FILENAMES! WordPress' and supports this wp_enqeue_script() wp_enqueue_style() wp_enqueue_script($handle,$src,$deps,$ver,$in_footer); wp_enqueue_style($handle,$src,$deps,$ver,$media); which outputs a script like this my-super-neato-script.js?ver=3.6.1 my-trendy-styles.css?ver=3.6.1
  49. 49. But then every time you update your JavaScript or CSS you need to change the $vervariable to bust the cache…
  50. 50. SO I WROTE A PLUGIN CDN Friendly CSS and JS URLs in WordPress /theme/css/2013-09-12_5:21/my-style.css maps to /theme/css/my-style.css
  51. 51. CDNS
  52. 52. CONTENT DELIVERY NETWORKS (CDNS) Set of servers in multiple data centers around the world to serve content with high availability and performance.
  53. 53. CDNs serve their copy of a file, if available, sparing your server from the traffic.
  54. 54. If the CDN doesn't have a copy of the file, it passes the request back to the origin.
  55. 55. TWO TYPES OF CDNS 1. Push - assets get uploaded to the CDN manually, you link directly to it 2. Pull - The CDN is a proxy saving requests that are passed through it See Push vs. Pull CDNs
  56. 56. DNS CHANGES NEEDED FOR PULL CDNS cdn.example.com masks ugly CDN URL (CNAME)
  57. 57. DNS CHANGES NEEDED FOR PULL CDNS example.com points to origin IP Address (A Record)
  58. 58. The CDN uses the Expires header to determine if cached asset is stale or not. Stale requests get passed to the origin server
  59. 59. Some CDNs and proxies . So avoid it if you can. don't cache URLs with a query string BAD http://www.example.com/js/file.js?2013-09-12 GOOD http://www.example.com/js/2013-09-12/file.js http://www.example.com/js/file.2013-09-12.js
  60. 60. If you cache your HTML via a CDN then if your origin server goes down your site will still be served. Visitors won't even know.
  61. 61. Distributing content across the world, visitors will download from a server closer to them.
  62. 62. CDN PROVIDERS Akamai EdgeCast Amazon Cloudfront MaxCDN CloudFlare
  63. 63. FULL PAGE CACHING
  64. 64. Full page caching takes the result of a page request from WordPress and saves it as a static HTML file that will be served up the next time.
  65. 65. This reduces the load on PHP and MySQL
  66. 66. CACHING PLUGINS (Advandced, lots of options) (Easier set-up) (Multi-server environment) (For low-resource hosts) W3 Total Cache WP Super Cache Batcache Hyper Cache
  67. 67. CACHING PLUGIN TIPS Don't cache pages for logged in users Don't cache POST requests Do serve cached files from mod_rewrite(not PHP) Don't serve a separate mobile version (use responsive design) Make sure it is working!
  68. 68. PHP CACHING
  69. 69. WORDPRESS' CACHING APIS Transients API WP Object Cache
  70. 70. TRANSIENTS API Used to store data that can expire at any time Has an expiration to invalidate the data Uses the wp_options table or an object cache See http://codex.wordpress.org/Transients_API
  71. 71. TRANSIENTS API FUNCTIONS set_transient() get_transient() delete_transient()
  72. 72. MULTISITE TRANSIENTS API FUNCTIONS set_site_transient() get_site_transient() delete_site_transient()
  73. 73. TRANSIENTS EXAMPLE $my_transient=get_transient('my_transient'); if($my_transient==false){ //Dosomecomplicatedtaskworthcaching $my_transient='Somethingcomplicated'; set_transient('my_transient',$my_transient,12*HOUR_IN_SECONDS); }
  74. 74. TIME CONSTANTS As of WordPress 3.5 several constants were introduced to easily express time MINUTE_IN_SECONDS =60(seconds) HOUR_IN_SECONDS =60*MINUTE_IN_SECONDS DAY_IN_SECONDS =24*HOUR_IN_SECONDS WEEK_IN_SECONDS =7*DAY_IN_SECONDS YEAR_IN_SECONDS =365*DAY_IN_SECONDS
  75. 75. TRANSIENTS API IS IDEAL FOR… Fetching RSS feeds Storing an external API call Caching a complex query ANYTHING that needs to expire at some time
  76. 76. WP OBJECT CACHE WordPress' internal class for caching data. See http://codex.wordpress.org/Class_Reference/WP_Object_Cache
  77. 77. CACHING PERSISTANCE WP_Object_Cache data isn't saved between page requests by default. If an object cache is available, WP_Object_Cache will use that instead
  78. 78. WP_CACHE FUNCTIONS Don't call WP_Object_Cache Class directly! wp_cache_add($key,$data,$group,$expire); wp_cache_set($key,$data,$group,$expire); wp_cache_get($key,$group='',$force=false,$found=null); wp_cache_delete($key,$group); wp_cache_replace($key,$data,$group,$expire)
  79. 79. WHEN SHOULD WE USE THIS?
  80. 80. OBJECT CACHING
  81. 81. WHAT IS OBJECT CACHING? Distributed, in-memory key-value store for small chunks of data. (not distributed) Memcached Redis APC
  82. 82. UH… IN ENGLISH? Store Transients API and WP Object Cache items in memory between requests Make it available to multiple servers RAM is way faster than disk!
  83. 83. HOW DO I ENABLE OBJET CACHING? 1. Download and install or or on your server 2. Add the appropriate object-cache.phpfile to your wp- content folder Memcached Redis APC See: or or Memcached Object Cache Plugin WordPress Redis Backend APC Object Cache Backend
  84. 84. OPCODE CACHING
  85. 85. WHAT DOES OPCODE CACHING DO? PHP is written in a human-readable syntax When run, PHP is compiled to opcode that a computer understands An opcode cache speeds up the execution of PHP
  86. 86. See Scaling WordPress
  87. 87. See Scaling WordPress
  88. 88. OPCODE CACHES Alternative PHP Cache (APC) eAccelerator XCache Zend Optimizer+
  89. 89. WHICH OPCODE CACHE TO USE? Zend Optimizer+ will be bundled with PHP 5.5 See http://halfelf.org/2013/trading-apc-for-zend/
  90. 90. BENCHMARKS PHP (No Opcode Cache) ~40 APC ~260 Zend Optimizer + ~307 Number of Requests per second See http://www.ricardclau.com/2013/03/apc-vs-zend-optimizer-benchmarks- with-symfony2/
  91. 91. MYSQL CACHING
  92. 92. MYSQL'S QUERY CACHE Cache's result for frequently used SELECTstatements Any INSERT, UPDATE, or DELETEstatement flushes the query cache See MySQL Query Cache Documentation
  93. 93. TO SUMMARIZE
  94. 94. Leverage browser caching via HTTP headers Use a CDN if you can or a full-page caching plugin WordPress' caching APIs are helpful Set-up object caching on your server Utilize an opcode cache to speed up PHP Make sure MySQL's query_cacheis turned on
  95. 95. MORE READING 1. by Zack Tollman 2. by Joseph Scott 3. by Ryan Burnette 4. by WordPress.com VIP 5. by Erick Hitter 6. by Scott Taylor Core Caching Concepts in WordPress Scaling WordPress WordPress Fragment Caching Revisited Caching Caching, Scaling, and What I've Learned Programming for WordPress.com VIP WordPress + Memcached
  96. 96. IN CONCLUSION
  97. 97. THANK YOU! @kingkool68

×