PHP Advent

#[Production]

PHP OPcache: Production Tuning and Preloading

By Charles Hickle ·

A glass-fronted brass memory cabinet holding neatly indexed copper plates beside a glowing oscilloscope trace and analog pressure dials on a dark slate counter.

Enable PHP OPcache in production and use your web SAPI metrics to size its memory and file hash table. Your deployment reloads need to match your timestamp validation settings. Run opcache_get_status(false) inside the web server or PHP-FPM SAPI. Each SAPI has an isolated shared memory segment, and opcache.enable_cli defaults to off. If you add opcache.preload, plan for full PHP process restarts during deployment.

PHP compiles each source file into Zend opcodes before executing it. Without OPcache, every HTTP request re-parses and compiles the same framework and application files from disk. Even on a persistent worker runtime like FrankenPHP or RoadRunner, OPcache keeps shared bytecode ready across processes, and keeping it enabled during PHP profiling ensures file compilation time does not hide real bottlenecks. Starting in PHP 8.5.0, the PHP OPcache installation manual notes that OPcache is always built into the PHP binary and loaded automatically, so keeping zend_extension=opcache.so in php.ini emits a warning; see our PHP 8.5 features and upgrade guide for other upgrade changes.

Production php.ini Baseline for OPcache

Default OPcache settings work for small sites, but larger frameworks quickly exhaust the 8 MB interned strings buffer or the 10,000-file limit. Put your global settings in a dedicated php.ini drop-in file for your web SAPI (such as /etc/php/8.4/fpm/conf.d/99-opcache.ini), and keep zend_extension=opcache.so out on PHP 8.5 and newer.

[opcache]
opcache.enable = 1
opcache.memory_consumption = 256
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 20000
opcache.max_wasted_percentage = 5
opcache.validate_timestamps = 1
opcache.revalidate_freq = 60
opcache.save_comments = 1

These settings control resource limits and reload behavior. They are documented in the PHP OPcache runtime configuration manual. Measure your live application under load before settling on these values.

Shared Memory Consumption and Wasted Memory Restarts

The opcache.memory_consumption directive sets the size of OPcache's shared memory storage in megabytes, defaulting to 128 with an enforced minimum of 8. When the JIT compiler is enabled (opcache.jit defaults to "disable" in PHP 8.4 and newer, after defaulting to "tracing" in PHP 8.0 through 8.3), the shared memory segment holds both OPcache and the JIT buffer, totaling opcache.memory_consumption plus opcache.jit_buffer_size. On PHP 8.5.0 and newer, changing opcache.memory_consumption in an FPM pool after OPcache shared memory is initialized fails and logs a warning instead of being silently ignored. Set it globally in php.ini.

When files are invalidated or updated, old bytecode regions become wasted memory rather than returning immediately to the free pool. Once current_wasted_percentage reaches opcache.max_wasted_percentage (default 5, maximum 50) and free memory is insufficient, OPcache schedules a cache restart. Repeated oom_restarts in opcache_get_status() indicate that opcache.memory_consumption is too small for the compiled codebase.

Interned Strings Buffer Sizing

The opcache.interned_strings_buffer directive sets the memory available for interned strings in megabytes. These strings include class names, method names, and immutable string literals. Its default is 8 MB. On 64-bit systems, PHP 8.4.0 raised the maximum from 4095 MB to 32767 MB, while 32-bit architectures remain capped at 4095 MB.

Because frameworks and libraries register thousands of class, property, and attribute names, 8 MB fills up quickly in Symfony or Laravel applications. Inspect interned_strings_usage['free_memory'] in opcache_get_status(false); if free bytes drop near zero, increase opcache.interned_strings_buffer to 16 or 32 and raise opcache.memory_consumption to leave room for growth.

Maximum Accelerated Files and Prime Bucket Sizes

The opcache.max_accelerated_files directive controls the maximum number of script keys in the OPcache hash table, defaulting to 10000 with an allowed range of 200 to 1000000. OPcache does not allocate the exact integer you configure. Instead, it picks the first prime number in { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987, 262237, 524521, 1048793 } that is greater than or equal to your setting, so setting 20000 actually allocates 32531 slots.

Count the PHP files in your deployed release (find /var/www/app -name '*.php' | wc -l), add room for generated proxy or container files, and size opcache.max_accelerated_files comfortably above that count. Enabling Composer autoloader optimization reduces filesystem stat lookups by consolidating PSR-4 maps into autoload_classmap.php, which adds one heavily accessed file to the cache. Keep an eye on num_cached_keys versus max_cached_keys and verify hash_restarts stays at 0.

An open black aluminum memory chassis holds translucent glass and copper plates with four empty reserve bays beside a brass-framed compartment of amber blocks.

