Speeding up PHP CLI applications using OpCache

I run a few PHP based applications which require background jobs, and I use the usual crond via crontab to run the jobs. PHP has an excellent feature – OpCache which can cache the compiled code in memory to speed up the web applications, where typically the PHP-FPM process is a long running process so the compiled code can be fetched on next request. But with CLI applications there is no shared state or memory to store the compiled code.

The Solution

Use the file cache feature of PHP, configurable in php.ini using opcache.file_cache configuration option. Note that OpCache on CLI must be enabled using opcache.enable_cli=1, by default it stays off.

With multiple users running background jobs

The opcache.file_cache path must point to a directory where the user running the PHP script must have write access so that PHP can create the .bin files. Now here’s the catch, what happens if we have multiple users running different PHP scripts? They cannot share a common file cache directory for security reasons or it can cause cache poisoning. PHP seems to generate some hash string based directory structure but since all my PHP applications live in a common directory but are run by different users, it was not working when using a single directory. Consider /home as the common path and /home/user1, /home/user2 as different users.

Solution for multiple users

Specify opcache.file_cache path in the crontab! Here’s how:

*/5 * * * * /usr/bin/php7.3 -d opcache.file_cache=/var/cache/php/user1 -f /home/user1/app/cron.php

Create the /var/cache/php directory with permissions similar to /tmp (sticky bit) and the individual directories as well (they don’t seem to get created automatically):

mkdir /var/cache/php
chmod 1777 /var/cache/php

mkdir /var/cache/php/user1
chown user1:group1 /var/cache/php/user1
chmod 700 /var/cache/php/user1

It is also a good idea to enable the file consistency check option opcache.file_cache_consistency_checks=1, it will prevent errors in case cache gets corrupted for any reason.

Enjoy fast background jobs!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: