Blog

PHP runtime metrics: Find the OPcache that added 24 ms per request

The PHP memory, GC, OPcache and CPU metrics Elastic contributed to OpenTelemetry explain three slowdowns, including two endpoints with the same latency.

Elastic speaks OpenTelemetry natively. Send traces, logs, and metrics over OTLP straight into Elasticsearch, no proprietary agents required. See how it fits together, try it for free in the cloud, or run it locally.

One chart of PHP runtime metrics explained a deployment that raised average latency from 16 ms to 40 ms in our demo: the OPcache was 16 MB instead of 128 MB, the hit rate fell from 100% to 44%, and no trace, query or dependency showed a problem. Elastic contributed the OpenTelemetry package that reports PHP memory, garbage collection (GC), OPcache, CPU and context switches. It is bundled with Elastic Distribution of OpenTelemetry PHP (EDOT PHP) 1.8.0 and later and with the OpenTelemetry PHP Distro. Kibana 9.6 charts it in the APM Metrics tab. This post walks through three slowdowns it explains (growing application state, an undersized OPcache, and two endpoints with identical latency) and shows how to read the metrics alongside traces.

Traces show where a request spent its time, and infrastructure metrics show whether a host or container is under pressure. Neither shows what happens inside PHP while application behavior changes. In Kibana 9.6 and later, the APM Metrics tab for a PHP service shows these metrics, and with EDOT PHP they need no extra installation or configuration.

All charts in this post come from a controlled reproduction on a single machine (PHP 8.4 with nginx and PHP-FPM, a development build of EDOT PHP, Elasticsearch and Kibana 9.6, synthetic load, one scenario at a time). Each number comes from a single run. They show how the metrics behave, and the numbers will differ in your environment.

What PHP runtime metrics add to traces and infrastructure metrics

When the 95th percentile latency of a PHP service starts climbing, traces show that requests are slower, but no single database query or external call is responsible. Container memory remains below its limit, and aggregate CPU utilization does not immediately identify a cause.

Without runtime telemetry, the investigation turns into guesses. Each question below has a metric behind it:

QuestionMetricGroup
Did the deployment allocate more memory per request?php.memory.peak_usageMemory
Is cycle collection running more often?php.gc.runs, php.gc.rootsGC
Is time going into destructors during collection?php.gc.destructor_timeGC
Was OPcache filled or invalidated after the deployment?php.opcache.memory_free, php.opcache.hit_rateOPcache
Is PHP computing, waiting, or being rescheduled?process.cpu.time, process.context_switchesCPU

Each of these questions has a metric you can read next to request latency, error rates, logs, and traces.

Runtime metrics are especially useful in traditional PHP-FPM and Apache deployments, where runtime signals show what each request costs, how OPcache behaves around deployments, and how much work the garbage collector does as application state grows.

Which OpenTelemetry package provides PHP runtime metrics?

The runtime metrics implementation was contributed to OpenTelemetry by Elastic in open-telemetry/opentelemetry-php-contrib pull request #645. The result is the standalone open-telemetry/opentelemetry-metrics-runtime package.

Elastic donated EDOT PHP to the OpenTelemetry project, and EDOT PHP is now based on the upstream OpenTelemetry PHP Distro.

Contributing the implementation upstream has two effects:

  1. The metrics are not tied to a proprietary agent or backend. They use the OpenTelemetry data model and travel over OTLP, the OpenTelemetry protocol, through the same pipeline as the rest of an application's telemetry. Elastic Observability is one destination, but the instrumentation remains useful with any compatible OpenTelemetry backend.

  2. The same runtime visibility is available on every main OpenTelemetry PHP deployment path. EDOT PHP 1.8.0 and later bundle the package and export the metrics with their native asynchronous OTLP transport, the upstream OpenTelemetry PHP Distro bundles it from version 0.6.0, and any application that uses the OpenTelemetry PHP SDK can add it with Composer.

The four groups of PHP runtime metrics: Memory, GC, OPcache and CPU

The package organizes its instruments into four groups. The package documentation has the complete reference; this section covers how to read each group.

