SlideShare a Scribd company logo
Less and faster
Caching tips for WordPress
developers
Who, where, and why?
Premium hosting
and upkeep for
WordPress
HTTP/2
TESTED
UPDATES
24/7 UPKEEP
Top-notch performance
A comparison published by a
Google employee at
ismyhostfastyet.com
confirms that Seravo’s
customer sites load faster
than competing services’.
The study used
time-to-first-byte (TTFB)
measurement data from real
users as collected from the
Chrome browser UX data. Fast/Average/Slow TTFB by WordPress Host
“There are only two hard
things in Computer Science:
cache invalidation and
naming things.”
– Phil Karlton
Caches are everywhere
● Inside the CPU (levels L1-L4).
○ No need to retrieve data from RAM over and over again.
● In operating system (Linux) to protect the hard drives.
○ Prevents different programs from continuously reading the same file from the hard drive.
● Some programs have built-in caches:
○ PHP
■ Saves files so that there is no need to download them from the hard drive every second.
■ Saves the interpreted PHP code so that it does not have to be constantly recompiled.
○ Database
■ Uses plenty of cache (RAM) so that the hard drive does not need to be read as often.
○ WordPress
■ Stores transients in the database so that the following queries do not have to be as
extensive.
...and these are just couple of examples. The list is long.
Caches are everywhere, because...?
● Speed!
○ Can you say instantly how much is 5 times 5? Yes, because the
result is already in your memory.
○ How about 55 times 555? Hmm… Probably have to count that one.
● Not everything can be stored in the memory, so it is a good idea to save
only things you are likely need several times again later on.
The numbers every coder should know
● Retrieval times for different types of memories:
○ L1 cache: 1 nanosecond
○ L2 cache: 3 ns
○ L3 cache: 10 ns
○ RAM: 25 ns
○ PCIe NVMe hard drive: 2000 ns – most Seravo customers
○ SSD hard drive: 100 000 ns – few Seravo customers
○ HDD hard drive: 10 000 000 ns – none of Seravo’s customers
○ Tampere-Berlin ping: 30 000 000 ns
○ HTML-page from Nginx 2 000 000 ns
○ HTML-page from PHP/WP 50 000 000 – 1 000 000 000 ns
Should the cache contain everything?
● Not everything can be stored in the memory, so you
should only store things that will most likely be
needed twice or more.
● If something is not needed, clear the cache:
○ Clearing by command, so called “cache purge”.
○ A built-in mechanism, e.g. a counter to tell how many times the data has been retrieved
in the past hour.
● The cache can be cleared at any time, and some
systems do so on a regular basis.
● In addition, the cache can expire.
Difficult: Cache invalidation
● In what time will the cache expire?
○ 5 seconds?
○ 60 seconds?
○ 15 minutes?
○ 7 days?
● It depends. That is why it is so difficult.
Cache concepts
Retrieval time – has to be faster from cache than the source in order to get savings.
Invalidation – the criteria for deleting data from the cache.
Expiry – the time in which the data expires and is removed from the cache.
Bypass – intentionally bypasses the cache.
Miss – if the cache is empty, retrieves the latest data.
Hit rate – hit/miss-ratio, how often the data was found in the cache (ideally 99,99 %).
Caches in
WordPress sites
For a WP developer to consider
● Browser HTTP cache
○ Always the fastest!
● Server HTTP cache
○ Nginx, Varnish, Cloudflare, Fastly etc.
● WordPress transients
○ get_transient(key);
● WordPress object cache
○ wp_cache_get(key);
● File system cache
● MariaDB database cache
See also: https://seravo.com/tag/cache/
No, another
plugin is not
the way to go.
It might be a band-aid,
at best.
Browser HTTP cache
● Objective: to avoid unnecessary network traffic.
● The browser stores pages and files purely based on
what the HTTP headers say.
● Make sure your site sends sensible HTTP headers and
content expiration dates.
● WordPress does not do this as a standard.
An example: WP 5.3.2 CSS file
$ curl -IL https://seravo.com/wp-includes/css/dist/block-library/style.min.css?ver=5.3.2
HTTP/2 200
server: nginx
date: Wed, 29 Apr 2020 05:33:47 GMT
content-type: text/css
last-modified: Tue, 28 Apr 2020 11:42:09 GMT
etag: "5ea81691-1d52e"
expires: Thu, 07 May 2020 05:33:45 GMT
cache-control: max-age=691200
x-proxy-cache: HIT P: A: N: H:0 O: S:
x-powered-by: Seravo
x-seravo-request-id: dd1d5d1e649b5f675269a54e86dabacb
The server tells the browser that the content is valid for seven days. The length of the time
does not matter.
However, the content in the address style.min.css?ver=5.3.2 stays the same so it must be
updated with a new version number if the content is updated. Otherwise the page will be
“broken” for seven days for old visitors.
An example: theme’s CSS file
wp_enqueue_style(
'seravo', get_stylesheet_directory_uri() . '/dist/layout.min.css',
false,
wp_get_theme()->get('Version')
);
=> https://seravo.com/wp-content/themes/seravo/dist/layout.min.css?ver=1.2.3
If you download style files or scripts without version numbers, the browser will always have the
same layout.min.css.
However, if you add the version number, the download happens with an address
layout.min.css?ver=1.2.3 which ensures that whenever there is a new version of the theme,
the browser will also download a new version of the style file.
An example: seravo.com CSS file
wp_enqueue_style(
'seravo', get_stylesheet_directory_uri() . '/dist/layout.min.css',
false,
seravo_get_git_commit_id()
);
=> https://seravo.com/wp-content/themes/seravo/dist/layout.min.css?ver=c98272d0
function seravo_get_git_commit_id() {
// Don't use shell_exec('git rev-parse --short HEAD') or similar since it
// would spawn a shell session on every WordPress load of every page.
// Instead read directly from .git/logs/HEAD to as efficient as possible.
$git_log_file = '/data/wordpress/.git/logs/HEAD';
if ( is_readable($git_log_file) ) {
$lines = file($git_log_file);
$last_line = array_pop($lines);
$fields = explode(' ', $last_line);
return substr($fields[1], 0, 8);
} else {
return wp_get_theme()->get('Version');
}
}
Content expiration date
header.php:
$seconds_to_cache = 3600; // 1 hour
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Cache-Control: max-age=$seconds_to_cache");
=>
expires: Wed, 29 Apr 2020 06:55:49 GMT
cache-control: max-age=3600
In dynamic files the validity period comes from PHP. WordPress itself does not set a default
expiration date. If desired, the theme can set it using HTTP headers if the page is rarely
updated or the refresh delay is irrelevant.
The validity period for static files (e.g. style.css or script.js) comes from the HTTP server
settings. At Seravo static files have seven day expiration and cache control by default.
Blocking content expiration date
nocache_headers();
=>
expires: Wed, 11 Jan 1984 05:00:00 GMT
cache-control: no-cache, must-revalidate, max-age=0
WordPress (or a theme or a plugin) sometimes blocks itself the content expiration date with a
nocache_headers() -function.
Server HTTP cache
● Objective: to avoid unnecessary PHP execution and to
provide an HTML file directly from the memory.
● The server cache (as well as the browser!) stores
pages and files purely based on what the HTTP
headers say.
● Once again, make sure your site sends sensible HTTP
headers and content expiration dates.
Tool: wp-speed-test
$ wp-speed-test
Testing speed URL https://seravo.com...
URL TOTAL NAMELOOKUP CONNECT APPCONNECT PRETRANSFER STARTTRANSFER = AVG
https://seravo.com 0.161 0.004 0.005 0.011 0.011 0.159 0.161
https://seravo.com 0.124 0.000 0.000 0.000 0.000 0.122 0.142
https://seravo.com 0.113 0.000 0.000 0.000 0.000 0.111 0.132
https://seravo.com 0.216 0.000 0.000 0.000 0.000 0.215 0.153
$ wp-speed-test --cache
Testing speed URL https://seravo.com...
Warning: invoked with --cache and thus measuring cached results. This does not measure actual PHP speed.
URL TOTAL NAMELOOKUP CONNECT APPCONNECT PRETRANSFER STARTTRANSFER = AVG
https://seravo.com 0.015 0.004 0.004 0.012 0.012 0.013 0.015
https://seravo.com 0.009 0.000 0.000 0.000 0.000 0.007 0.009
https://seravo.com 0.002 0.000 0.000 0.000 0.000 0.001 0.006
https://seravo.com 0.006 0.000 0.000 0.000 0.000 0.005 0.006
If --cache gives a better result, the HTTP-level server cache is working correctly. By default, the
wp-speed-test always overrides the cache (it is not nginx- but wp-speed-test).
Tool: wp-check-http-cache
$ wp-check-http-cache
----------------------------------------
Seravo HTTP cache checker
----------------------------------------
Testing https://example.com...
Request 1: MISS
Request 2: MISS
Request 3: MISS
----------------------------------------
FAILED: HTTP cache does not work for https://example.com.
----------------------------------------
Please review these headers and try to find what emits them:
expires: Wed, 11 Jan 1984 05:00:00 GMT
cache-control: no-transform, no-cache, no-store, must-revalidate
----------------------------------------
You can also test this yourself by running:
curl -IL https://example.com
The site probably has WP_DEBUG or nocache_headers() on through some other route because of
the 1984.
Tool: wp-check-http-cache
$ wp-check-http-cache
----------------------------------------
Seravo HTTP cache checker
----------------------------------------
Testing https://seravo.com...
Request 1: HIT
Request 2: HIT
Request 3: HIT
----------------------------------------
SUCCESS: HTTP cache works for https://seravo.com.
----------------------------------------
You can also test this yourself by running:
curl -IL https://seravo.com
The site is not sending HTTP headers that would prevent server-level caching.
Intentionally bypassing the cache
Most sites want HTTP-level caching enabled. An exception is a page that has content
customized for one user only, such as showing “Hello Otto!” to an identified user or a
WooCommerce shopping cart.
By default the shopping cart is displayed empty and caching is enabled, but as soon as the user
puts something in the cart, customized content should be displayed to that particular visitor,
and the event should not be cached.
WooCommerce makes sure this happens by setting cookies woocommece_items_in_cart and
woocommerce_cart_hash that automatically prevent the cache from working, as they indicate
user-specific content.
Can the server cache slow down the page?
Additional layers of caching can reduce the need to retrieve information directly from the
source. The best cache is in the browser itself. An attractive option may be to cache a server
that is close to the user. However, recycling traffic through the CDN can also increase the delay.
For example, the direct connection is 90 ms but the use of WooCommerce via CDN is 60 + 60
ms = 120 ms => 30 % slower. Be sure to measure before and after!
Read more: https://seravo.com/blog/does-cloudflare-help-my-wordpress-site/
Open the
shopping cart
User in
Berlin
Server in
Helsinki
Server in
Amsterdam
HTTP/2-connection, connect+fetch 90 ms
HTTP/2-connection, c+f 60 ms
HTTP/2-connection, c+f 60 ms
Seravo’s feature: server caching
● A standard WordPress page is server-level cached for 10 minutes by
default (see the action by looking at HIT/MISS lines in the HTTP
response).
● The server-level cache can be cleared with the wp-purge-cache
command.
● ...or skipped by loading the page with Ctrl+F5.
● If the page is broken (e.g. PHP syntax error), stale cache enters the
game and displays the page from the cache while the coder adds the
missing semicolon etc.
WordPress transients
● Objective: to avoid repeated heavy network and
database queries within the same minute or an hour.
WordPress transients
// Check for transient. If none, then execute WP_Query
if ( false === ( $featured = get_transient( 'foo_featured_posts' ) ) ) {
$featured = new WP_Query(
array(
'category' => 'featured',
'posts_per_page' => 5
));
// Put the results in a transient. Expire after 12 hours.
set_transient( 'foo_featured_posts', $featured, 12 * HOUR_IN_SECONDS );
}
WordPress’ own built-in cache for storing data for later use (e.g. one minute or one hour).
Stores in the database by default, but can also use for example only RAM if object-cache.php
is used and e.g. Redis server is available (as is the case for all Seravo clients).
Transient API in brief: get_transient(), set_transient() ja delete_transient()
For more information: https://seravo.com/blog/faster-wordpress-with-transients/
Always remember expiry! Otherwise
WP may load data via
wp_load_alloptions() with each site load!
WordPress object cache
● Objective: to avoid repetitive database queries during
the same PHP page load.
WP object cache
function prefix_get_post_count( $post_status = 'publish' ) {
$cache_key = 'prefix_post_count_'. $post_status;
$_posts = wp_cache_get( $cache_key );
if ( false === $_posts ) {
$_posts = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = %s",
$post_status
));
wp_cache_set( $cache_key, $_posts );
}
return $_posts;
}
For example, stores database query results in PHP’s memory, so that queries made in different
parts of WordPress code during the same PHP run do not have to be repeated many times.
NOTE: I have never used wp_cache_*. The Transient API is what a site developer really needs!
Example page https://developer.wordpress.org/reference/functions/wp_cache_get/
File system cache
● Objective: to avoid unnecessary hard drive operations
in general for any program.
● Seravo’s got you covered!
Database cache
● Objective: to avoid unnecessary hard drive operations
in the database in particular.
● Seravo’s got you covered!
Tideways
Xdebug is a good tool for profiling
PHP code in a local development
environment.
In a production environment Seravo
recommends Tideways.com
service.
seravo.com/docs/development/xdebug/
seravo.com/docs/development/tideways/
seravo.com/docs
Instructions for
WordPress site
developers
Always remember to measure
before and after!
Thank you!
Seravo.com @Seravo @ottokekalainen
See also
Make Your Site Faster with Caching
https://seravo.com/blog/wordpress-cache/
300% faster WordPress load times with transients
https://seravo.com/blog/faster-wordpress-with-transients/
5 common reasons why your WordPress site is slow
https://youtu.be/8sJExUO-U4A
Improving WordPress Performance with XDebug and PHP Profiling
https://youtu.be/oKcIS5A-6_c

