Skip to content

PHP memory_limit: measuring real consumption before you raise it

Use memory_get_peak_usage(), Blackfire, and FPM slow-log to quantify actual PHP memory consumption before adjusting memory_limit in production.

When PHP throws Allowed memory size exhausted, the knee-jerk reaction is to double memory_limit. Before touching that knob, measure what the application actually allocates — the true peak may be 30 MB or 800 MB, and the right response is completely different in each case. This runbook shows how to instrument a PHP process, collect real allocation data, and decide whether you need a higher limit, a leak fix, or a redesign of the code path that triggers the error.

How to verify

# current memory_limit for FPM and CLI
php -i | grep memory_limit
sudo grep memory_limit /etc/php/8.3/fpm/pool.d/*.conf /etc/php/8.3/fpm/php.ini

# peak usage logged in application code (add to a middleware or shutdown function)
# php -r 'echo memory_get_peak_usage(true) / 1024 / 1024 . " MiB peak\n";'

# check OS-level RSS of FPM workers right now
ps aux --sort=-%mem | grep php-fpm | head -20

# find the largest workers and their PIDs
ps -eo pid,rss,comm --sort=-rss | grep php-fpm | head -10

# inspect FPM slow log for memory hints (if request_slowlog_timeout is set)
sudo tail -f /var/log/php8.3-fpm-slow.log

A worker whose RSS grows steadily over hours without returning to baseline after request completion is leaking. A worker that spikes to 512 MB on one specific route and returns to 20 MB afterward has a code-path problem, not a leak.

What’s happening

PHP’s memory_limit is a per-request ceiling, not a per-worker ceiling. FPM workers persist between requests (pm = dynamic), so the OS RSS of a worker accumulates: base interpreter memory, extension overhead, loaded classes from OPcache (minus the shared segment), and any memory the application did not free before the request ended.

memory_get_peak_usage(true) returns the highest point of PHP’s internal allocator during the current request — reported in bytes, with true requesting the real memory allocated from the OS rather than the emalloc-level figure. This number is what memory_limit is checked against. The OS RSS is always higher because it includes the interpreter binary, loaded .so extensions, and memory PHP has freed but not yet returned to the kernel.

The gap between PHP’s peak and OS RSS matters: a worker showing 200 MB RSS may have a PHP peak of 80 MB — the rest is extension memory, JIT buffers, OPcache, or deferred munmap. Racing to raise memory_limit past 200 MB would be solving the wrong problem.

The procedure

  1. Add a shutdown hook to log peak usage per request. In a Laravel app this goes in app/Http/Middleware/MemoryLogger.php:

    <?php
    namespace App\Http\Middleware;
    use Closure;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Log;
    
    class MemoryLogger
    {
        public function handle(Request $request, Closure $next): mixed
        {
            $response = $next($request);
            $peak = memory_get_peak_usage(true) / 1048576;
            if ($peak > 64) { // only log routes above 64 MiB
                Log::warning('High memory peak', [
                    'peak_mib'  => round($peak, 1),
                    'route'     => $request->route()?->getName(),
                    'url'       => $request->path(),
                ]);
            }
            return $response;
        }
    }

    Register it globally in bootstrap/app.php. This produces structured log lines you can grep or send to a log aggregator.

  2. Identify the top offenders in the log:

    # parse laravel.log for peak memory entries
    grep 'High memory peak' /var/www/app/storage/logs/laravel.log \
      | jq -r '.[].context | "\(.peak_mib) MiB \(.url)"' \
      | sort -rn | head -20
  3. Reproduce the high-memory route in a profiler. With Blackfire:

    blackfire curl https://app.example.com/reports/export?format=csv
    # or from within the app container
    blackfire run php artisan reports:export --format=csv

    Open the Blackfire call graph and sort by memory: identify the call site that allocates the largest block. Common culprits are array_map over large result sets, Eloquent hydration of thousands of models, and image loading without streaming.

  4. Without Blackfire, use the built-in memory functions in a test script:

    <?php
    $before = memory_get_usage(true);
    $data   = SomeService::heavyQuery();          // suspect call
    $after  = memory_get_usage(true);
    echo 'Delta: ' . (($after - $before) / 1048576) . " MiB\n";
    unset($data);
    gc_collect_cycles();
    echo 'After gc: ' . (memory_get_usage(true) / 1048576) . " MiB\n";

    If gc_collect_cycles() does not return memory, you have a reference cycle.

  5. Once you know the real peak, set memory_limit conservatively above it with headroom:

    ; /etc/php/8.3/fpm/pool.d/app.ini — per-pool override
    php_admin_value[memory_limit] = 128M

    Use php_admin_value (not php_value) in pool config — it cannot be overridden from .htaccess or ini_set() in application code.

  6. For CLI commands (exports, queue workers, cron jobs), set a separate, higher limit in the command’s own ini file rather than raising the FPM pool limit:

    php -d memory_limit=1G artisan reports:export

    This prevents a runaway CLI script from inflating your FPM limit for web traffic.

Common pitfalls

  • memory_get_peak_usage(false) vs true. Without true, you get the emalloc-level figure, which excludes memory PHP allocated directly from the OS (mmap blocks for large strings). Always pass true for a number that correlates with memory_limit.

  • Raising the limit on the wrong pool. On a server with multiple FPM pools (one per application or cron), a memory_limit change in php.ini affects all of them. Isolate high-memory workloads to a dedicated pool with its own php_admin_value[memory_limit].

  • OOM from pool * workers, not per request. memory_limit = 512M with pm.max_children = 30 means up to 15 GB of potential RSS — more than most VMs. The limit per request is separate from total system memory. Plan worker counts and per-request limits together.

  • GC not collecting reference cycles. PHP’s reference counting does not free circular references until gc_collect_cycles() runs (automatically triggered, but deferrable). A request that creates many circular object graphs may show steadily growing RSS across requests in the same worker, mimicking a leak.

  • ini_set('memory_limit', '-1') left in production. This is common in import scripts that get promoted from dev. Unlimited memory allocation will happily consume all available RAM before OOM-killing the kernel process. Always enforce an explicit limit even for long-running CLI scripts.

Understanding what PHP actually allocates is foundational to every memory sizing decision. Stack Harbor’s managed operations practice instruments memory logging by default on all managed PHP environments and tracks peak-usage percentiles over time — so limit adjustments are data-driven, not guesswork.