Profiling PHP code

OxPHP ships a built-in, per-request profiler. Unlike xdebug or a standalone extension, it runs inside the server, needs no PHP restart, and costs nothing measurable while it is off.

This page is the guide: a first run, finding slow endpoints and leaks, and comparing runs before and after a change. The Profiler Reference lists every setting, file format and route, and Profiling Examples has complete PHP scenarios.

Quick start

compose.yml
services: app: image: ghcr.io/oxphp/oxphp:0.16.0 environment: INTERNAL_ADDR: 0.0.0.0:9090 PROFILER_ENABLED: "true" PROFILER_AUTH_TOKEN: "dev-secret" volumes: - ./www:/var/www/html - profiles:/tmp/oxphp-profiles ports: - "80:80" - "9090:9090" volumes: profiles:
bash
# 1. Request a page with the profiling trigger. curl -H "X-OxPHP-Profile: dev-secret" http://localhost/slow-endpoint # 2. List captured runs. curl -H "Authorization: Bearer dev-secret" http://localhost:9090/__profiler/runs \ | jq '.runs[0]' # 3. Download the newest run as collapsed stacks. RUN_ID=$(curl -s -H "Authorization: Bearer dev-secret" http://localhost:9090/__profiler/runs \ | jq -r '.runs[0].run_id') curl -H "Authorization: Bearer dev-secret" \ "http://localhost:9090/__profiler/runs/$RUN_ID.collapsed" > profile.collapsed

Drop profile.collapsed on speedscope.app to see the flamegraph.

What the profiler does

  • Records every PHP function call through the Zend Observer API, with no bytecode patching and no change to your code.
  • Builds a tree of spans with wall time, CPU time, memory at entry and exit, attributes and events.
  • Writes each run in two formats: xhprof.json and collapsed (for flamegraph.pl and speedscope.app).
  • Keeps runs in memory and on disk, and can push each one to a collector over HTTP.
  • Serves runs through four routes on the internal server (INTERNAL_ADDR).
  • Exports Prometheus metrics: runs per source, spans collected, bytes written, drops and push failures.
  • Turns on per request, through a trigger, so it needs no restart.

Three per-request modes

Mode When What is recorded
Off The default: nothing asked for profiling. Nothing, at no cost.
ApmOnly APM is enabled (OTEL_APM_ENABLED), but no profiler trigger matched. Only APM's own spans: #[Trace], the PDO and cURL hooks, oxphp_apm_*().
ProfileAll A profiler trigger matched, or the script called OxPHP\Profile\start() with the profiler enabled. Every PHP function call, plus everything APM records.

With APM and the profiler both on, a request that matches a trigger has one span tree for both, so nothing is recorded twice.

Installation and build

The plugin-profiler plugin is part of the default cargo features, so a stock build already includes it. To leave it out of your own build:

Dockerfile
ARG OXPHP_WITH_PROFILER=0 # or ARG CARGO_FEATURES="plugin-apm,plugin-otel" # no plugin-profiler

To check that it is compiled in, look at the startup log. With LOG_LEVEL=info (the default), every compiled-in plugin logs a Plugin initialized line that carries its name:

bash
docker compose logs app | grep '"Plugin initialized"' | grep '"name":"profiler"' # expect one JSON line with "message":"Plugin initialized" and "name":"profiler"

Activation triggers

Two triggers start a profile from outside the script: the X-OxPHP-Profile header, checked first, and random sampling. Either one switches the request to ProfileAll. The header's token is compared in constant time. From inside the script, start() starts a profile too.

For development, CI benchmarks, Postman collections and curl scripts.

bash
curl -H "X-OxPHP-Profile: dev-secret" https://app.local/checkout

To walk a scenario in a browser, set the header with a request-header extension. Every request sent while it is on is profiled.

Excluding paths from sampling

PROFILER_SAMPLE_RATE samples a random fraction of all requests, including framework self-traffic that pollutes the data. Symfony's web debug toolbar polls /_wdt/{token} and links to /_profiler/{token}; Laravel Debugbar and Telescope behave similarly. Keep these out of sampling with PROFILER_EXCLUDE_PATHS:

