cache rules everything around me

103

Upload: russell-heimlich

Post on 06-May-2015

2.134 views

Category:

Technology


2 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Cache Rules Everything Around Me
Page 2: Cache Rules Everything Around Me
Page 3: Cache Rules Everything Around Me
Page 4: Cache Rules Everything Around Me

CACHE RULESEVERYTHINGAROUND ME

presented atWordCamp Baltimore

September 21 2013

Page 5: Cache Rules Everything Around Me

HI, I'M RUSSELL HEIMLICH(Heimlich, like the maneuver)

Head Cache Invalidator at the Pew Research Center

Page 6: Cache Rules Everything Around Me

FOLLOW ALONGv.gd/wpcream

Page 7: Cache Rules Everything Around Me

BUT FIRST ASTORY…

Page 8: Cache Rules Everything Around Me

2006 - 2009 I worked at USNews & World Report

Page 9: Cache Rules Everything Around Me
Page 10: Cache Rules Everything Around Me

MONTHS OF WORK GO IN TO THERELEASE OF NEW RANKINGS.

Page 11: Cache Rules Everything Around Me

ON LAUNCH DAY WEALWAYS SEE A HUGE

TRAFFIC SPIKEBut one year we got lucky…

Page 12: Cache Rules Everything Around Me

The marketing/biz dev team managed to get us featured onthe homepage of a major web portal!

(And by featured I mean the featured story on their homepage)

Page 13: Cache Rules Everything Around Me

WE WERE GOING TO BEFEATURED ON…

(Before their CEO discovered Adobe Illustrator)

Page 14: Cache Rules Everything Around Me

WE WERE EXCITED!

Page 15: Cache Rules Everything Around Me

Ok maybe we looked more like this…

Page 16: Cache Rules Everything Around Me

The story went live on Yahoo.com and we watched…

Page 17: Cache Rules Everything Around Me

The servers started getting slower…

Page 18: Cache Rules Everything Around Me

Editors were calling us saying they couldn't get in to theadmin area…

Page 19: Cache Rules Everything Around Me

Our servers were completely down…

Page 20: Cache Rules Everything Around Me

We had to call Yahoo! and have them remove the storybecause we couldn't handle the traffic…

Page 21: Cache Rules Everything Around Me

WE LASTED 15 MINUTES.

Page 22: Cache Rules Everything Around Me

PERFORMANCE AND UPTIMEARE IMPORTANT!

And caching can help.

Page 23: Cache Rules Everything Around Me

P.S. Don't feel bad for USNews

Page 24: Cache Rules Everything Around Me

WHAT ISCACHING?

Page 25: Cache Rules Everything Around Me

CACHE“a component that transparently stores dataso that future requests for that data can be

served faster.”

— via Wikipedia, Cache (Computing)

Page 26: Cache Rules Everything Around Me

A cache may contain values computed earlier or duplicatevalues stored elsewhere.

Page 27: Cache Rules Everything Around Me

A cache hit can complete the request by reading the valuefrom the cache.

Page 28: Cache Rules Everything Around Me

A cache miss has to be recomputed or fetched fromanother location which is much slower.

Page 29: Cache Rules Everything Around Me

The more requests that can be served from a cache, thefaster the system performs.

The faster the system, the more requests it can handle.

Page 30: Cache Rules Everything Around Me

A REAL-WORLD EXAMPLEYou're taking 5 classes and need to write 5 essays…

Page 31: Cache Rules Everything Around Me

You could write 5 separate essays

ORYou could write one essay and use it for all of your classes

Page 32: Cache Rules Everything Around Me

THAT'S CACHING!

Page 33: Cache Rules Everything Around Me

There are many (potential) layers of caching involved in asingle web request.

Page 34: Cache Rules Everything Around Me

HOW DOES AREQUESTWORK?

Page 35: Cache Rules Everything Around Me

A BASIC REQUEST

Page 36: Cache Rules Everything Around Me

A BASIC REQUEST

Page 37: Cache Rules Everything Around Me

PHP PAGESTAKE LONGERTO SERVE

Page 38: Cache Rules Everything Around Me

A PHP PAGE REQUEST

Page 39: Cache Rules Everything Around Me

A PHP PAGE REQUEST

Page 40: Cache Rules Everything Around Me

A PHP PAGEWITH MYSQLDATA TAKESEVEN MOREWORK

Page 41: Cache Rules Everything Around Me

A PHP/MYSQL PAGEREQUEST

Page 42: Cache Rules Everything Around Me

A PHP/MYSQL PAGEREQUEST

Page 43: Cache Rules Everything Around Me

