Part 1 of 3
What happened
The uncached pages were a lot slower, before even WordPress did any real work.
On the client site I worked on, OPcache was enabled, but it was caching the WordPress core files only. Every plugin and theme file was left out of the cache and was getting compiled again with every request.
OPcache on the client site, before the fix
On paper
opcache.enableFine:1- OPcache statusFine: enabled
In practice
- WordPress core (
wp-includes,wp-admin)Fine: cached - Plugins and theme (
wp-content)Wrong: compiled again on every request
This is how the site came set up from the host.
This was fixed, and the uncached origin time came down by 52 to 61%.
Part 2 of 3
What OPcache is
PHP compiles every file before executing it. This can be very bad for performance if the file is big and it is being compiled again and again with each request.
To overcome this, we have OPcache. It stops PHP from compiling the same file again and again with every request, but it can show enabled and still skip most of your site files.
What happens when PHP runs a file?
PHP never runs your source code directly. It first goes through a set of five steps for every file a request needs.
- Read the file.
- Lex the code (break it into tokens).
- Parse the tokens into a syntax tree.
- Compile the tree into opcodesOpcodes The instructions PHP compiles a file into. They are what the Zend Engine actually runs.. Opcodes = instructions for the Zend Engine to execute.
- Execute the opcodes.
So what happens at the end of a request?
PHP throws all of it away. Nothing is kept between requests (by design).
So what happens when the next request comes for the same files? Again the same work would be done.
What do opcodes look like?
You can easily look at it for yourself with a three line file:
<?php
$name = 'WordPress';
echo 'Hello, ' . $name;This would print Hello, WordPress.
There is a way to ask OPcache to dump the compiler output. You can do this by adding the following line in php.ini:
opcache.opt_debug_level=0x10000
This would generate the output for the above code:
php -d opcache.enable_cli=1 -d opcache.opt_debug_level=0x10000 hello.phpoutput
$_main:
; (lines=4, args=0, vars=1, tmps=2)
; (before optimizer)
; /tmp/hello.php:1-4
; return [] RANGE[0..0]
0000 ASSIGN CV0($name) string("WordPress")
0001 T2 = CONCAT string("Hello, ") CV0($name)
0002 ECHO T2
0003 RETURN int(1)
Hello, WordPressIt is generating 4 opcodes for 3 lines. Imagine for your real plugin file you are adding maybe a few hundred lines, and in a single request you are loading a lot of these. What would be the size of the opcode for that?
What is OPcache?
The opcode cache keeps all the compiled opcodes in a shared memory between the requests. The first request needing a file will compile it and store the result in the shared memory, and every request after that would directly get it from the shared memory. It will not even go through the read, lex, parse and compile stages, it will directly go to the execute stage.
- ReadLoad the file from diskSkipped: With OPcache
- LexSplit the source into tokensSkipped: With OPcache
- ParseBuild a syntax treeSkipped: With OPcache
- CompileTurn the tree into opcodesSkipped: With OPcache
- ExecuteRun the opcodes
- Shared memory
- The shared memory here is the one for all the PHP workers of a server or a pool. It’s not a case of one copy per request.
- Interned stringsInterned strings Identical strings (function names, class names, array keys) stored once and shared. OPcache keeps them in their own buffer, 8 MB by default.
- Strings which are identical are stored only a single time in a separate buffer and are then shared between the places, for example function names, class names, array keys etc.
- File timestamps
- By default the file timestamps are checked every 2 seconds, and if there’s a change in the file, the PHP file is recompiled and the updated opcode is stored in the opcode cache.
Why does WordPress care so much?
WordPress loads a lot of PHP every request, even if it’s just a static page. Without OPcache all of it would be compiled every time. For this site, one WordPress load through WP-CLI gave me 1,433 PHP files.
- WordPress core
- 460
- 11 active plugins + theme
- 973
- Forminator on its own
- 327
That is a lot for a blog. On a local copy of the client site, the checkout page loaded around 1,880 files.
Part 3 of 3
Finding it and fixing it
How can it be off?
The enabled somewhere in the configuration does not mean that your code is being cached. There can be five ways in which it would be off or as good as off.
- It’s not loaded or not enabled.
- You are looking at the wrong process.
- A folder in the cache was left out on purpose.
- The cache is full.
- And the opposite one: the deploys are not being noticed.
This was our case for the client site, the third one, the folder was there but left out.
Is a folder left out on purpose?
opcache.blacklist_filename -> The file containing the paths of the files which are never to be cached (they will be compiled and executed from scratch with every request).
One path per line is written in this file, wildcards are allowed.
If we write a bare path, it will be considered as a prefix for the matched pattern.
For example:
; Matches every file under this path.
/var/www/site/wp-contentIf we only write the wp-content path in this file and if OPcache is enabled, all the files from the wp-content directory would never be cached, and they would be compiled and executed on every request, making it the same as if OPcache was off.
There is a counter in OPcache named blacklist_misses which would increase every time a file specified in the blacklist is loaded.
Our client site looked exactly like this. Only core files were cached, and all wp-content files were not being cached and were being executed every time.
How was it fixed?
The host turned it on for the wp-content on request.
The uncached origin time on every page I measured dropped by 52 to 61%.
Checkout page, uncached, time at the origin
56% lower, 2.3x
I checked the size limits after this as well, and the host had the wp-content cache well above the defaults, but the coverage was the whole problem here.
Is OPcache loaded and enabled at all?
It has been part of PHP since 5.5. Until PHP 8.4 it was a separate extension and the server could have left it out during the installation, and if it was the case, we would need to add the line zend_extension=opcache to the php.ini to enable it. From PHP 8.5 it is always a part of the core PHP install and it will be there always.
We can still add opcache.enable=0 in the php.ini no matter the PHP version, to switch it off.
Also for users on shared hosting panels, they usually provide a graphical option to toggle these extensions on a per-account basis. So it is possible for one site to be on an OPcache enabled server, and the very next site on the same server to be on an OPcache disabled one.
Is it on for the command line?
The opcache.enable_cli is 0 by default, also on this site’s host.
This is mostly fine, as the opcache -> the data is live in the memory of the process which made it -> so if the CLI process exits after the execution of the command -> the cached data is also gone.
A trap here can be reading the wrong one.
As WP-CLI runs on PHP CLI -> if we try to get the status of the opcache via wp eval 'opcache_get_status();' -> it would tell us the status of the CLI opcache, not the one of the website.
Or if we try to reset the opcache via WP-CLI using opcache_reset() -> it would reset the opcache of the CLI only, the website one would be untouched.
So, resetting a cache which does not even exist.
Is the cache full?
There are three fixed size limits in opcache by default:
opcache.memory_consumption- 128 MB -> This is for the compiled code
opcache.interned_strings_buffer- 8 MB -> It is used to cache the string data that is used multiple times
opcache.max_accelerated_files- 10,000 -> It is the number of keys allowed in the cache, this would be rounded up to the next prime number in the fixed list (10,000 -> 16,229)
On my local test site, I’ve set it to 4,000 and it reports 7,963.
If the memory is full, it will not cache the new files and will compile the code every time the script is requested.
These are the limits per cache, not per site, so if you have multiple sites on a single PHP pool, they will all be sharing the 128 MB and the 10,000 cache entries.
When does it throw everything away?
When a file is changed on the disk, the old copy stays in the memory and is counted as wasted memory by the opcache.
For this, opcache has a configuration opcache.max_wasted_percentage -> this is by default 5%. If the wasted memory exceeds the 5% + there is not enough free memory left, the opcache will schedule a restart to clear the cache.
The whole cache is dropped at once and the next requests would have to compile from scratch.
There is a counter which tells you how often this has happened: oom_restarts.
Does it notice your deploys?
The opposite of failure: OPcache can work too well. For example, if you have configured opcache.validate_timestamps=0, OPcache will never check if the files in its cache have been changed on the disk. So even if you deploy new code, the old code would continue to run from OPcache.
To invalidate the cache you will have to run opcache_reset(), opcache_invalidate() or restart your PHP process.
You will have to run it via a web request in PHP.
How do you check yours?
This can be achieved from a web request, as an admin user, by a throwaway mu-pluginmu-plugin Must-use plugin. A PHP file in wp-content/mu-plugins/ that loads before normal plugins and cannot be switched off from the admin. with a single function which calls opcache_get_status( true ).
<?php
// wp-content/mu-plugins/opcache-check.php. Delete it when you are done.
add_action( 'admin_init', function () {
if ( ! isset( $_GET['opcache-check'] ) || ! current_user_can( 'manage_options' ) ) {
return;
}
$status = function_exists( 'opcache_get_status' ) ? opcache_get_status( true ) : false;
if ( ! is_array( $status ) ) {
wp_send_json( 'OPcache is off, or opcache.restrict_api blocks this file' );
}
$scripts = array_keys( $status['scripts'] ?? array() );
$non_core = array_filter(
$scripts,
fn( $path ) => ! str_contains( $path, '/wp-includes/' ) && ! str_contains( $path, '/wp-admin/' )
);
$memory = $status['memory_usage'];
$stats = $status['opcache_statistics'];
$mb = fn( $bytes ) => round( $bytes / MB_IN_BYTES, 1 );
wp_send_json(
array(
'enabled' => $status['opcache_enabled'],
'cache_full' => $status['cache_full'],
'used_mb' => $mb( $memory['used_memory'] ),
'free_mb' => $mb( $memory['free_memory'] ),
'wasted_mb' => $mb( $memory['wasted_memory'] ),
'strings_free_mb' => $mb( $status['interned_strings_usage']['free_memory'] ?? 0 ),
'cached_scripts' => count( $scripts ),
'non_core_scripts' => count( $non_core ),
'max_cached_keys' => $stats['max_cached_keys'],
'hit_rate' => round( $stats['opcache_hit_rate'], 2 ),
'oom_restarts' => $stats['oom_restarts'],
'blacklist_misses' => $stats['blacklist_misses'],
)
);
} );Here it is counting the core files and everything else. We can load a few front-end pages first and then open /wp-admin/?opcache-check, and we will get the JSON below (my local test site after a handful of requests).
{
"enabled": true,
"cache_full": false,
"used_mb": 31,
"free_mb": 97,
"wasted_mb": 0,
"strings_free_mb": 3.1,
"cached_scripts": 555,
"non_core_scripts": 25,
"max_cached_keys": 7963,
"hit_rate": 90.25,
"oom_restarts": 0,
"blacklist_misses": 0
}What to look for
enabled- If the value is set to
false, this would cause the very first problem. non_core_scripts- Your plugins and theme related scripts. Here, it shows the count of the scripts which are not part of the WordPress core files. As the count is
0next to hundreds of core files -> they are being left out. hit_rate- This value climbs towards 100 as the cache warms. Every file you request once will be a cache miss as the data will not be there in the cache previously.
cache_full,free_mb,strings_free_mb- If these values are near to zero -> This is the size problem.
oom_restarts- The value should stay
0, if there is any value other than0-> It means something is causing the cache to overflow and restarts to be performed. blacklist_misses- If this value is above
0it means some files are left out from being cached on purpose, they can be found in the config file.
The data for the WordPress core files is being counted on purpose. Even if we add a condition and match against /wp-content/, the PHP code is still reporting the real paths of the files and not the symlinks.
Matching against /wp-content/ -> it found 1 out of 1,433 the first time.
What this does not cover
- JIT, preloading
opcache.preload, file cacheopcache.file_cache-> Topics I would like to dig more. - One host, one site -> Do not know how many other managed hosts are shipped like this.
- 52 to 61% = This would be the percentage of uncached origin time only. The page-cached pages would not have even touched PHP. The rest of the page being slow would be separate fixes.
Leave a comment