GroupMain metricsUse it to answer
Memoryphp.memory.usage, php.memory.peak_usage, php.memory.limitHow much memory does a request need, and how close is it to memory_limit?
Garbage collectionphp.gc.runs, php.gc.collected, php.gc.roots, php.gc.threshold, php.gc.collector_timeIs cyclic cleanup becoming part of the request cost?
OPcachephp.opcache.memory_used, php.opcache.memory_free, php.opcache.hit_rate, php.opcache.cached_scriptsIs PHP running cached bytecode, or compiling on every request?
CPUprocess.cpu.time, process.context_switchesIs a request computing, or waiting?

PHP memory metrics

php.memory.usage and php.memory.peak_usage report memory through a memory.type attribute. emalloc is memory used by PHP's internal allocator; overhead is additional memory obtained from the operating system beyond emalloc. The two add up to the real allocation reported by PHP. php.memory.limit reports the configured memory_limit; when the limit is -1 (unlimited), the metric is not reported at all.

Under PHP-FPM and Apache, the values are sampled when a request finishes, so they describe what that request needed, not the lifetime of the worker. That is the right signal when memory grows because the data each request builds grows, or when a deployment raises the baseline memory per request.

PHP memory metrics and container or host memory measure different things. PHP allocation can explain which service creates the pressure, and infrastructure metrics show the effect on the surrounding system.

PHP garbage collection metrics

PHP uses reference counting for most memory management and a cycle collector for circular references. The package exposes php.gc.runs, php.gc.collected, php.gc.roots (objects currently in the root buffer), and php.gc.threshold (roots required to trigger a run). On PHP 8.3 and later it also exposes php.gc.collector_time, php.gc.destructor_time, and php.gc.free_time, which separate time spent collecting, running destructors, and freeing memory.

Under PHP-FPM and Apache, PHP restarts the collector statistics with every request. Read runs, collected, and the time metrics as per-request values: how many collection runs a typical request triggers, how many objects it frees, and what that costs. roots against threshold shows how close a request is to triggering the next run. The package exports runs, collected, and the time metrics as counters, but under PHP-FPM and Apache they do not accumulate. The GC panels show how they rise and fall, and the raw metrics give the exact per-request numbers.

More GC runs do not always mean a problem. Look for GC activity or GC time that rises together with latency, CPU time, or a deployment.

PHP OPcache metrics

OPcache keeps compiled bytecode in shared memory. The package reports memory used, free, and wasted, hit and miss counters, hit rate, the number of cached scripts, and interned-string usage. These metrics are registered only when OPcache is enabled (opcache.enable=1, and opcache.enable_cli=1 for CLI processes).

OPcache metrics matter most around deployments. A cache that is too small, or one that fills over time, shows up as free memory dropping to zero, a falling hit rate, and a cached script count that stops growing. Wasted memory is not fragmentation. It grows when OPcache discards a cached script, for example after a file changes and the script is invalidated, and the memory that script occupied stays allocated until a restart or opcache_reset() reclaims it. A steadily rising value therefore tracks invalidations, such as redeploys without a reset. OPcache schedules a restart itself when wasted memory exceeds opcache.max_wasted_percentage (5% by default) and free memory runs out, so the trend can support an evidence-based restart policy.

PHP CPU and context switch metrics

process.cpu.time separates CPU consumption into user and system modes (cpu.mode). process.context_switches separates voluntary switches, which commonly happen when a process waits, from involuntary ones, where the scheduler moved the process off the CPU (process.context_switch.type). Both are cumulative per process, so use them as rates per process ID. The CPU group requires getrusage(), and the context-switch counts may be missing on some platforms such as macOS.

The CPU and context switch metrics improve the first stage of triage, though they do not replace a profiler: rising user CPU time alongside latency suggests a compute-heavy code path, while rising system time or voluntary switches point toward I/O, scheduling, or contention.

Three PHP slowdowns that runtime metrics explain

The charts below are panels of the Metrics tab of the demo service, captured in the time window of each scenario.

The three slowdowns at a glance:

SlowdownWhat you seeMetrics that explain itLikely cause
Requests get slower as state growsAverage latency 15 ms to 49 ms; peak memory 1.4 MB to 60 MBMemory Usage, GC roots and collector time, CPU TimeGrowing in-memory state
Latency steps up after a deploymentAverage latency 16 ms to 40 ms; hit rate 100% to 44%OPcache Memory, hit rate, cached scripts, CPU TimeOPcache too small
Same latency, different causeBoth endpoints answer in about 210 to 220 msCPU Time, CPU Context Switches, GC timeCPU-bound versus waiting on a dependency