bash
PROFILER_EXCLUDE_PATHS=/_profiler,/_profiler/**,/_wdt/**

The value is a comma-separated list of glob patterns, in the syntax of PHP_DENY_PATHS: * does not cross /, ** does, and a leading / is optional. /_profiler/** covers /_profiler/x but not the bare /_profiler, so list both, as above. Patterns match the request path as received, with no percent-decoding or .. normalization, so list the literal path your framework uses.

Exclusion affects sampling only

A request carrying the X-OxPHP-Profile header is always profiled, even on an excluded path. That lets you profile /_profiler itself on purpose while keeping it out of background sampling.

PHP SDK

Five functions live in the OxPHP\Profile namespace, and each is safe to call at any time. When the request is not being profiled, the mutators do nothing and is_active() returns false. With the profiler disabled (PROFILER_ENABLED), start() does nothing either. Each function's full contract is in PHP Functions.

Explicit capture around a region

php
use function OxPHP\Profile\{start, stop}; function heavy_report(): array { start(); // turn on ProfileAll for this request $result = build_report(); // this lands in the tree stop(); // stop recording new calls return $result; }

start() turns capture on for the rest of the request, and stop() turns it off again. Both are idempotent. In a request APM is already tracing, start() discards the spans collected so far, so read its entry before you rely on them.

Leaving a call out of a profile

stop() before a noisy call and start() after it leave a gap in the tree. Check is_active() first, because start() turns profiling on for a request that was not being profiled:

php
$profiled = OxPHP\Profile\is_active(); if ($profiled) { OxPHP\Profile\stop(); } noisy_helper_we_dont_care_about(); if ($profiled) { OxPHP\Profile\start(); }

Point markers: mark()

php
use function OxPHP\Profile\mark; mark('cache_miss'); mark('got_auth_token', ['user_id' => (string) $user->id]);

mark() attaches a timestamped event to the topmost open span: an interim timestamp in a long function, or a marker for the branch taken. Neither file format carries events; What a captured span contains says where to read them.

Numeric metrics: metric()

php
use function OxPHP\Profile\metric; $rows = $pdo->query('SELECT ...')->fetchAll(); metric('db.rows', (float) count($rows)); metric('payload.kb', strlen($body) / 1024.0);

metric() records a number as a metric.<name> attribute of the current span, such as rows fetched or payload size. Attributes are not in the file formats either; the same section of the reference says where they go.

Status check: is_active()

php
if (OxPHP\Profile\is_active()) { // this request is being profiled anyway, // so an expensive debug dump is affordable error_log(json_encode($debug_state)); }

is_active() tells whether this request is being profiled. Use it to guard work that only makes sense when it is.

Attributes

Three PHP 8 attributes add an event to the span of a function or method, and change nothing else about it.

Attribute Effect
#[Mark(label?)] Adds a Mark event when the function is entered. Without a label, the event takes the function's name.
#[SlowThreshold(ms)] Adds a Slow event when the call's wall time is at least ms.
#[MemoryThreshold(kb)] Adds a MemorySpike event when the call's net allocation is at least kb.

#[Profile], #[Exclude], #[Sample] and #[Tag] were removed in 0.16.0; see Migration from 0.15.0.

Slow-function threshold

php
use OxPHP\Profile\SlowThreshold; #[SlowThreshold(ms: 250)] function render_dashboard(User $u): string { // if it runs for 250 ms or more, a Slow event is added to its span }

Memory threshold

php
use OxPHP\Profile\MemoryThreshold; #[MemoryThreshold(kb: 512)] function import_csv(string $path): int { // if it allocates 512 KB or more net while it runs, // a MemorySpike event is added to its span }

Workflows

Find a slow endpoint

  1. Turn on PROFILER_SAMPLE_RATE=0.001 in production and let runs accumulate.
  2. Sort the runs by duration_ms:
    bash
    curl -s -H "Authorization: Bearer $TOK" \ "http://INT_ADDR/__profiler/runs?limit=500" \ | jq '.runs | sort_by(.duration_ms) | reverse | .[:10] | map({run_id, url, duration_ms, span_count})'
  3. Download the slowest one and drop it on speedscope.app:
    bash
    curl -s -H "Authorization: Bearer $TOK" \ "http://INT_ADDR/__profiler/runs/<id>.collapsed" > top.collapsed
  4. Pick Left Heavy in speedscope to put the functions with the most total time first.
  5. Click the widest bar to see its time and what it calls.

Validate a before/after hypothesis

  1. Benchmark before your change:
    bash
    for i in $(seq 1 20); do curl -s -H "X-OxPHP-Profile: dev-secret" http://localhost/api/report > /dev/null done curl -s -H "Authorization: Bearer dev-secret" \ "http://localhost:9090/__profiler/runs?limit=20" \ | jq '.runs | map(.duration_ms) | sort | .[length/2|floor]' > /tmp/p50_before.txt
  2. Apply the change, rebuild, repeat, and compare the medians.
  3. For a detailed diff, download the .collapsed file of one run from each side and compare them with the FlameGraph scripts:
    bash
    difffolded.pl before.collapsed after.collapsed | flamegraph.pl > diff.svg

Hunting a memory leak

  1. Send the request that grows:
    bash
    curl -H "X-OxPHP-Profile: dev-secret" http://localhost/import?file=big.csv
  2. Download its xhprof profile and list the calls that grew memory the most:
    bash
    curl -s -H "Authorization: Bearer dev-secret" \ "http://localhost:9090/__profiler/runs/<id>.xhprof.json" \ | jq 'to_entries | sort_by(-.value.mu) | .[:10] | map({call: .key, mu: .value.mu, pmu: .value.pmu})'
  3. Add #[MemoryThreshold(kb: 1024)] to the functions you suspect. A call over the limit adds a MemorySpike event to its span, counted in the run's event_count.

Continuous monitoring of a critical path

php
#[SlowThreshold(ms: 500)] public function chargeCard(PaymentRequest $r): PaymentResult { // a Slow event on the span whenever it lags }

In Grafana, add a panel for oxphp_profiler_runs_total{source="sample"} and an alert on duration_ms outliers from index.json, through a log-based metric or a sidecar exporter.

Interaction with APM

  • APM and the profiler share one span tree (see Three per-request modes), so running both costs only APM's own coverage.
  • APM still exports only its own spans over OTLP, since Jaeger and Tempo cap a trace at about 10,000 spans. For the full tree, read the run from /__profiler/runs/<id>.
  • A run's trace_id is the trace's id, so a trace view in Grafana or Kibana can link to the run.

Best practices

  1. Never commit PROFILER_AUTH_TOKEN. Read it from Vault, Docker secrets or Kubernetes secrets.
  2. In production, use sampling. The header trigger is a developer tool. For on-demand profiling in production, use a dedicated token rotated daily.
  3. Size the disk for PROFILER_RETENTION_COUNT. A run weighs from hundreds of KB for a small request to megabytes for a large tree, so 500 runs × 2 MB is 1 GB.
  4. Mind PROFILER_MAX_SPANS on heavy requests. A request that calls helpers tens of thousands of times hits the cap. Raise it, or profile only the part you care about with start() and stop().
  5. Diff stored profiles freely. span_id is a deterministic counter, so two stored profiles diff cleanly.

Troubleshooting

No profiles appear
  1. Is the plugin compiled in? A stock build includes it. Check that you did not pass --build-arg OXPHP_WITH_PROFILER=0, or a custom CARGO_FEATURES without plugin-profiler.
  2. Is PROFILER_ENABLED=true set?
  3. Does the header value match PROFILER_AUTH_TOKEN? Look for a stray \n in the variable.
  4. Does the server see the request at all? Check the access log.
401 from /__profiler/runs

The bearer token does not match PROFILER_AUTH_TOKEN. A common trap: echo "secret" > secret.txt appends \n. Use printf, or pass the token through the environment.

The collector does not receive new runs
  1. Check that it is reachable:
    bash
    docker compose exec app curl -v $PROFILER_EXPORT_URL
  2. Look at oxphp_profiler_http_push_failures_total.
  3. Check the log. Each failed push logs a warning with the run_id and the HTTP status.
No files on disk
  • Is PROFILER_OUTPUT_DIR absolute? A relative path is ignored.
  • Is it writable by www-data?
    bash
    docker compose exec app ls -la /tmp/oxphp-profiles
  • Is PROFILER_OUTPUT_FORMATS empty? That turns disk output off.
  • Is PROFILER_DISK_MAX_PER_SEC too low? Look at oxphp_profiler_disk_drops_total.
Too much overhead in production
  • Keep PROFILER_SAMPLE_RATE between 0.0005 and 0.002.
  • Keep PROFILER_MAX_SPANS reasonable. Past it no further spans are recorded, the request itself carries on, and what was collected up to that point is written with truncated: true. For very large requests, wrap only the section you care about in start() and stop().
truncated=true in index.json

The request went past PROFILER_MAX_SPANS (default 50,000). Either raise the cap, trading memory for detail, or turn profiling on from PHP and wrap only the suspect region in start() and stop().

Migration from 0.15.0

0.16.0 removed most of the profiler's surface, with no deprecation cycle. It keeps two triggers, two file formats and a plain HTTP push.

  1. 1
    Send the header instead of the cookie or query parameter. An OXPROF cookie or a __oxprof query parameter does nothing now, even with the right token. In a browser, a request-header extension sends X-OxPHP-Profile for a whole walk through pages.
  2. 2
    Replace pause() and resume(). Both are gone, and calling either raises an Error. Use stop() and start() with the is_active() check shown under Leaving a call out of a profile.
  3. 3
    Delete #[Profile], #[Exclude], #[Sample] and #[Tag]. PHP ignores an attribute whose class is missing, so the code keeps running without their effect. Only ReflectionAttribute::newInstance() on one of them throws an Error.
  4. 4
    Clean up the variables. PROFILER_OUTPUT_FORMATS now defaults to xhprof,collapsed, and speedscope and pprof are no longer formats: a list that still names them logs a startup warning for each and writes the rest, or both formats when nothing else is left. PROFILER_INTERNAL never had an effect and is gone. PROFILER_EXPORT_XHGUI, PROFILER_EXPORT_BUGGREGATOR, PROFILER_EXPORT_APP_NAME and PROFILER_EXPORT_TAGS are ignored if still set.
  5. 5
    Put an adapter in front of xhgui or Buggregator. PROFILER_EXPORT_URL now receives exactly what PROFILER_EXPORT_FORMAT names, with no wrapper, also when the URL ends in /run/import or /api/profiler/store.
  6. 6
    Open runs from their .collapsed file. GET /__profiler/runs/{id}/speedscope is gone: download /__profiler/runs/{id}.collapsed and drop it on speedscope.app. The /__profiler/ landing page and DELETE /__profiler/runs/{id} are gone too; PROFILER_RETENTION_COUNT trims old runs.
  7. 7
    Move dashboards off /__profiler/stats. Read the oxphp_profiler_* series on /metrics instead. The label values format="speedscope", format="pprof", source="cookie" and source="query" no longer appear, so a panel or alert that selects them goes empty.

Runs stored by 0.15.0 stay listed in /__profiler/runs. Retention deletes their .speedscope.json and .pprof files as usual, and asking for those two formats over HTTP answers 404.

Prompts for your agent

These prompts assume an agent with the OxPHP documentation MCP server connected. The agent reads the pages it needs itself.

prompt
Profile a slow endpoint of mine with OxPHP's profiler. Read the `features/profiling` page through the OxPHP documentation MCP server. Turn the profiler on in this repository's Compose or Kubernetes configuration, choose between the header trigger and sampling for how I reach that endpoint, and give me the commands that capture a run and download it for speedscope.app.
prompt
Read my captured OxPHP profile and tell me what is slow. Read the `features/profiling` and `features/profiling-reference` pages through the OxPHP documentation MCP server. Pull the run through the internal profiler routes, then map its widest frames back onto the code in this repository and tell me what is worth changing first.
prompt
Move my OxPHP profiler setup from 0.15.0 to 0.16.0. Read the `features/profiling` page through the OxPHP documentation MCP server, starting with its migration section. Find everything in this repository that relies on what 0.16.0 removed (the cookie and query triggers, pause() and resume(), the removed attributes, formats and push settings, the stats and speedscope routes) and give me the change for each.

See also

Found a mistake? Report it