All posts

Memory and OPcache: Settings That Belong on Every Laravel Server

What memory_limit really limits, how to configure OPcache for production, and which Laravel commands belong in every deploy.

Marijan Kopčić••2 min read
Memory and OPcache: Settings That Belong on Every Laravel Server

memory_limit

memory_limit is a limit per request, not for PHP as a whole. If the limit is 256 MB and FPM has 40 workers, the theoretical maximum is over 10 GB. That is why memory_limit and pm.max_children are always looked at together.

The CLI has its own php.ini, so queue workers and artisan commands often run with a different limit than the web. To check:

php -i | grep memory_limit
php --ini

OPcache

Without OPcache, PHP reads and compiles every file again on every request. With it, the compiled code is kept in shared memory.

opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0

validate_timestamps=0 means PHP no longer checks whether files have changed. It is the fastest setting, but FPM has to be reloaded after every deploy:

sudo systemctl reload php8.3-fpm

Without that, the server keeps running the old code.

max_accelerated_files has to be higher than the number of PHP files in the project, including the vendor directory:

find . -name "*.php" | wc -l

The Laravel side

composer install --no-dev --optimize-autoloader
php artisan optimize

optimize caches the configuration, routes, views and events. After config:cache, calling env() outside the config files returns null, so values are read only through config().

Keep reading