Why do PHP-FPM requests get slower as memory use grows?

A cache without a size limit, a growing result set, or a session store that is never pruned can make every request rebuild more objects than the one before. Clearing the state makes the problem disappear, which looks like a memory leak but does not prove one.

In our demo, the state grows by 8 KB with every request, about 18 MB after 15 minutes at 2.5 requests per second. A request's peak memory ends up larger than the state itself, because PHP builds objects from it. Reading the panels for the affected window together:

  • Memory Usage: The peak memory of a request climbs steadily from about 1.4 MB to about 60 MB.
  • GC roots and threshold: Roots rise toward the threshold of 10,000 and drop again after each collection, over and over, so the cycle collector runs during requests (up to nine runs per request at the end of the growth phase, from the raw php.gc.runs values).
  • GC Timings: Collector time rises from zero to about 9 ms per second at the peak and falls to zero after the reset. Treat that panel as indicative. PHP resets the GC statistics on every request, so the exported counters drop back each time. In our demo, the per-second rate came out at about half of the value computed from the raw per-request data. The raw php.gc.collector_time values give the cost of a request: about 6.5 ms on average (up to about 9.6 ms) across all requests in the last two minutes of growth. At about 2.5 requests per second that is roughly 16 ms of collector time per second, about twice what the panel shows. It is also about a sixth of the roughly 41 ms of CPU a request uses (0.10 seconds of user CPU per second at 2.5 requests per second). That is a visible cost, but not the main one.
  • CPU Time: User CPU time rises from about 0.03 to about 0.10 seconds per second, so the extra work is real computation on a growing object graph.

On the Overview tab, average latency rises from about 15 ms to about 49 ms over the same minutes (the 95th percentile reaches about 59 ms). When the state is cleared, memory, GC activity, CPU, and latency fall back together.

The charts do not identify the exact structure that keeps growing, but they narrow the search substantially. The next step can be targeted profiling or heap inspection of that endpoint instead of a broad investigation of databases, queues, and network calls.

Memory scenario over its whole length: baseline, growth, state reset, recovery.

The Overview tab for the same window; the vertical marker is the state reset.

How do you find an undersized OPcache after a deployment?

A release goes out and average latency jumps within a minute. Throughput is unchanged, the error rate stays at zero, and the extra time is spread thinly across every request instead of concentrated in one slow query or dependency.

In our demo, the release shipped with an OPcache that was far too small (16 MB instead of 128 MB). The demo is a Laravel 12 application on PHP 8.4 behind nginx with four PHP-FPM workers. k6 sends about 5 requests per second in total, split evenly between this instance and a second one that the charts leave out. The normal cache uses opcache.memory_consumption=128, the undersized one opcache.memory_consumption=16 with opcache.interned_strings_buffer=4. The deployment annotation on the Overview tab sits exactly where latency steps up. On the Metrics tab for the same window:

  • OPcache Memory: Free memory drops from about 107 MB to zero and used memory stops at the configured 16 MB. The cache is full.
  • OPcache hit rate (%): Falls from about 100% to 44% and returns to about 100% after the second deployment.
  • OPcache cached scripts: The cache holds about 424 scripts instead of roughly 960, so every request now recompiles the files that no longer fit.
  • CPU Time: User CPU time rises from about 0.06 to about 0.15 seconds per second, consistent with compiling on every request.
  • Memory Usage: The peak memory of a request grows from about 1.4 MB to about 8 MB, consistent with the compiler holding the parsed scripts in request memory.

Average latency rises from about 16 ms to about 40 ms. A second deployment that restores the cache size brings all of these signals, and the latency, back to normal.

In this incident the metrics point to one setting, the OPcache size, and one change fixes it. A short dip in hit rate right after a restart is normal while the cache fills; what matters is whether the hit rate recovers and whether free memory stays above zero.

The deployment window: the OPcache shrinks at the first deployment and recovers at the second.

The Overview tab; the vertical markers are the deployments of 1.1.0 (undersized OPcache) and 1.2.0 (the fix).

How do you tell CPU-bound PHP from PHP waiting on I/O?