More Related Content

What's hot

The 5 most common reasons for a slow WordPress site and how to fix them
The 5 most common reasons for a slow WordPress site and how to fix themThe 5 most common reasons for a slow WordPress site and how to fix them
The 5 most common reasons for a slow WordPress site and how to fix them
Otto Kekäläinen
 
Scaling WordPress
Scaling WordPressScaling WordPress
Scaling WordPress
Joseph Scott
 
Anthony Somerset - Site Speed = Success!
Anthony Somerset - Site Speed = Success!Anthony Somerset - Site Speed = Success!
Anthony Somerset - Site Speed = Success!
WordCamp Cape Town
 
Automatic testing and quality assurance for WordPress plugins and themes
Automatic testing and quality assurance for WordPress plugins and themesAutomatic testing and quality assurance for WordPress plugins and themes
Automatic testing and quality assurance for WordPress plugins and themes
Otto Kekäläinen
 
WordPress Need For Speed
WordPress Need For SpeedWordPress Need For Speed
WordPress Need For Speed
pdeschen
 
Roy foubister (hosting high traffic sites on a tight budget)
Roy foubister (hosting high traffic sites on a tight budget)Roy foubister (hosting high traffic sites on a tight budget)
Roy foubister (hosting high traffic sites on a tight budget)WordCamp Cape Town
 
