cache rules everything around me

Post on 06-May-2015

2.134 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

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

CACHE RULESEVERYTHINGAROUND ME

presented atWordCamp Baltimore

September 21 2013

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

Head Cache Invalidator at the Pew Research Center

FOLLOW ALONGv.gd/wpcream

BUT FIRST ASTORY…

2006 - 2009 I worked at USNews & World Report

MONTHS OF WORK GO IN TO THERELEASE OF NEW RANKINGS.

ON LAUNCH DAY WEALWAYS SEE A HUGE

TRAFFIC SPIKEBut one year we got lucky…

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)

WE WERE GOING TO BEFEATURED 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 theadmin area…

Our servers were completely down…

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

WE LASTED 15 MINUTES.

PERFORMANCE AND UPTIMEARE IMPORTANT!

And caching can help.

P.S. Don't feel bad for USNews

WHAT ISCACHING?

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

served faster.”

— via Wikipedia, Cache (Computing)

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

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

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

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

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

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

You could write 5 separate essays

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

THAT'S CACHING!

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

HOW DOES AREQUESTWORK?

A BASIC REQUEST

A BASIC REQUEST

PHP PAGESTAKE LONGERTO SERVE

A PHP PAGE REQUEST

A PHP PAGE REQUEST

A PHP PAGEWITH MYSQLDATA TAKESEVEN MOREWORK

A PHP/MYSQL PAGEREQUEST

A PHP/MYSQL PAGEREQUEST

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

MYSQL

HTTP HEADERS

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

I just made this quote up.

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?

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

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>

BUT WHAT IF THEIMAGE/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 hardrefresh the page (Shift + Refresh).

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

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

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

CDNS

CONTENT DELIVERYNETWORKS (CDNS)

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

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

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

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

DNS CHANGES NEEDED FORPULL CDNS

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

DNS CHANGES NEEDED FORPULL CDNS

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

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

Stale requests get passed to the origin server

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

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.

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

FULL PAGECACHING

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.

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 CacheWP Super CacheBatcacheHyper Cache

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!

PHP CACHING

WORDPRESS' CACHING APISTransients APIWP Object Cache

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

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 );}

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

TRANSIENTS API IS IDEALFOR…

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

WP OBJECT CACHEWordPress' internal class for caching data.

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

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

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 )

WHEN SHOULD WE USETHIS?

OBJECTCACHING

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

small chunks of data.

(not distributed)

MemcachedRedisAPC

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

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

OPCODECACHING

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

WHICH OPCODE CACHE TOUSE?

Zend Optimizer+ will be bundled with PHP 5.5

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

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/

MYSQLCACHING

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

See MySQL Query Cache Documentation

TO SUMMARIZE

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

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

INCONCLUSION

THANK YOU!@kingkool68

top related