Two endpoints in our demo both answer in about 210 ms (210 ms and 220 ms on average) at the same request rate. Latency alone cannot tell them apart, and neither shows an error, but the CPU metrics can:

  • CPU Time: While the first endpoint runs, user CPU time rises from about 0.03 to about 0.44 seconds per second (up to 0.53). While the second runs, it stays near 0.04, because that endpoint spends its 200 ms waiting for a dependency.
  • CPU Context Switches: The CPU-bound phase shows more involuntary switches, from about 0.4 to about 4 per second, because the scheduler moves busy processes off the CPU. In the waiting phase the pattern reverses: voluntary switches rise to about 16 to 19 per second, against about 4 at baseline, because processes give up the CPU while they wait. Individual peaks are noisy; read the pattern, not a single value.
  • GC metrics: Stay at zero in both phases (php.gc.collector_time is 0), which rules out object allocation as the explanation.

High user CPU with no GC activity suggests application computation and is a good reason to inspect a CPU profile or the slow transactions. Low CPU with many voluntary switches points to waiting, so the next place to look is the spans of a slow trace. In our demo, the waiting endpoint's trace contains an outgoing HTTP span of about 200 ms, while the computing endpoint's trace contains no outgoing spans. A simultaneous increase in GC time would make object allocation and cleanup a stronger hypothesis.

No single metric proves a cause, but together they narrow the plausible explanations and show what to check next.

CPU Time and CPU Context Switches over the baseline, CPU-bound, and waiting phases (the vertical lines and labels were added to the image).

Both slow endpoints look identical by latency alone.