Timestamp Validation Tradeoffs and Atomic Deploys

Timestamp validation determines how often OPcache checks files on disk and when it picks up deployed changes.

Option 1: Periodic Validation (opcache.validate_timestamps = 1)

With opcache.validate_timestamps = 1 (the default), OPcache checks whether a cached script's modification time changed every opcache.revalidate_freq seconds (default 2). Raising opcache.revalidate_freq to 60 cuts stat syscalls while still letting hotfixes propagate within a minute. Setting opcache.revalidate_freq = 0 checks timestamps on every request, which suits local development rather than production.

Option 2: Disabled Validation (opcache.validate_timestamps = 0)

Setting opcache.validate_timestamps = 0 eliminates runtime timestamp checks completely. Every request executes cached bytecode without checking the file on disk. Edits on disk do not take effect until you explicitly call opcache_invalidate(), call opcache_reset() inside the web SAPI, or restart PHP-FPM. Never set opcache.validate_timestamps = 0 unless your deployment pipeline performs an automated cache clear or worker replacement on every release.

The Symlink Deployment Trap (opcache.revalidate_path and opcache.file_update_protection)

Atomic release deployments typically unpack code into /var/www/releases/2026-12-01 and swing a symlink at /var/www/current. Two settings affect how OPcache handles this:

  • opcache.revalidate_path defaults to 0. When disabled, OPcache keys scripts using the path passed to include or require without resolving symlinks again, so switching /var/www/current leaves workers executing the previous release's cached paths. Enabling opcache.revalidate_path = 1 resolves paths to their real targets on each lookup, at some lookup cost.
  • opcache.file_update_protection defaults to 2 seconds and skips caching any file modified less than two seconds ago to avoid caching half-written uploads. If your deployment replaces files atomically via release directories, you can set opcache.file_update_protection = 0 so newly deployed scripts enter the cache immediately.

Even with opcache.validate_timestamps = 0, OPcache can still check timestamps at compile time if opcache.file_update_protection or opcache.max_file_size is non-zero.

A brushed-steel and brass mechanical switch routes a glowing cyan optical conduit onto an active branch away from an unlit copper rail beside a glass-domed dial.

Inspecting Hit Rates with opcache_get_status()

Running php -r 'print_r(opcache_get_status());' over SSH can print nothing or show zero hits. There are two reasons:

  1. The opcache.enable_cli directive defaults to 0, so opcache_get_status() returns false in CLI unless you explicitly enabled CLI caching.
  2. Even with opcache.enable_cli = 1, the CLI binary creates its own short-lived memory space rather than attaching to the PHP-FPM or web server shared memory segment.

