A PHP process that accumulates memory across requests without returning to baseline after each one is exhibiting a memory leak. For FPM workers this manifests as steadily growing RSS over hours until the worker is recycled by pm.max_requests. For queue workers and CLI daemons — which may run for days — unchecked leaks exhaust available RAM and trigger OOM kills. This runbook distinguishes genuine PHP leaks from expected growth, shows how to locate the allocation site, and covers the fix patterns for the most common leak sources.
How to verify
# watch worker RSS grow over time — a real leak shows monotonic increase
watch -n5 "ps -eo pid,rss,comm --sort=-rss | grep php-fpm | head -10"
# compare RSS before and after a known heavy request on a specific worker
# (pin a request to one worker using nginx sticky routing or direct fastcgi)
PID=$(pgrep -n 'php-fpm: worker')
cat /proc/$PID/status | grep VmRSS
# run the heavy request
curl -s https://app.example.com/api/heavy-route > /dev/null
cat /proc/$PID/status | grep VmRSS
# if RSS grew and never returns to the before value across subsequent requests, it is leaking
# check FPM's own max_requests counter (processes are recycled to contain leaks)
sudo cat /proc/$(pgrep -n 'php-fpm: worker')/cmdline | tr '\0' ' '
grep max_requests /etc/php/8.3/fpm/pool.d/*.conf
# measure PHP-level allocation growth per request (requires instrumentation)
php -r '
$before = memory_get_usage(true);
for ($i = 0; $i < 100; $i++) {
// simulate request body
require "simulate-request.php";
gc_collect_cycles();
}
$after = memory_get_usage(true);
echo "Net growth per 100 iterations: " . (($after-$before)/1024) . " KiB\n";
'
If RSS grows monotonically across 100+ requests with gc_collect_cycles() called between them, you have either a reference cycle that the GC cannot collect or a native extension retaining memory.
What’s happening
PHP’s memory management is reference counting: each value holds a counter of references to it. When the counter drops to zero, the memory is freed immediately. Reference cycles — where object A holds a reference to object B and B holds a reference back to A — cannot be freed by reference counting alone. PHP’s cycle collector (gc_collect_cycles()) is triggered automatically after a configurable number of allocation roots, but in long-running processes it may lag behind allocation rate.
Beyond PHP-level cycles, extension memory is invisible to PHP’s allocator. PDO persistent connections, MySQL client library buffers, libcurl handles, and Imagick objects that wrap C structs all hold memory at the C level. PHP’s memory_get_usage() does not account for this. A process whose memory_get_usage() returns a flat 20 MB but whose RSS grows to 200 MB has a C-level leak in an extension.
FPM’s pm.max_requests is the containment strategy: after N requests, the worker is gracefully killed and a fresh one is spawned. This is not a fix but a rate limiter. For a queue worker processing one job per second with pm.max_requests=500, the worker is replaced every 8 minutes. If jobs average 512 KB of leaked memory, peak RSS before replacement is 256 MB — acceptable on a host with 8 GB but fatal on a 512 MB container.
The procedure
Step 1 — isolate the leaking code path
-
Enable FPM slow log to correlate large requests with worker memory growth:
; /etc/php/8.3/fpm/pool.d/app.conf request_slowlog_timeout = 3s slowlog = /var/log/php8.3-fpm-slow.log -
Add a per-request memory logger in a middleware (see the
php-memory-limit-profilingarticle for the full middleware). Log the delta between start and end of each request, not just the peak:$start = memory_get_usage(true); $response = $next($request); $end = memory_get_usage(true); if (($end - $start) > 1_048_576) { // grew by more than 1 MiB Log::warning('Request memory growth', [ 'delta_mib' => round(($end - $start) / 1048576, 2), 'end_mib' => round($end / 1048576, 2), 'url' => $request->path(), ]); }
Step 2 — pinpoint the allocation site
-
Use Xdebug’s memory profiler on a development or staging replica:
; xdebug memory profiling xdebug.mode=develop,profile xdebug.start_with_request=trigger xdebug.output_dir=/tmp/xdebug xdebug.profiler_output_name=cachegrind.out.%p.%rTrigger a profile of the leaking route:
curl -s 'https://staging.app.example.com/api/heavy-route?XDEBUG_PROFILE=1' # open /tmp/xdebug/cachegrind.out.* in qcachegrind or kcachegrind -
For production-safe inspection, use
gc_status()to monitor cycle accumulation:// add to a health-check or admin endpoint header('Content-Type: application/json'); echo json_encode([ 'gc' => gc_status(), 'memory' => [ 'current_mib' => round(memory_get_usage(true) / 1048576, 2), 'peak_mib' => round(memory_get_peak_usage(true) / 1048576, 2), ], ], JSON_PRETTY_PRINT);A rising
gc_status()['roots']that is never cleared indicates cycles accumulating faster than the GC runs.
Step 3 — fix the leak
-
Reference cycles — break them explicitly. The most common pattern in PHP frameworks is an event listener holding a reference to a service that holds a reference back to the event dispatcher:
// before — cycle: $listener → $service → $dispatcher → $listener class MyListener { public function __construct(private SomeService $service) {} } // after — use weak references to break the cycle class MyListener { private \WeakReference $serviceRef; public function __construct(SomeService $service) { $this->serviceRef = \WeakReference::create($service); } private function service(): SomeService { return $this->serviceRef->get(); } } -
Eloquent model collections — detach models after processing in a loop:
foreach (User::cursor() as $user) { process($user); // without this, ORM identity map holds every model in memory } // better: User::chunk(500, function ($users) { foreach ($users as $user) { process($user); } }); // each chunk is released after the closure returns -
Extension handles — explicitly close or destroy:
$imagick = new \Imagick($path); // ... operations ... $imagick->destroy(); // releases C-level memory, not just PHP refcount
Common pitfalls
-
Confusing RSS growth with a PHP leak. OPcache, extension shared memory, and libc’s allocator all hold pages that
ps rssincludes but PHP does not manage. A worker whose RSS grows from 30 MB to 50 MB over its lifetime and then stabilizes is exhibiting normal allocation behavior, not a leak. -
gc_collect_cycles()in a hot loop. The GC scan is O(n) in the number of cycle roots. Calling it every request on a worker that processes 1 000 requests/minute can consume more CPU than the cycle collection saves. Call it every N requests ($i % 100 === 0), not unconditionally. -
pm.max_requests=0on queue workers. This disables recycling entirely. A queue worker processing memory-leaking jobs will grow without bound. Even if you fix the leak, setmax_requeststo a finite value as a safety net. -
Weak references do not prevent destruction. A
WeakReferenceto an object does not prevent that object from being destroyed when all strong references are gone.$ref->get()returns null after the target is collected. Guard every access with a null check. -
Event listeners registered multiple times. In frameworks where listeners are registered during container bootstrapping, a misconfigured queue worker may re-register the same listener on every job, accumulating duplicate closures in the event dispatcher’s internal array — each closure holding its own reference chain.
For queue workers and CLI daemons where FPM’s max_requests safety valve does not apply, Stack Harbor’s managed operations practice sets memory thresholds in systemd’s MemoryMax= and combines that with structured memory-delta logging to provide early warning before a leak causes an outage.