Automatic testing and quality assurance for WordPress plugins
Automatic testing and quality assurance for WordPress pluginsAutomatic testing and quality assurance for WordPress plugins
Automatic testing and quality assurance for WordPress plugins
Otto Kekäläinen
 
WordPress performance tuning
WordPress performance tuningWordPress performance tuning
WordPress performance tuning
Vladimír Smitka
 
Find WordPress performance bottlenecks with XDebug PHP profiling
Find WordPress performance bottlenecks with XDebug PHP profilingFind WordPress performance bottlenecks with XDebug PHP profiling
Find WordPress performance bottlenecks with XDebug PHP profiling
Otto Kekäläinen
 
Care and feeding notes
Care and feeding notesCare and feeding notes
Care and feeding notes
Perrin Harkins
 
WordPress security 101 - WP Jyväskylä Meetup 21.3.2017
WordPress security 101 - WP Jyväskylä Meetup 21.3.2017WordPress security 101 - WP Jyväskylä Meetup 21.3.2017
WordPress security 101 - WP Jyväskylä Meetup 21.3.2017
Otto Kekäläinen
 
Redundancy Rocks. Redundancy Rocks.
Redundancy Rocks. Redundancy Rocks.Redundancy Rocks. Redundancy Rocks.
Redundancy Rocks. Redundancy Rocks.
AOE
 