To check production hit rates, memory consumption, and wasted space, run opcache_get_status(false) inside the same web SAPI that serves HTTP traffic, as documented in the PHP status function manual. Passing false omits the large per-file scripts array (which in PHP 8.3.0+ also includes each entry's revalidate timestamp) so the health check stays fast.

<?php

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

$status = opcache_get_status(false);
if ($status === false) {
    http_response_code(503);
    echo json_encode(['error' => 'OPcache is disabled or API access is restricted']);
    exit;
}

$stats = $status['opcache_statistics'];
$memory = $status['memory_usage'];
$strings = $status['interned_strings_usage'];

echo json_encode([
    'opcache_enabled' => $status['opcache_enabled'],
    'cache_full' => $status['cache_full'],
    'hit_rate_percent' => round((float) $stats['opcache_hit_rate'], 2),
    'hits' => $stats['hits'],
    'misses' => $stats['misses'],
    'cached_keys' => $stats['num_cached_keys'],
    'max_cached_keys' => $stats['max_cached_keys'],
    'oom_restarts' => $stats['oom_restarts'],
    'hash_restarts' => $stats['hash_restarts'],
    'memory_free_mb' => round($memory['free_memory'] / 1048576, 2),
    'wasted_percent' => round((float) $memory['current_wasted_percentage'], 2),
    'interned_strings_free_mb' => round($strings['free_memory'] / 1048576, 2),
    'preload_active' => isset($status['preload_statistics']),
], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);

Call status and reset endpoints inside the web SAPI or through a local FastCGI client connected to the FPM socket. Running php -r 'opcache_reset();' leaves PHP-FPM untouched. Expose this endpoint only on a private loopback port, behind internal authentication, or guarded by opcache.restrict_api. When setting opcache.restrict_api in php.ini, always end the path prefix with a directory separator (such as /var/www/ops/ rather than /var/www/ops), because OPcache performs a plain case-sensitive prefix match against the main SAPI script path without path normalization. For example, opcache.restrict_api = /var/www/admin also allows /var/www/administrator. End the directory prefix with / to keep unintended directories from reading cache internals or calling opcache_reset().

Minimal Preload Script and Tradeoffs

Introduced in PHP 7.4.0, OPcache preloading runs a designated PHP script once when the server process starts up. As described in the PHP OPcache preloading manual, functions, classes, interfaces, and traits declared in preloaded files stay resident in memory and are immediately available to every request without triggering autoloading.

Configure preloading in php.ini with an absolute path and a non-root user:

opcache.preload = /var/www/app/config/preload.php
opcache.preload_user = www-data

When a server master process boots as root before dropping privileges (such as PHP-FPM or Apache), PHP refuses to run the preload script as root unless opcache.preload_user is explicitly set (opcache.preload_user = root is allowed but discouraged). Starting in PHP 8.3.0, PHP lifts that requirement for CLI and phpdbg, though preloading itself remains pointless for short-lived CLI commands except when working with FFI libraries. Preloading is not supported on Windows.

Choose a few stable classes to preload instead of loading everything in vendor/. Replace these paths with classes from your own application. This example uses opcache_compile_file() so the files' top-level code does not run during startup:

<?php

declare(strict_types=1);

foreach ([
    __DIR__ . '/../src/Kernel.php',
    __DIR__ . '/../src/Domain/Order.php',
] as $file) {
    if (is_file($file)) {
        opcache_compile_file($file);
    }
}

The choice between require_once (or include) and opcache_compile_file() inside preload.php affects what runs at startup:

  • require_once runs top-level statements, follows nested include calls, and handles conditional declarations, but parent classes and interfaces must be loaded in dependency order before their children.
  • opcache_compile_file() parses and caches files without executing top-level code and can compile subclasses before parent classes, though it does not traverse nested includes.

Preloading also changes what stays available between requests:

  1. Constants defined with define() are not stored by preloading; if a file defines global constants at runtime, request code must still execute it.
  2. Including an already-preloaded file during a request skips redefining its classes and functions, but its top-level code still runs, even when called via include_once.
  3. Static class properties and static variables in preloaded code behave normally and reset at request boundaries.
  4. Preloaded symbols enter a single shared table, so do not share one PHP-FPM pool across multiple applications or two versions of the same app that declare identical class names. Multiple apps or releases sharing one FPM master process collide in that table, so give each preloaded app its own FPM instance or container.

Deployment Reloads Without Serving Stale Code

A deployment can succeed and still serve old code if its cache invalidation command does not match the OPcache configuration.

If you run standard OPcache without opcache.preload, you have three ways to clear stale code after updating files or swinging a release symlink:

  • Use the PHP cache invalidation function when patching specific files: opcache_invalidate($file, true). Passing true forces invalidation even if the file timestamp did not advance, though avoid passing untrusted paths when opcache.file_cache is writable.
  • Calling the PHP cache reset function inside the web SAPI clears all in-memory cached scripts (not the optional disk file cache) so the next request compiles fresh files.
  • Running systemctl reload php8.4-fpm (sending SIGUSR2) or replacing immutable containers cleanly swaps workers onto the new release directory.

When opcache.preload is active, opcache_reset() does not reload preloaded files. Because preloaded definitions live permanently in shared memory for the server's lifetime, you must perform a full PHP-FPM service restart (systemctl restart php8.4-fpm) or replace the application container during deployment so the server boots again and runs preload.php against the new release.

A newly docked black server blade module glows with cyan and emerald indicator bars in a steel-and-brass cradle beside an unpowered older module and a brass toggle switch.

Keeping Doc Comments Available

Setting opcache.save_comments = 0 strips doc comments to save memory. This breaks libraries and tools that inspect docblocks at runtime, including Doctrine annotations, serialization metadata, and test runners. Keep opcache.save_comments = 1 when your application depends on those comments.

Frequently Asked Questions

Does OPcache replace Composer autoloader optimization or PHP worker mode?

No. Composer's --optimize-autoloader builds a class map so PHP finds files without directory scanning, OPcache caches compiled bytecode so PHP skips re-parsing those files, and worker runtimes such as FrankenPHP keep instantiated framework objects alive between requests. Production PHP-FPM apps benefit from combining Composer class-map optimization with OPcache, and worker runtimes still need OPcache enabled.

Should opcache.enable_cli be enabled in production?

Keep opcache.enable_cli = 0 unless you run long-running CLI worker daemons or queue consumers that benefit from bytecode caching across repeated includes. Short-lived CLI scripts exit immediately after running, so initializing a cache segment adds startup overhead without cross-invocation reuse.

Why did opcache_get_status() show max_cached_keys larger than my opcache.max_accelerated_files setting?

OPcache rounds opcache.max_accelerated_files up to the next prime number in its internal sizing table (such as 16229 for 15000, or 32531 for 20000) to keep hash table lookups evenly distributed. A higher max_cached_keys value is expected.