A slow trace from each endpoint: the waiting one (top) has an outgoing span of about 200 ms (the last bar; the nested GET /wait above it is the agent's second server span), the computing one has none.

How do you correlate PHP runtime metrics with traces and logs?

Runtime metrics become most useful when they share resource attributes with other OpenTelemetry signals. Attributes such as service.name, service.instance.id, deployment.environment.name, service.version, k8s.pod.name, or host.name let you compare the same service, version, pod, or process across metrics, logs, and traces.

The correlation is usually temporal and resource-based: select the affected service instance and time window, inspect the runtime change, then open traces or logs from the same interval. These observable instruments do not link individual metric points to individual traces.

Choose the aggregation to match the metric type. Inspect a gauge such as memory usage per instance, or summarize it deliberately, instead of summing it across a fleet. Cumulative counters such as CPU time, hits, and misses are most useful as rates per process. The lifetime of reported values depends on the PHP SAPI and process model, so compare like with like: PHP-FPM workers with other PHP-FPM workers.

The PHP-specific instruments use the php.* namespace, while applicable operating-system process instruments use process.*, following the broader OpenTelemetry runtime semantic convention guidance.

How do you enable PHP runtime metrics with EDOT PHP or Composer?

PathRuntime metrics fromSetup
EDOT PHPVersion 1.8.0EDOT PHP setup guide
OpenTelemetry PHP DistroVersion 0.6.0Distro setup guide
Composer (PHP 8.1 or later)The open-telemetry/opentelemetry-metrics-runtime packageAdd it to an existing OpenTelemetry PHP installation

With EDOT PHP or the OpenTelemetry PHP Distro, the runtime metrics are bundled and exported automatically: you install nothing extra, and the data appears in the Kibana Metrics tab as soon as the service sends telemetry. You can switch groups off with the settings described later in this post.

Install the PHP runtime metrics package with Composer

Only the Composer path needs the package:

composer require open-telemetry/opentelemetry-metrics-runtime

The package registers itself when OpenTelemetry PHP autoloading is enabled:

OTEL_PHP_AUTOLOAD_ENABLED=true
OTEL_METRICS_EXPORTER=otlp
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

Under PHP-FPM, set these variables in the pool configuration (env[...] entries, or clear_env = no to pass the container environment to the workers); variables exported in a shell do not reach the workers. Under Apache, make sure they are in the environment of the Apache process.

Turn off individual PHP runtime metric groups

The package documentation describes how to turn metrics off with OTEL_PHP_DISABLED_INSTRUMENTATIONS:

To disableSet OTEL_PHP_DISABLED_INSTRUMENTATIONS to
The whole packagemetrics-runtime
Memory metricsmetrics-runtime-memory
GC metricsmetrics-runtime-gc
OPcache metricsmetrics-runtime-opcache
CPU and context switch metricsmetrics-runtime-cpu

Send PHP runtime metrics to Kibana

Whichever instrumentation path you choose, the metrics can be exported over OTLP to Elastic Observability or another compatible backend. For the built-in PHP panels in Kibana, the data must arrive through an OTel-native ingestion path:

  • The managed OTLP endpoint on Elastic Cloud
  • An EDOT Collector or Elastic Agent in OTel mode for self-managed deployments

The panels work with EDOT PHP and with the upstream OpenTelemetry PHP SDK, not with the classic Elastic APM PHP agent. If you send OTLP directly to APM Server's classic intake, the data is stored but the PHP panels stay empty. In Elastic Observability (Kibana 9.6 and later), open Applications → Service inventory → your PHP service → Metrics to see CPU, context switches, memory, OPcache, and garbage collection panels without building a dashboard. Use the Node name filter or a KQL query such as service.instance.id : "web-01" to focus on one instance.

When to use PHP runtime metrics alongside a profiler

Application latency, error rates, and traces tell us that user-visible behavior changed. PHP runtime metrics add another layer: whether memory allocation, cyclic garbage collection, OPcache, CPU consumption, or scheduling behavior changed with it.

Runtime metrics make the first diagnostic questions cheaper to answer, so you can decide where to look next from evidence. They complement profiling and application-level instrumentation.

To try it, send runtime metrics from a PHP-FPM service in a test environment to Kibana, lower opcache.memory_consumption, and compare the OPcache and CPU panels before and after.

Frequently Asked Questions

What PHP runtime metrics can I get with OpenTelemetry?

The open-telemetry/opentelemetry-metrics-runtime package reports four groups for PHP 8.1 and later: memory (php.memory.usage, php.memory.peak_usage, php.memory.limit), garbage collection (php.gc.*), OPcache (php.opcache.*), and CPU (process.cpu.time and process.context_switches). OPcache metrics need opcache.enable=1, and the three GC time metrics need PHP 8.3 or later.

Which EDOT PHP, PHP Distro and Kibana versions do I need for PHP runtime metrics?

EDOT PHP includes the package from version 1.8.0, and the OpenTelemetry PHP Distro from version 0.6.0. Applications that use the OpenTelemetry PHP SDK can add the package with Composer. The APM Metrics tab for PHP services is part of Kibana 9.6.

Why do PHP garbage collection metrics look like per-request values under PHP-FPM?

PHP resets the garbage collector statistics at the start of every request, so php.gc.runs, php.gc.collected, and the GC time metrics describe one request, not a running total. Use the GC panels to see how they rise and fall, and query the raw values (for example their average or maximum per interval) for exact per-request numbers.

How can I tell that my PHP OPcache is too small?

Look for free OPcache memory dropping to zero, a falling hit rate, and a cached script count that stops growing. In our demo, a 16 MB cache instead of 128 MB cut the hit rate from about 100% to about 44% and raised average latency from about 16 ms to about 40 ms.

How do I tell CPU-bound PHP from PHP that is waiting on a dependency?

Compare user CPU time and context switches for the same time window. In our demo, a CPU-bound endpoint raised user CPU from about 0.03 to about 0.44 seconds per second, while a waiting endpoint stayed near 0.04 and raised voluntary context switches to about 16 to 19 per second. Both endpoints answered in about 210 to 220 ms, so latency alone could not tell them apart.

How helpful was this content?

Related Content

Your ingest path lives in someone's head; Elastic Streams Map draws it

Your ingest path lives in someone's head; Elastic Streams Map draws it

Patri Pascual
Mobile SLOs with EDOT Android: Crash-free sessions and ANRs in Elastic Observability

Mobile SLOs with EDOT Android: Crash-free sessions and ANRs in Elastic Observability

Afzaal Ahmad Zeeshan
Meet the new Elastic Streams: Managed data pipelines for telemetry

Meet the new Elastic Streams: Managed data pipelines for telemetry

Marcin Stożek
From a checkout alert to the failing span: Investigating with the Elastic AI Agent and Elastic APM flyouts

From a checkout alert to the failing span: Investigating with the Elastic AI Agent and Elastic APM flyouts

Costas Pipilas

Elastic Observability Labs Newsletter