WE WANT TO MINIMIZE THEAMOUNT OF WORK DONEBY OUR SERVER, PHP AND

MYSQL

Page 44: Cache Rules Everything Around Me

HTTP HEADERS

Page 45: Cache Rules Everything Around Me

“The easiest request to serve is the one neversent at all.”

I just made this quote up.

Page 46: Cache Rules Everything Around Me

Your logo image isn't going to change when going from yourhomepage to a single blog post…

So why make the browser even request it?

Page 47: Cache Rules Everything Around Me

FAR FUTURE EXPIRESHEADER

Tell the browser how long the copy of the file is validCached files that are valid are not re-downloaded fromthe server

Page 48: Cache Rules Everything Around Me

WHAT DOES THAT LOOKLIKE?

Add this to your file:.htaccess

<ifmodule mod_expires.c="">

ExpiresActive on ExpiresDefault "access plus 1 month"

ExpiresByType image/gif "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/png "access plus 1 month"

</ifmodule>

Page 50: Cache Rules Everything Around Me

BUT WHAT IF THEIMAGE/JS/CSS FILE

CHANGES?The browser will keep loading the resource from it's local

cache

Page 51: Cache Rules Everything Around Me

>

And then you have to clear the browser cache or hardrefresh the page (Shift + Refresh).

Page 52: Cache Rules Everything Around Me

WE NEED CACHE-BUSTINGFILENAMES!

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.1my-trendy-styles.css?ver=3.6.1

Page 53: Cache Rules Everything Around Me

But then every time you update your JavaScript or CSS youneed to change the $ver variable to bust the cache…

Page 54: Cache Rules Everything Around Me

SO I WROTE A PLUGINCDN Friendly CSS and JS URLs in WordPress

/theme/css/2013-09-12_5:21/my-style.css

maps to

/theme/css/my-style.css

Page 55: Cache Rules Everything Around Me

CDNS

Page 56: Cache Rules Everything Around Me

CONTENT DELIVERYNETWORKS (CDNS)

Set of servers in multiple data centers around the world toserve content with high availability and performance.

Page 57: Cache Rules Everything Around Me

CDNs serve their copy of a file, if available, sparing yourserver from the traffic.

Page 58: Cache Rules Everything Around Me

If the CDN doesn't have a copy of the file, it passes therequest back to the origin.

Page 59: Cache Rules Everything Around Me

TWO TYPES OF CDNS1. Push - assets get uploaded to the CDN manually, you link

directly to it2. Pull - The CDN is a proxy saving requests that are passed

through itSee Push vs. Pull CDNs

Page 60: Cache Rules Everything Around Me

DNS CHANGES NEEDED FORPULL CDNS

cdn.example.com masks ugly CDN URL (CNAME)

Page 61: Cache Rules Everything Around Me

DNS CHANGES NEEDED FORPULL CDNS

example.com points to origin IP Address (A Record)

Page 62: Cache Rules Everything Around Me

The CDN uses the Expires header to determine if cachedasset is stale or not.

Stale requests get passed to the origin server

Page 63: Cache Rules Everything Around Me

Some CDNs and proxies . So avoid it if you can.

don't cache URLs with a querystring

BADhttp://www.example.com/js/file.js?2013-09-12

GOODhttp://www.example.com/js/2013-09-12/file.jshttp://www.example.com/js/file.2013-09-12.js

Page 64: Cache Rules Everything Around Me

If you cache your HTML via a CDN then if your origin servergoes down your site will still be served. Visitors won't even

know.

Page 65: Cache Rules Everything Around Me

Distributing content across the world, visitors will downloadfrom a server closer to them.

Page 67: Cache Rules Everything Around Me

FULL PAGECACHING

Page 68: Cache Rules Everything Around Me

Full page caching takes the result of a page request fromWordPress and saves it as a static HTML file that will be

served up the next time.

Page 69: Cache Rules Everything Around Me

This reduces the load on PHP and MySQL

Page 70: Cache Rules Everything Around Me

CACHING PLUGINS (Advandced, lots of options) (Easier set-up)

(Multi-server environment) (For low-resource hosts)

W3 Total CacheWP Super CacheBatcacheHyper Cache

Page 71: Cache Rules Everything Around Me

CACHING PLUGIN TIPSDon't cache pages for logged in usersDon't cache POST requestsDo serve cached files from mod_rewrite (not PHP)Don't serve a separate mobile version (use responsivedesign)Make sure it is working!

Page 72: Cache Rules Everything Around Me

PHP CACHING

Page 73: Cache Rules Everything Around Me

WORDPRESS' CACHING APISTransients APIWP Object Cache

Page 74: Cache Rules Everything Around Me

