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
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:# 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.collapsedDrop 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.jsonandcollapsed(forflamegraph.pland 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:
ARG OXPHP_WITH_PROFILER=0
# or
ARG CARGO_FEATURES="plugin-apm,plugin-otel" # no plugin-profilerTo 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:
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.
curl -H "X-OxPHP-Profile: dev-secret" https://app.local/checkoutTo walk a scenario in a browser, set the header with a request-header extension. Every request sent while it is on is profiled.
For production.
PROFILER_SAMPLE_RATE=0.001 # ≈ 1 in 1000 requestsSampling needs no token. A good starting range is 0.0005 to 0.002; higher rates add noticeable overhead.
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:
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.
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
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:
$profiled = OxPHP\Profile\is_active();
if ($profiled) { OxPHP\Profile\stop(); }
noisy_helper_we_dont_care_about();
if ($profiled) { OxPHP\Profile\start(); }Point markers: mark()
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()
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()
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
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
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
- Turn on
PROFILER_SAMPLE_RATE=0.001in production and let runs accumulate. - Sort the runs by
duration_ms: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})' - Download the slowest one and drop it on speedscope.app:
curl -s -H "Authorization: Bearer $TOK" \ "http://INT_ADDR/__profiler/runs/<id>.collapsed" > top.collapsed - Pick Left Heavy in speedscope to put the functions with the most total time first.
- Click the widest bar to see its time and what it calls.
Validate a before/after hypothesis
- Benchmark before your change:
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 - Apply the change, rebuild, repeat, and compare the medians.
- For a detailed diff, download the
.collapsedfile of one run from each side and compare them with the FlameGraph scripts:difffolded.pl before.collapsed after.collapsed | flamegraph.pl > diff.svg
Hunting a memory leak
- Send the request that grows:
curl -H "X-OxPHP-Profile: dev-secret" http://localhost/import?file=big.csv - Download its xhprof profile and list the calls that grew memory the most:
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})' - Add
#[MemoryThreshold(kb: 1024)]to the functions you suspect. A call over the limit adds aMemorySpikeevent to its span, counted in the run'sevent_count.
Continuous monitoring of a critical path
#[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_idis the trace's id, so a trace view in Grafana or Kibana can link to the run.
Best practices
- Never commit
PROFILER_AUTH_TOKEN. Read it from Vault, Docker secrets or Kubernetes secrets. - In production, use sampling. The header trigger is a developer tool. For on-demand profiling in production, use a dedicated token rotated daily.
- 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. - Mind
PROFILER_MAX_SPANSon 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 withstart()andstop(). - Diff stored profiles freely.
span_idis a deterministic counter, so two stored profiles diff cleanly.
Troubleshooting
No profiles appear
- Is the plugin compiled in? A stock build includes it. Check that you did not pass
--build-arg OXPHP_WITH_PROFILER=0, or a customCARGO_FEATURESwithoutplugin-profiler. - Is
PROFILER_ENABLED=trueset? - Does the header value match
PROFILER_AUTH_TOKEN? Look for a stray\nin the variable. - 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
- Check that it is reachable:
docker compose exec app curl -v $PROFILER_EXPORT_URL - Look at
oxphp_profiler_http_push_failures_total. - Check the log. Each failed push logs a warning with the
run_idand the HTTP status.
No files on disk
- Is
PROFILER_OUTPUT_DIRabsolute? A relative path is ignored. - Is it writable by
www-data?docker compose exec app ls -la /tmp/oxphp-profiles - Is
PROFILER_OUTPUT_FORMATSempty? That turns disk output off. - Is
PROFILER_DISK_MAX_PER_SECtoo low? Look atoxphp_profiler_disk_drops_total.
Too much overhead in production
- Keep
PROFILER_SAMPLE_RATEbetween0.0005and0.002. - Keep
PROFILER_MAX_SPANSreasonable. Past it no further spans are recorded, the request itself carries on, and what was collected up to that point is written withtruncated: true. For very large requests, wrap only the section you care about instart()andstop().
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.
- 1Send the header instead of the cookie or query parameter. An
OXPROFcookie or a__oxprofquery parameter does nothing now, even with the right token. In a browser, a request-header extension sendsX-OxPHP-Profilefor a whole walk through pages. - 2Replace
pause()andresume(). Both are gone, and calling either raises anError. Usestop()andstart()with theis_active()check shown under Leaving a call out of a profile. - 3Delete
#[Profile],#[Exclude],#[Sample]and#[Tag]. PHP ignores an attribute whose class is missing, so the code keeps running without their effect. OnlyReflectionAttribute::newInstance()on one of them throws anError. - 4Clean up the variables.
PROFILER_OUTPUT_FORMATSnow defaults toxhprof,collapsed, andspeedscopeandpprofare 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_INTERNALnever had an effect and is gone.PROFILER_EXPORT_XHGUI,PROFILER_EXPORT_BUGGREGATOR,PROFILER_EXPORT_APP_NAMEandPROFILER_EXPORT_TAGSare ignored if still set. - 5Put an adapter in front of xhgui or Buggregator.
PROFILER_EXPORT_URLnow receives exactly whatPROFILER_EXPORT_FORMATnames, with no wrapper, also when the URL ends in/run/importor/api/profiler/store. - 6Open runs from their
.collapsedfile.GET /__profiler/runs/{id}/speedscopeis gone: download/__profiler/runs/{id}.collapsedand drop it on speedscope.app. The/__profiler/landing page andDELETE /__profiler/runs/{id}are gone too;PROFILER_RETENTION_COUNTtrims old runs. - 7Move dashboards off
/__profiler/stats. Read theoxphp_profiler_*series on/metricsinstead. The label valuesformat="speedscope",format="pprof",source="cookie"andsource="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.
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.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.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
- Profiler Reference: every setting, the span contents, export formats, storage, routes, push and metrics
- Profiling Examples: complete PHP scenarios
- PHP Functions: the full contract of each
OxPHP\Profile\*function - Distributed Tracing & APM: APM spans, OTLP export and the
oxphp_apm_*()functions - speedscope: the in-browser flamegraph viewer for
.collapsedfiles - FlameGraph:
flamegraph.planddifffolded.pl