ProdCraft
Subscribe
PHP

PHP OPcache Tuning: Improve Application Performance Without Stale Code

Tune PHP OPcache memory, timestamp validation and deployment resets to improve performance without serving stale application code.

ProdCraft6 min read
Desktop monitor displaying programming code for diagnosing a WordPress HTTP 500 error after a plugin update

PHP OPcache stores compiled bytecode in shared memory so PHP does not need to parse and compile every script on each request. A correctly configured OPcache can reduce CPU overhead, but poor deployment handling can cause stale code or confusing differences between CLI and PHP-FPM.

Confirm OPcache is enabled in the serving SAPI

Check the configuration used by PHP-FPM or Apache, not only the CLI binary. Different PHP installations may load different INI files. Use a restricted diagnostic endpoint temporarily or inspect the process configuration through trusted administrative tooling. Remove any public phpinfo page after testing.

Review core settings

Important settings include opcache.memory_consumption, opcache.interned_strings_buffer, opcache.max_accelerated_files and opcache.validate_timestamps. The right values depend on the application size, deployment model and available memory. Monitor cache hit rate, wasted memory and restart frequency.

Handle code releases deliberately

When timestamp validation is disabled for performance, a release process must reliably reset or reload OPcache. Otherwise workers may continue executing old bytecode after files are replaced. Prefer atomic releases that switch a symlink or release directory, followed by a controlled PHP-FPM reload where appropriate.

Separate CLI and FPM behavior

Running php -i may show CLI settings that differ from the FPM pool. Check the active FPM service and its loaded INI configuration. A deployment that updates CLI PHP but not the FPM runtime can produce inconsistent behavior.

Measure before and after

Compare request latency, CPU, memory use, OPcache hit rate and application error rate under a representative workload. A high hit rate does not prove the application is fast if database queries or external APIs dominate request time.

Safe tuning checklist

  • Confirm OPcache is enabled for the web SAPI.
  • Size shared memory from real script count and usage.
  • Define a cache invalidation strategy for every release.
  • Reload FPM safely and verify workers are healthy.
  • Never expose OPcache diagnostics publicly.

OPcache is a useful performance layer, but deployment correctness matters just as much. Read PHP-FPM pool security and how to compare PHP runtime versions.

Design and prerequisites

Check the configuration loaded by the web SAPI rather than assuming CLI PHP reflects the FPM process. Different PHP versions and pools can load different INI files and extensions. Confirm the active FPM binary, pool configuration and OPcache status through trusted administrative tools. If you use a temporary diagnostic page, restrict access and remove it immediately after testing. A mismatch between CLI and FPM is a common reason a deployment appears correct in shell tests but behaves differently for web requests.

Configuration strategy

Size shared memory and interned string buffers from the application’s script footprint. Monitor cache hits, misses, wasted memory and the number of cached scripts. If the maximum accelerated file count is too low, scripts may be repeatedly evicted even when memory remains available. If shared memory is too small, the cache may restart or fail to store all required bytecode. Tune gradually and compare request latency and CPU under a representative workload.

Security and compatibility

Timestamp validation controls how OPcache notices changed files. Keeping validation enabled can simplify development and deployments, while disabling it may improve production behavior when releases are immutable. If timestamp validation is disabled, the deployment must explicitly reset or reload the cache after switching code. Without that step, workers may continue running old bytecode even though the filesystem contains the new release.

Testing and validation

Prefer atomic release directories rather than copying files over a live tree. Build the new release, verify dependencies and permissions, switch the active symlink, then reload FPM in a controlled way if required. Ensure old workers drain and new workers load the intended code. If a deployment fails, switch the symlink back and reload again. This makes code and bytecode changes easier to reason about than a partially updated directory.

Monitoring and diagnosis

OPcache is not a replacement for application profiling. If database queries, remote APIs or filesystem calls dominate request time, bytecode caching may have only a small effect. Compare p50 and p95 response time, CPU, memory and cache statistics before and after tuning. Check that performance gains do not come with stale code or more frequent FPM restarts. Keep a record of the configuration and PHP version used for each benchmark.

Operations and maintenance

Use separate configuration profiles for development and production. Development may need frequent timestamp checks, while production can use immutable releases and explicit invalidation. Ensure CLI jobs that rely on OPcache are understood separately from FPM workers. After PHP upgrades, confirm extension compatibility and inspect startup logs for shared memory or cache warnings. Document the reset procedure so on-call staff do not guess which service needs a restart.

Operational handover and review

Before handing this implementation to an operations team, document the configuration owner, supported versions, dependency map and escalation path. Include the commands or dashboard views needed to verify normal operation, along with expected values and known limitations. Store configuration in version control, review changes through the normal deployment process and keep a tested rollback procedure. Schedule periodic reviews because upstream components, security requirements and workload patterns change. A short runbook should explain how to identify a failed component, what evidence to collect, which actions are safe to retry and when to escalate. Test that runbook during a maintenance exercise rather than waiting for an outage. Finally, measure the result against a baseline: reliability improvements should be visible in error rates, latency, resource consumption, recovery time or reduced manual work. This makes the implementation maintainable after the original developer has moved to another project.

Change management and production verification

Create a controlled change record for every production adjustment. Record the current value, intended value, reason, approver and expected impact before changing the live configuration. Use a staging environment or a representative test fixture to verify behavior, and compare the result against a known baseline. Keep rollback instructions beside the change record, not in an engineer’s private notes. If the change affects a shared service, coordinate the maintenance window with its consumers and define how they will report regressions.

Service-level observability

Build operational dashboards around outcomes rather than configuration alone. Track the service-level indicators that show whether the system is working: request success, latency, queue delay, resource pressure, error counts and recovery time. Add component-specific metrics where they help explain a failure, but avoid collecting high-cardinality labels that make monitoring expensive or unstable. Define alert thresholds with an owner and a response action. An alert that has no documented next step will eventually be ignored.

Failure testing and recovery

Test failure modes before declaring the work complete. Simulate a dependency outage, an invalid input, a restart during active work and a resource limit being reached. Confirm that the system fails safely, preserves recoverable state and produces useful logs. Verify that retries are bounded and that repeating an operation does not create duplicate side effects. Capture the observed behavior in a runbook so the next operator can distinguish a transient issue from a configuration defect.

Ongoing review

Review the design after the first production cycle. Compare expected and actual resource use, support incidents, maintenance effort and user impact. Remove temporary exceptions that are no longer required, update version pins deliberately and check upstream release notes before upgrades. Re-run the original validation suite after a dependency or runtime change. A technical implementation should remain understandable to a new engineer, so document trade-offs, known limitations and the reasons behind non-obvious settings.

Apply this review specifically to PHP OPcache Tuning: Improve Application Performance Without Stale Code: confirm the supported runtime and component versions, validate the behavior with a representative workload, and retain evidence from the test. Do not treat a successful configuration reload as proof that the user-facing workflow is healthy. Verify the end-to-end result from the same network path and identity used by the production application.

Share this article

Written by

ProdCraft

ProdCraft publishes practical engineering guides on DevOps, Kubernetes, Docker, Linux, databases, cloud and LLMs — written for engineers who ship.

227 articles View profile

The weekly ops & AI brief

One email a week with the best new guides, tools and incident write-ups. No spam, unsubscribe anytime.

Leave a Reply

Your email address will not be published. Required fields are marked *