TRANSIENTS APIUsed to store data that can expire at any timeHas an expiration to invalidate the dataUses the wp_options table or an object cache

See http://codex.wordpress.org/Transients_API

Page 77: Cache Rules Everything Around Me

TRANSIENTS EXAMPLE$my_transient = get_transient( 'my_transient' );if( $my_transient == false ) { //Do some complicated task worth caching $my_transient = 'Something complicated'; set_transient( 'my_transient', $my_transient, 12 * HOUR_IN_SECONDS );}

Page 78: Cache Rules Everything Around Me

TIME CONSTANTSAs of WordPress 3.5 several constants were introduced to

easily express time

MINUTE_IN_SECONDS = 60 (seconds)HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDSDAY_IN_SECONDS = 24 * HOUR_IN_SECONDSWEEK_IN_SECONDS = 7 * DAY_IN_SECONDSYEAR_IN_SECONDS = 365 * DAY_IN_SECONDS

Page 79: Cache Rules Everything Around Me

TRANSIENTS API IS IDEALFOR…

Fetching RSS feedsStoring an external API callCaching a complex queryANYTHING that needs to expire at some time

Page 80: Cache Rules Everything Around Me

WP OBJECT CACHEWordPress' internal class for caching data.

See http://codex.wordpress.org/Class_Reference/WP_Object_Cache

Page 81: Cache Rules Everything Around Me

CACHING PERSISTANCEWP_Object_Cache data isn't saved between page requests

by default.If an object cache is available, WP_Object_Cache will use that

instead

Page 82: Cache Rules Everything Around Me

WP_CACHE FUNCTIONSDon'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 )

Page 83: Cache Rules Everything Around Me

WHEN SHOULD WE USETHIS?

Page 84: Cache Rules Everything Around Me

OBJECTCACHING

Page 85: Cache Rules Everything Around Me

WHAT IS OBJECT CACHING?Distributed, in-memory key-value store for

small chunks of data.

(not distributed)

MemcachedRedisAPC

Page 86: Cache Rules Everything Around Me

UH… IN ENGLISH?Store Transients API and WP Object Cache items inmemory between requestsMake it available to multiple serversRAM is way faster than disk!

Page 87: Cache Rules Everything Around Me

HOW DO I ENABLE OBJETCACHING?

1. Download and install or or onyour server

2. Add the appropriate object-cache.php file to your wp-content folder

Memcached Redis APC

See: or

orMemcached Object Cache PluginWordPress Redis BackendAPC Object Cache Backend

Page 88: Cache Rules Everything Around Me

OPCODECACHING

Page 89: Cache Rules Everything Around Me

WHAT DOES OPCODECACHING DO?

PHP is written in a human-readable syntaxWhen run, PHP is compiled to opcode that a computerunderstandsAn opcode cache speeds up the execution of PHP

Page 93: Cache Rules Everything Around Me

WHICH OPCODE CACHE TOUSE?

Zend Optimizer+ will be bundled with PHP 5.5

See http://halfelf.org/2013/trading-apc-for-zend/

Page 94: Cache Rules Everything Around Me

BENCHMARKSPHP (No Opcode Cache) ~40APC ~260Zend Optimizer + ~307

Number of Requests per second

See http://www.ricardclau.com/2013/03/apc-vs-zend-optimizer-benchmarks-with-symfony2/

Page 95: Cache Rules Everything Around Me

MYSQLCACHING

Page 96: Cache Rules Everything Around Me

MYSQL'S QUERY CACHECache's result for frequently used SELECT statementsAny INSERT, UPDATE, or DELETE statement flushes thequery cache

See MySQL Query Cache Documentation

Page 97: Cache Rules Everything Around Me

TO SUMMARIZE

Page 98: Cache Rules Everything Around Me

Leverage browser caching via HTTP headersUse a CDN if you can or a full-page caching pluginWordPress' caching APIs are helpfulSet-up object caching on your serverUtilize an opcode cache to speed up PHPMake sure MySQL's query_cache is turned on

Page 99: Cache Rules Everything Around Me

MORE READING1. by Zack Tollman2. by Joseph Scott3. by Ryan

Burnette4. by WordPress.com VIP5.

by Erick Hitter6. by Scott Taylor

Core Caching Concepts in WordPressScaling WordPressWordPress Fragment Caching Revisited

CachingCaching, Scaling, and What I've Learned Programmingfor WordPress.com VIPWordPress + Memcached

Page 100: Cache Rules Everything Around Me

INCONCLUSION

Page 101: Cache Rules Everything Around Me
Page 102: Cache Rules Everything Around Me
Page 103: Cache Rules Everything Around Me

THANK YOU!@kingkool68