Skip to content

OPcache warm-up strategies: preloading and on-hit priming

Eliminate cold-cache latency spikes after deploys by using preload scripts and request-driven priming to fill OPcache before production traffic hits.

After every FPM restart or opcache_reset() call during a deploy, the cache is cold and the first N requests for each file absorb the full compilation cost. On a Symfony or Laravel application with 15 000+ files, that cold period can produce p99 latencies 5–10x above steady state. This article covers the two practical strategies to eliminate that window — PHP 8’s preload mechanism for permanent bytecode slots, and request-driven priming for environments where preload is impractical.

How to verify

# check current cache fill level
php -r 'var_export(opcache_get_status(false)["opcache_statistics"]);'

# count cached scripts vs total PHP files on disk
php -r 'echo opcache_get_status(false)["opcache_statistics"]["num_cached_scripts"] . "\n";'
find /var/www/app -name '*.php' | wc -l

# verify preload config
php -i | grep -E 'opcache\.(preload|preload_user)'

# check preloaded classes after FPM start
php -r 'var_export(opcache_get_status(false)["preload_statistics"] ?? ["disabled"]);'

# monitor hit ratio during the warm-up window
watch -n2 "php -r 'echo opcache_get_status(false)[\"opcache_statistics\"][\"opcache_hit_rate\"] . \"%\n\";'"

A freshly restarted FPM with validate_timestamps=0 will show num_cached_scripts = 0 and opcache_hit_rate near zero until traffic or a warm-up script populates the cache.

What’s happening

OPcache stores compiled bytecode in a shared memory segment. After any FPM restart — planned or crash-induced — that segment is wiped. Each worker independently recompiles every file it encounters, serializes the opcode array to shared memory, and only then serves the cached version to subsequent workers. With pm = dynamic and 40 workers, you may have 40 concurrent compilations of the same 500 files during the first minute of traffic.

PHP 8.0 introduced opcache.preload, which runs a PHP script once at FPM start, as a privileged step before any worker is forked. Files loaded during this preload phase occupy a permanent, read-only shared memory slot that all workers inherit without copying. Preloaded scripts are never evicted, never revalidated, and never require a lock. The cost is a longer FPM startup time (typically 0.5–3 seconds) in exchange for zero cold cache on the first request.

For environments where preload is unavailable or impractical — shared hosting, containers with read-only root, preload scripts that fail silently — the alternative is a warm-up runner: a process that fires synthetic requests or calls opcache_compile_file() on every PHP file immediately after deploy, racing the first real user to populate the cache.

The procedure

Option A — PHP 8 preload (preferred)

  1. Create a preload script that requires every framework and application file:

    <?php
    // /var/www/app/preload.php
    // Laravel example — Composer classmap provides the file list
    require_once '/var/www/app/vendor/autoload.php';
    
    $map = require '/var/www/app/vendor/composer/autoload_classmap.php';
    foreach (array_unique($map) as $file) {
        if (file_exists($file)) {
            opcache_compile_file($file);
        }
    }

    For Symfony, the framework generates its own preload file at var/cache/prod/App_KernelProdContainer.preload.php — point opcache.preload at it instead of writing your own.

  2. Set these directives in /etc/php/8.3/fpm/conf.d/20-opcache.ini:

    opcache.preload=/var/www/app/preload.php
    opcache.preload_user=www-data
    opcache.memory_consumption=256
    opcache.interned_strings_buffer=32
    opcache.max_accelerated_files=65407
    opcache.validate_timestamps=0

    opcache.preload_user is mandatory when running FPM as root with worker drop — without it PHP refuses to execute the preload.

  3. Test the preload script in isolation before restarting FPM:

    sudo -u www-data php --no-php-ini \
      -d opcache.enable_cli=1 \
      -d opcache.preload=/var/www/app/preload.php \
      /var/www/app/preload.php

    Any fatal error here will prevent FPM from starting. Fix before proceeding.

  4. Restart FPM (not just reload — preload only runs at start, not reload):

    sudo systemctl restart php8.3-fpm
    # verify preload ran
    php -r 'print_r(opcache_get_status(false)["preload_statistics"]);'

    The preload_statistics.memory_consumption field should be non-zero.

Option B — opcache_compile_file() warm-up runner

  1. Create a warm-up script that compiles every PHP file from the Composer classmap:

    <?php
    // /usr/local/bin/opcache-warm.php
    $sock  = '/run/php/php8.3-fpm.sock';
    $files = include '/var/www/app/vendor/composer/autoload_classmap.php';
    $files = array_merge($files, glob('/var/www/app/app/**/*.php', GLOB_BRACE));
    
    foreach (array_unique($files) as $path) {
        if (is_file($path) && !opcache_is_script_cached($path)) {
            opcache_compile_file($path);
        }
    }
    echo count($files) . " files compiled\n";
  2. Call it via FPM (not CLI — CLI opcache is a separate instance):

    # trigger via a protected HTTP endpoint instead
    curl -s --unix-socket /run/php/php8.3-fpm.sock \
      http://localhost/opcache-warm.php
  3. Run it as the last step of the deploy pipeline:

    # deploy hook
    php /var/share/scripts/opcache-warm.php
    # or with curl if the script is web-accessible behind a secret header
    curl -s -H "X-Warm-Secret: $WARM_SECRET" https://app.example.com/_warm

Common pitfalls

  • Preload runs once at start, not reload. systemctl reload php8.3-fpm sends SIGUSR2 (graceful restart of workers) but does not re-execute the preload script. If you reload instead of restart after a deploy, preloaded bytecode stays from the previous release. For hot-swapped deploys, use opcache_reset() plus the warm-up runner instead.

  • Preload file errors kill FPM startup. A missing require, a class that references a non-existent interface, or a return statement with a value are all fatal. Keep the preload script thin — compile files with opcache_compile_file(), do not execute application bootstrapping code.

  • CLI opcache is a separate process. Running php preload.php from the shell uses the CLI process’s own opcache segment, not the FPM shared memory. The two never interact. Always test preload behaviour through an FPM request.

  • Warm-up runner may race against real traffic. On a high-traffic site, real requests will also populate the cache. The warm-up runner and live workers compete for write locks on the shared cache. This is safe but may slow compilation throughput during the priming window.

  • Symlink-based deploys break the preload path. If opcache.preload points to /var/www/app/preload.php and /var/www/app is a symlink that changes on deploy, the old path is stale. Use the real path (/var/www/releases/20251114/preload.php) or a stable wrapper at a non-symlinked location that delegates to the current release.

Managing the deploy pipeline to guarantee a warm cache on every release is one of the operational details Stack Harbor’s managed operations practice handles for PHP environments — along with monitoring the hit-rate metric to catch regressions before they affect end users.