WordPress security for everyone
WordPress security for everyoneWordPress security for everyone
WordPress security for everyone
Vladimír Smitka
 
EasyEngine - Command-Line tool to manage WordPress Sites on Nginx
EasyEngine - Command-Line tool to manage WordPress Sites on NginxEasyEngine - Command-Line tool to manage WordPress Sites on Nginx
EasyEngine - Command-Line tool to manage WordPress Sites on Nginx
rtCamp
 
CFML Sessions For Dummies
CFML Sessions For DummiesCFML Sessions For Dummies
CFML Sessions For Dummies
ColdFusionConference
 
High Performance Wordpress: “Faster, Cheaper, Easier : Pick Three”
High Performance Wordpress: “Faster, Cheaper, Easier : Pick Three”High Performance Wordpress: “Faster, Cheaper, Easier : Pick Three”
High Performance Wordpress: “Faster, Cheaper, Easier : Pick Three”
Valent Mustamin
 
WordPress Security: Defend yourself against digital invaders
WordPress Security:Defend yourself against digital invadersWordPress Security:Defend yourself against digital invaders
WordPress Security: Defend yourself against digital invaders
Vladimír Smitka
 
WordPress Performance optimization
WordPress Performance optimizationWordPress Performance optimization
WordPress Performance optimization
Brecht Ryckaert
 

What's hot (20)

The 5 most common reasons for a slow WordPress site and how to fix them
The 5 most common reasons for a slow WordPress site and how to fix themThe 5 most common reasons for a slow WordPress site and how to fix them
The 5 most common reasons for a slow WordPress site and how to fix them
 
Scaling WordPress
Scaling WordPressScaling WordPress
Scaling WordPress
 
Anthony Somerset - Site Speed = Success!
Anthony Somerset - Site Speed = Success!Anthony Somerset - Site Speed = Success!
Anthony Somerset - Site Speed = Success!
 
Automatic testing and quality assurance for WordPress plugins and themes
Automatic testing and quality assurance for WordPress plugins and themesAutomatic testing and quality assurance for WordPress plugins and themes
Automatic testing and quality assurance for WordPress plugins and themes
 
WordPress Need For Speed
WordPress Need For SpeedWordPress Need For Speed
WordPress Need For Speed
 
Roy foubister (hosting high traffic sites on a tight budget)
Roy foubister (hosting high traffic sites on a tight budget)Roy foubister (hosting high traffic sites on a tight budget)
Roy foubister (hosting high traffic sites on a tight budget)
 
04 web optimization
04 web optimization04 web optimization
04 web optimization
 
Automatic testing and quality assurance for WordPress plugins
Automatic testing and quality assurance for WordPress pluginsAutomatic testing and quality assurance for WordPress plugins
Automatic testing and quality assurance for WordPress plugins
 
