Laravel OPcache settings and Laravel’s own caches decide how much work each request repeats. Without them, every request reads and compiles framework files, merges config files and registers every route before it runs your code. At peak that repeated work burns the CPU you need for real requests.
What breaks at peak
OPcache stores compiled PHP scripts in shared memory, so PHP-FPM children skip parsing and compiling on each request. The defaults suit a small app, and a Laravel app with its vendor directory often outgrows them:
opcache.memory_consumptiondefaults to 128 MB. When it fills, OPcache stops caching new scripts, and those compile on every request.opcache.max_accelerated_filesdefaults to 10000. A Laravel project with a few dozen packages can hold more PHP files than that.opcache.interned_strings_bufferdefaults to 8 MB. Laravel’s class, method and config key names fill it fast.
When memory or the key table fills, OPcache checks how much of its memory holds stale scripts. Past opcache.max_wasted_percentage, 5% by default, it schedules a restart that empties the cache. Every child then recompiles at the same moment, and at peak your CPU jumps and p99 follows. Below that share, the cache stays full and new scripts compile on every request.
OPcache logs only errors by default, so these warnings stay hidden until you raise opcache.log_verbosity_level to 2:
Not enough free shared space to allocate 32768 bytes (16384 bytes free)
Interned string buffer overflow
Laravel adds its own repeated work. Without the config cache, each request loads every file in config/ and parses .env. Without the route cache, each request registers every route. Without the view cache, the first request to each Blade view after a deploy compiles it. Ship a new release during a busy hour, and that first wave of requests pays for all of it.
Laravel OPcache settings, config cache and route cache
Start with OPcache. This file goes in PHP’s conf.d directory, for example /usr/local/etc/php/conf.d/opcache.ini on the official Docker images:
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=32531
opcache.max_wasted_percentage=10
opcache.validate_timestamps=0
opcache.save_comments=1
opcache.log_verbosity_level=2
On the official images, OPcache may ship as an extension you have to install. Run docker-php-ext-install opcache in your Dockerfile if php -m doesn’t list Zend OPcache.
opcache.memory_consumptionis the shared memory for compiled scripts, in megabytes. Size it from your own app: warm the cache, readused_memory, and leave at least half again on top for growth.opcache.interned_strings_bufferholds one copy of each repeated string, in megabytes. Size it the same way frominterned_strings_usage.opcache.max_accelerated_filescaps how many scripts OPcache can hold. PHP rounds it up to the next prime in a fixed list, and 32531 is one of them. Count your files withfind /var/www/html -name '*.php' | wc -land set it above that count, with room for new packages.opcache.max_wasted_percentagesets how much stale memory OPcache tolerates before a restart. Withvalidate_timestamps=0, little memory goes stale between deploys.opcache.validate_timestamps=0stops OPcache from checking each file’s timestamp. The default checks everyopcache.revalidate_freqseconds, 2 by default. With 0, PHP never sees new code until you reload PHP-FPM or start a new container.opcache.save_comments=1is the default. Keep it, because packages that read annotations from docblocks break without it.opcache.log_verbosity_level=2adds warnings to the log, including the two lines above.
The CLI keeps its own cache, since opcache.enable_cli defaults to 0. php -i on the command line shows the CLI’s view, not FPM’s. Read FPM’s numbers from the metrics script below.
I leave the JIT and preloading off for Laravel. Most request time goes to the database and the network, where the JIT doesn’t help. Preloading ties every deploy to a full FPM restart, and OPcache already holds the same files.
Cache Laravel’s config, routes, events and views on deploy. Run these as part of every release:
composer install --no-dev --optimize-autoloader --no-interaction
php artisan optimize
On Laravel 11 and later, php artisan optimize runs config:cache, event:cache, route:cache and view:cache. On Laravel 10 it covers config and routes, so add php artisan view:cache and php artisan event:cache. --optimize-autoloader builds a class map, so Composer stops searching directories for each class.
The config cache rule. Once you run config:cache, Laravel stops loading .env. Any env() call outside the config/ files returns null. Search for them before you turn it on:
grep -rn "env(" app/ routes/ resources/views/ | grep -v "config("
Move each one into a config file and read it with config().
Where to run the cache commands. In a container image, route:cache, view:cache and event:cache can run during the build. config:cache writes your environment’s values into bootstrap/cache/config.php. Run it at container start, with the production environment loaded, or the image carries build-time values. In my images it’s the one artisan command in the entrypoint.
Reload after each deploy on VMs. With validate_timestamps=0, FPM keeps serving the old code until you reload it. Tools such as Deployer switch a current symlink to the new release. PHP’s realpath cache can keep resolving the old path, so reload FPM after the switch:
sudo systemctl reload php8.3-fpm
Use $realpath_root in nginx, so FPM sees the resolved release path:
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
Set process_control_timeout = 10s in the [global] section of php-fpm.conf. It gives children time to finish in-flight requests when the master reloads. The default is 0.
A full OPcache restart and too few FPM children look alike from outside. The PHP-FPM max children recipe covers the pool side.
Test it on your system
First confirm what FPM loaded. php artisan about lists Config, Events, Routes and Views under Cache, each as CACHED or NOT CACHED. Then read OPcache’s numbers from the metrics script below, through FPM.
Test two moments: steady peak, and a deploy during peak. This k6 script holds a fixed rate across your main pages:
import http from 'k6/http';
import { check } from 'k6';
const pages = ['/', '/dashboard', '/orders', '/orders/1001', '/api/v1/products?page=3'];
export const options = {
scenarios: {
peak: {
executor: 'constant-arrival-rate',
rate: Number(__ENV.RATE || 80), // your peak requests per second
timeUnit: '1s',
duration: '20m',
preAllocatedVUs: 150,
maxVUs: 1500,
},
},
thresholds: {
http_req_failed: ['rate<0.001'],
http_req_duration: ['p(99)<900'],
},
};
export default function () {
const page = pages[Math.floor(Math.random() * pages.length)];
const res = http.get(`${__ENV.BASE_URL}${page}`);
check(res, { 'not 5xx': (r) => r.status < 500 });
}
Use your own routes, with logged-in pages behind a test session cookie if most traffic is authenticated. Ten minutes in, roll a new release to staging while the test runs. That’s where missing view caches and cold OPcache show.
Watch these while it runs:
php_opcache_cache_fullstays 0, andphp_opcache_misses_totalstops climbing once the cache is warm.php_opcache_oom_restarts_totalandphp_opcache_hash_restarts_totalstay flat.- FPM CPU and p99 during the rollout, against the steady part of the run.
- The FPM error log, for the OPcache warnings above.
Set your bar first. A pass has no OPcache restarts and no full cache during the run. p99 through the rollout stays within the margin you allow over steady state, and the k6 thresholds hold.
Keep it healthy
No common exporter reads OPcache, because its numbers live inside FPM’s shared memory. This script prints them in Prometheus format. Serve it through FPM on an internal port only:
<?php
// opcache-metrics.php: expose on an internal listener only.
header('Content-Type: text/plain; version=0.0.4');
$s = function_exists('opcache_get_status') ? opcache_get_status(false) : false;
if ($s === false) {
echo "php_opcache_enabled 0\n";
exit;
}
$m = $s['memory_usage'];
$i = $s['interned_strings_usage'];
$st = $s['opcache_statistics'];
$metrics = [
'php_opcache_enabled' => $s['opcache_enabled'] ? 1 : 0,
'php_opcache_cache_full' => $s['cache_full'] ? 1 : 0,
'php_opcache_memory_used_bytes' => $m['used_memory'],
'php_opcache_memory_free_bytes' => $m['free_memory'],
'php_opcache_memory_wasted_bytes' => $m['wasted_memory'],
'php_opcache_interned_strings_used_bytes' => $i['used_memory'],
'php_opcache_interned_strings_buffer_bytes' => $i['buffer_size'],
'php_opcache_cached_keys' => $st['num_cached_keys'],
'php_opcache_max_cached_keys' => $st['max_cached_keys'],
'php_opcache_hits_total' => $st['hits'],
'php_opcache_misses_total' => $st['misses'],
'php_opcache_oom_restarts_total' => $st['oom_restarts'],
'php_opcache_hash_restarts_total' => $st['hash_restarts'],
];
foreach ($metrics as $name => $value) {
echo $name, ' ', $value, "\n";
}
An nginx server block on a port that only Prometheus can reach serves it:
server {
listen 9180;
allow 10.0.0.0/8;
deny all;
location = /metrics {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /var/www/ops/opcache-metrics.php;
fastcgi_pass unix:/run/php/php-fpm.sock;
}
}
Then alert on the failures from the first section:
groups:
- name: php-opcache
rules:
- alert: PhpOpcacheDisabled
expr: php_opcache_enabled == 0
for: 5m
labels:
severity: critical
annotations:
summary: "OPcache is off in PHP-FPM on {{ $labels.instance }}"
description: "Every request compiles PHP from source. Check that the opcache extension is installed and opcache.enable=1 in FPM's ini files, then reload FPM."
- alert: PhpOpcacheFull
expr: php_opcache_cache_full == 1
for: 5m
labels:
severity: warning
annotations:
summary: "OPcache memory is full on {{ $labels.instance }}"
description: "New scripts compile on every request. Raise opcache.memory_consumption above used_memory plus half again, then reload FPM off-peak."
- alert: PhpOpcacheRestarted
expr: increase(php_opcache_oom_restarts_total[30m]) + increase(php_opcache_hash_restarts_total[30m]) > 0
for: 1m
labels:
severity: warning
annotations:
summary: "OPcache emptied itself on {{ $labels.instance }}"
description: "A full cache or key table forced a restart, and every child recompiled. Raise opcache.memory_consumption or opcache.max_accelerated_files to fit your file count."
- alert: PhpOpcacheInternedStringsLow
expr: php_opcache_interned_strings_used_bytes / php_opcache_interned_strings_buffer_bytes > 0.9
for: 15m
labels:
severity: warning
annotations:
summary: "OPcache interned strings buffer is over 90% used on {{ $labels.instance }}"
description: "Once it overflows, strings stop being shared between children. Raise opcache.interned_strings_buffer and reload FPM."
Counters reset when FPM restarts, and increase() handles that. Each pod has its own OPcache, so scrape every pod.
Roll back
Keep the old ini file and record what FPM runs now:
cp /usr/local/etc/php/conf.d/opcache.ini /usr/local/etc/php/conf.d/opcache.ini.before
curl -s http://127.0.0.1:9180/metrics > opcache-before.txt
To undo the Laravel caches, run php artisan optimize:clear. It removes the config, event, route and view caches, and it also flushes the default cache store, so run it outside busy hours. Revert the OPcache file, then reload FPM.
If config:cache broke a feature because some code still calls env(), run php artisan config:clear right away and fix those calls before you cache again. If you turned off validate_timestamps and a deploy served old code, reload FPM now and add the reload to the deploy script. Other reverts can wait for a quiet hour.
More recipes
- Fix PHP-FPM server reached pm.max_children setting
Size pm.max_children from measured memory per child and set the pool's timeouts, so PHP-FPM serves peak traffic without queueing or running out of memory.
- Improve Cache Hit Ratio to Protect Your Origin at Peak
Trim the cache key, send cache headers from the origin and serve stale while revalidating, so the CDN absorbs peak traffic instead of passing it to your origin.
- Fix ALB 502 Bad Gateway and 504 Gateway Timeout
Set each target's keep-alive above the ALB idle timeout and keep slow requests under it, so the load balancer stops answering peak traffic with 502 and 504.
- Fix Lambda TooManyRequestsException Rate Exceeded
Size Lambda concurrency from peak traffic and split it with reserved and provisioned concurrency, so critical functions stop throttling when traffic spikes.