WordPress performance tuning
WordPress performance tuningWordPress performance tuning
WordPress performance tuning
 
Find WordPress performance bottlenecks with XDebug PHP profiling
Find WordPress performance bottlenecks with XDebug PHP profilingFind WordPress performance bottlenecks with XDebug PHP profiling
Find WordPress performance bottlenecks with XDebug PHP profiling
 
Care and feeding notes
Care and feeding notesCare and feeding notes
Care and feeding notes
 
WordPress security 101 - WP Jyväskylä Meetup 21.3.2017
WordPress security 101 - WP Jyväskylä Meetup 21.3.2017WordPress security 101 - WP Jyväskylä Meetup 21.3.2017
WordPress security 101 - WP Jyväskylä Meetup 21.3.2017
 
WPDay Bologna 2013
WPDay Bologna 2013WPDay Bologna 2013
WPDay Bologna 2013
 
Redundancy Rocks. Redundancy Rocks.
Redundancy Rocks. Redundancy Rocks.Redundancy Rocks. Redundancy Rocks.
Redundancy Rocks. Redundancy Rocks.
 
WordPress security for everyone
WordPress security for everyoneWordPress security for everyone
WordPress security for everyone
 
EasyEngine - Command-Line tool to manage WordPress Sites on Nginx
EasyEngine - Command-Line tool to manage WordPress Sites on NginxEasyEngine - Command-Line tool to manage WordPress Sites on Nginx
EasyEngine - Command-Line tool to manage WordPress Sites on Nginx
 
CFML Sessions For Dummies
CFML Sessions For DummiesCFML Sessions For Dummies
CFML Sessions For Dummies
 
High Performance Wordpress: “Faster, Cheaper, Easier : Pick Three”
High Performance Wordpress: “Faster, Cheaper, Easier : Pick Three”High Performance Wordpress: “Faster, Cheaper, Easier : Pick Three”
High Performance Wordpress: “Faster, Cheaper, Easier : Pick Three”
 
WordPress Security: Defend yourself against digital invaders
WordPress Security:Defend yourself against digital invadersWordPress Security:Defend yourself against digital invaders
WordPress Security: Defend yourself against digital invaders
 
WordPress Performance optimization
WordPress Performance optimizationWordPress Performance optimization
WordPress Performance optimization
 

Similar to Less and faster – Cache tips for WordPress developers

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
Wim Godden
 
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
Wim Godden
 
High Availability Content Caching with NGINX
High Availability Content Caching with NGINXHigh Availability Content Caching with NGINX
High Availability Content Caching with NGINX
Kevin Jones
 
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
Wim Godden
 
High Availability Content Caching with NGINX
High Availability Content Caching with NGINXHigh Availability Content Caching with NGINX
High Availability Content Caching with NGINX
NGINX, Inc.
 
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
Kevin Jones
 
Clug 2012 March web server optimisation
Clug 2012 March   web server optimisationClug 2012 March   web server optimisation
Clug 2012 March web server optimisation
grooverdan
 
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
Wim Godden
 
10 Million hits a day with WordPress using a $15 VPS
10 Million hits a day  with WordPress using a $15 VPS10 Million hits a day  with WordPress using a $15 VPS
10 Million hits a day with WordPress using a $15 VPS
Paolo Tonin
 
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
Ortus Solutions, Corp
 
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
Wim Godden
 
Caching 101
Caching 101Caching 101
Caching 101
Andy Melichar
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
Matteo Moretti
 
Django book15 caching
Django book15 cachingDjango book15 caching
Django book15 cachingShih-yi Wei
 
php & performance
 php & performance php & performance
php & performance
simon8410
 
Nginx [engine x] and you (and WordPress)
Nginx [engine x] and you (and WordPress)Nginx [engine x] and you (and WordPress)
Nginx [engine x] and you (and WordPress)
Justin Foell
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Study
hernanibf
 
Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018
Thijs Feryn
 
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Ontico
 
PHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on NginxPHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on Nginx
Harald Zeitlhofer
 

Similar to Less and faster – Cache tips for WordPress developers (20)

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
 
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
 
High Availability Content Caching with NGINX
High Availability Content Caching with NGINXHigh Availability Content Caching with NGINX
High Availability Content Caching with NGINX
 
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
 
High Availability Content Caching with NGINX
High Availability Content Caching with NGINXHigh Availability Content Caching with NGINX
High Availability Content Caching with NGINX
 
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
 
Clug 2012 March web server optimisation
Clug 2012 March   web server optimisationClug 2012 March   web server optimisation
Clug 2012 March web server optimisation
 
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
 
10 Million hits a day with WordPress using a $15 VPS
10 Million hits a day  with WordPress using a $15 VPS10 Million hits a day  with WordPress using a $15 VPS
10 Million hits a day with WordPress using a $15 VPS
 
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 @ 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
 
Caching 101
Caching 101Caching 101
Caching 101
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
 
Django book15 caching
Django book15 cachingDjango book15 caching
Django book15 caching
 
php & performance
 php & performance php & performance
php & performance
 
Nginx [engine x] and you (and WordPress)
Nginx [engine x] and you (and WordPress)Nginx [engine x] and you (and WordPress)
Nginx [engine x] and you (and WordPress)
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Study
 
Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018
 
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
 
PHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on NginxPHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on Nginx
 

Recently uploaded

一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Sanjeev Rampal
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptxInternet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
VivekSinghShekhawat2
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
keoku
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Brad Spiegel Macon GA
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
GTProductions1
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
natyesu
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 

Recently uploaded (20)

一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptxInternet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 

Less and faster – Cache tips for WordPress developers

  • 1. Less and faster Caching tips for WordPress developers
  • 3. Premium hosting and upkeep for WordPress HTTP/2 TESTED UPDATES 24/7 UPKEEP
  • 4. Top-notch performance A comparison published by a Google employee at ismyhostfastyet.com confirms that Seravo’s customer sites load faster than competing services’. The study used time-to-first-byte (TTFB) measurement data from real users as collected from the Chrome browser UX data. Fast/Average/Slow TTFB by WordPress Host
  • 5. “There are only two hard things in Computer Science: cache invalidation and naming things.” – Phil Karlton
  • 6. Caches are everywhere ● Inside the CPU (levels L1-L4). ○ No need to retrieve data from RAM over and over again. ● In operating system (Linux) to protect the hard drives. ○ Prevents different programs from continuously reading the same file from the hard drive. ● Some programs have built-in caches: ○ PHP ■ Saves files so that there is no need to download them from the hard drive every second. ■ Saves the interpreted PHP code so that it does not have to be constantly recompiled. ○ Database ■ Uses plenty of cache (RAM) so that the hard drive does not need to be read as often. ○ WordPress ■ Stores transients in the database so that the following queries do not have to be as extensive. ...and these are just couple of examples. The list is long.
  • 7. Caches are everywhere, because...? ● Speed! ○ Can you say instantly how much is 5 times 5? Yes, because the result is already in your memory. ○ How about 55 times 555? Hmm… Probably have to count that one. ● Not everything can be stored in the memory, so it is a good idea to save only things you are likely need several times again later on.
  • 8. The numbers every coder should know ● Retrieval times for different types of memories: ○ L1 cache: 1 nanosecond ○ L2 cache: 3 ns ○ L3 cache: 10 ns ○ RAM: 25 ns ○ PCIe NVMe hard drive: 2000 ns – most Seravo customers ○ SSD hard drive: 100 000 ns – few Seravo customers ○ HDD hard drive: 10 000 000 ns – none of Seravo’s customers ○ Tampere-Berlin ping: 30 000 000 ns ○ HTML-page from Nginx 2 000 000 ns ○ HTML-page from PHP/WP 50 000 000 – 1 000 000 000 ns
  • 9. Should the cache contain everything? ● Not everything can be stored in the memory, so you should only store things that will most likely be needed twice or more. ● If something is not needed, clear the cache: ○ Clearing by command, so called “cache purge”. ○ A built-in mechanism, e.g. a counter to tell how many times the data has been retrieved in the past hour. ● The cache can be cleared at any time, and some systems do so on a regular basis. ● In addition, the cache can expire.
  • 10. Difficult: Cache invalidation ● In what time will the cache expire? ○ 5 seconds? ○ 60 seconds? ○ 15 minutes? ○ 7 days? ● It depends. That is why it is so difficult.
  • 11. Cache concepts Retrieval time – has to be faster from cache than the source in order to get savings. Invalidation – the criteria for deleting data from the cache. Expiry – the time in which the data expires and is removed from the cache. Bypass – intentionally bypasses the cache. Miss – if the cache is empty, retrieves the latest data. Hit rate – hit/miss-ratio, how often the data was found in the cache (ideally 99,99 %).
  • 13. For a WP developer to consider ● Browser HTTP cache ○ Always the fastest! ● Server HTTP cache ○ Nginx, Varnish, Cloudflare, Fastly etc. ● WordPress transients ○ get_transient(key); ● WordPress object cache ○ wp_cache_get(key); ● File system cache ● MariaDB database cache See also: https://seravo.com/tag/cache/
  • 14. No, another plugin is not the way to go. It might be a band-aid, at best.
  • 15. Browser HTTP cache ● Objective: to avoid unnecessary network traffic. ● The browser stores pages and files purely based on what the HTTP headers say. ● Make sure your site sends sensible HTTP headers and content expiration dates. ● WordPress does not do this as a standard.
  • 16. An example: WP 5.3.2 CSS file $ curl -IL https://seravo.com/wp-includes/css/dist/block-library/style.min.css?ver=5.3.2 HTTP/2 200 server: nginx date: Wed, 29 Apr 2020 05:33:47 GMT content-type: text/css last-modified: Tue, 28 Apr 2020 11:42:09 GMT etag: "5ea81691-1d52e" expires: Thu, 07 May 2020 05:33:45 GMT cache-control: max-age=691200 x-proxy-cache: HIT P: A: N: H:0 O: S: x-powered-by: Seravo x-seravo-request-id: dd1d5d1e649b5f675269a54e86dabacb The server tells the browser that the content is valid for seven days. The length of the time does not matter. However, the content in the address style.min.css?ver=5.3.2 stays the same so it must be updated with a new version number if the content is updated. Otherwise the page will be “broken” for seven days for old visitors.
  • 17. An example: theme’s CSS file wp_enqueue_style( 'seravo', get_stylesheet_directory_uri() . '/dist/layout.min.css', false, wp_get_theme()->get('Version') ); => https://seravo.com/wp-content/themes/seravo/dist/layout.min.css?ver=1.2.3 If you download style files or scripts without version numbers, the browser will always have the same layout.min.css. However, if you add the version number, the download happens with an address layout.min.css?ver=1.2.3 which ensures that whenever there is a new version of the theme, the browser will also download a new version of the style file.
  • 18. An example: seravo.com CSS file wp_enqueue_style( 'seravo', get_stylesheet_directory_uri() . '/dist/layout.min.css', false, seravo_get_git_commit_id() ); => https://seravo.com/wp-content/themes/seravo/dist/layout.min.css?ver=c98272d0 function seravo_get_git_commit_id() { // Don't use shell_exec('git rev-parse --short HEAD') or similar since it // would spawn a shell session on every WordPress load of every page. // Instead read directly from .git/logs/HEAD to as efficient as possible. $git_log_file = '/data/wordpress/.git/logs/HEAD'; if ( is_readable($git_log_file) ) { $lines = file($git_log_file); $last_line = array_pop($lines); $fields = explode(' ', $last_line); return substr($fields[1], 0, 8); } else { return wp_get_theme()->get('Version'); } }
  • 19. Content expiration date header.php: $seconds_to_cache = 3600; // 1 hour $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT"; header("Expires: $ts"); header("Cache-Control: max-age=$seconds_to_cache"); => expires: Wed, 29 Apr 2020 06:55:49 GMT cache-control: max-age=3600 In dynamic files the validity period comes from PHP. WordPress itself does not set a default expiration date. If desired, the theme can set it using HTTP headers if the page is rarely updated or the refresh delay is irrelevant. The validity period for static files (e.g. style.css or script.js) comes from the HTTP server settings. At Seravo static files have seven day expiration and cache control by default.
  • 20. Blocking content expiration date nocache_headers(); => expires: Wed, 11 Jan 1984 05:00:00 GMT cache-control: no-cache, must-revalidate, max-age=0 WordPress (or a theme or a plugin) sometimes blocks itself the content expiration date with a nocache_headers() -function.
  • 21. Server HTTP cache ● Objective: to avoid unnecessary PHP execution and to provide an HTML file directly from the memory. ● The server cache (as well as the browser!) stores pages and files purely based on what the HTTP headers say. ● Once again, make sure your site sends sensible HTTP headers and content expiration dates.
  • 22. Tool: wp-speed-test $ wp-speed-test Testing speed URL https://seravo.com... URL TOTAL NAMELOOKUP CONNECT APPCONNECT PRETRANSFER STARTTRANSFER = AVG https://seravo.com 0.161 0.004 0.005 0.011 0.011 0.159 0.161 https://seravo.com 0.124 0.000 0.000 0.000 0.000 0.122 0.142 https://seravo.com 0.113 0.000 0.000 0.000 0.000 0.111 0.132 https://seravo.com 0.216 0.000 0.000 0.000 0.000 0.215 0.153 $ wp-speed-test --cache Testing speed URL https://seravo.com... Warning: invoked with --cache and thus measuring cached results. This does not measure actual PHP speed. URL TOTAL NAMELOOKUP CONNECT APPCONNECT PRETRANSFER STARTTRANSFER = AVG https://seravo.com 0.015 0.004 0.004 0.012 0.012 0.013 0.015 https://seravo.com 0.009 0.000 0.000 0.000 0.000 0.007 0.009 https://seravo.com 0.002 0.000 0.000 0.000 0.000 0.001 0.006 https://seravo.com 0.006 0.000 0.000 0.000 0.000 0.005 0.006 If --cache gives a better result, the HTTP-level server cache is working correctly. By default, the wp-speed-test always overrides the cache (it is not nginx- but wp-speed-test).
  • 23. Tool: wp-check-http-cache $ wp-check-http-cache ---------------------------------------- Seravo HTTP cache checker ---------------------------------------- Testing https://example.com... Request 1: MISS Request 2: MISS Request 3: MISS ---------------------------------------- FAILED: HTTP cache does not work for https://example.com. ---------------------------------------- Please review these headers and try to find what emits them: expires: Wed, 11 Jan 1984 05:00:00 GMT cache-control: no-transform, no-cache, no-store, must-revalidate ---------------------------------------- You can also test this yourself by running: curl -IL https://example.com The site probably has WP_DEBUG or nocache_headers() on through some other route because of the 1984.
  • 24. Tool: wp-check-http-cache $ wp-check-http-cache ---------------------------------------- Seravo HTTP cache checker ---------------------------------------- Testing https://seravo.com... Request 1: HIT Request 2: HIT Request 3: HIT ---------------------------------------- SUCCESS: HTTP cache works for https://seravo.com. ---------------------------------------- You can also test this yourself by running: curl -IL https://seravo.com The site is not sending HTTP headers that would prevent server-level caching.
  • 25. Intentionally bypassing the cache Most sites want HTTP-level caching enabled. An exception is a page that has content customized for one user only, such as showing “Hello Otto!” to an identified user or a WooCommerce shopping cart. By default the shopping cart is displayed empty and caching is enabled, but as soon as the user puts something in the cart, customized content should be displayed to that particular visitor, and the event should not be cached. WooCommerce makes sure this happens by setting cookies woocommece_items_in_cart and woocommerce_cart_hash that automatically prevent the cache from working, as they indicate user-specific content.
  • 26. Can the server cache slow down the page? Additional layers of caching can reduce the need to retrieve information directly from the source. The best cache is in the browser itself. An attractive option may be to cache a server that is close to the user. However, recycling traffic through the CDN can also increase the delay. For example, the direct connection is 90 ms but the use of WooCommerce via CDN is 60 + 60 ms = 120 ms => 30 % slower. Be sure to measure before and after! Read more: https://seravo.com/blog/does-cloudflare-help-my-wordpress-site/ Open the shopping cart User in Berlin Server in Helsinki Server in Amsterdam HTTP/2-connection, connect+fetch 90 ms HTTP/2-connection, c+f 60 ms HTTP/2-connection, c+f 60 ms
  • 27. Seravo’s feature: server caching ● A standard WordPress page is server-level cached for 10 minutes by default (see the action by looking at HIT/MISS lines in the HTTP response). ● The server-level cache can be cleared with the wp-purge-cache command. ● ...or skipped by loading the page with Ctrl+F5. ● If the page is broken (e.g. PHP syntax error), stale cache enters the game and displays the page from the cache while the coder adds the missing semicolon etc.
  • 28. WordPress transients ● Objective: to avoid repeated heavy network and database queries within the same minute or an hour.
  • 29. WordPress transients // Check for transient. If none, then execute WP_Query if ( false === ( $featured = get_transient( 'foo_featured_posts' ) ) ) { $featured = new WP_Query( array( 'category' => 'featured', 'posts_per_page' => 5 )); // Put the results in a transient. Expire after 12 hours. set_transient( 'foo_featured_posts', $featured, 12 * HOUR_IN_SECONDS ); } WordPress’ own built-in cache for storing data for later use (e.g. one minute or one hour). Stores in the database by default, but can also use for example only RAM if object-cache.php is used and e.g. Redis server is available (as is the case for all Seravo clients). Transient API in brief: get_transient(), set_transient() ja delete_transient() For more information: https://seravo.com/blog/faster-wordpress-with-transients/ Always remember expiry! Otherwise WP may load data via wp_load_alloptions() with each site load!
  • 30. WordPress object cache ● Objective: to avoid repetitive database queries during the same PHP page load.
  • 31. WP object cache function prefix_get_post_count( $post_status = 'publish' ) { $cache_key = 'prefix_post_count_'. $post_status; $_posts = wp_cache_get( $cache_key ); if ( false === $_posts ) { $_posts = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = %s", $post_status )); wp_cache_set( $cache_key, $_posts ); } return $_posts; } For example, stores database query results in PHP’s memory, so that queries made in different parts of WordPress code during the same PHP run do not have to be repeated many times. NOTE: I have never used wp_cache_*. The Transient API is what a site developer really needs! Example page https://developer.wordpress.org/reference/functions/wp_cache_get/
  • 32. File system cache ● Objective: to avoid unnecessary hard drive operations in general for any program. ● Seravo’s got you covered!
  • 33. Database cache ● Objective: to avoid unnecessary hard drive operations in the database in particular. ● Seravo’s got you covered!
  • 34. Tideways Xdebug is a good tool for profiling PHP code in a local development environment. In a production environment Seravo recommends Tideways.com service. seravo.com/docs/development/xdebug/ seravo.com/docs/development/tideways/
  • 36. Always remember to measure before and after!
  • 37. Thank you! Seravo.com @Seravo @ottokekalainen
  • 38. See also Make Your Site Faster with Caching https://seravo.com/blog/wordpress-cache/ 300% faster WordPress load times with transients https://seravo.com/blog/faster-wordpress-with-transients/ 5 common reasons why your WordPress site is slow https://youtu.be/8sJExUO-U4A Improving WordPress Performance with XDebug and PHP Profiling https://youtu.be/oKcIS5A-6_c