"Allowed memory size of X bytes exhausted": find the leak before raising the limit
What PHP's memory_limit fatal error means, how to tell a real leak from a big job, and fixes for the usual causes: loading whole tables, unbounded arrays, Composer and recursion.
On this page
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) in /app/src/Report.php on line 88
134217728 bytes is 128 MB, PHP’s default memory_limit. The script asked for more than the limit allows. The line number is where the last allocation happened, not necessarily where memory was wasted.
First: is it Composer?
If the error appears while running composer update or composer require, it is Composer’s dependency solver, not your code. Composer 2 already raises its own limit to 1.5 GB where it can. Run it with no limit:
COMPOSER_MEMORY_LIMIT=-1 composer update
# or
php -d memory_limit=-1 /usr/local/bin/composer update
Updating fewer packages at once (composer update vendor/package -W) also uses far less memory.
Measure before you change anything
error_log(sprintf('%s: %.1f MB (peak %.1f MB)', __LINE__,
memory_get_usage(true) / 1048576, memory_get_peak_usage(true) / 1048576));
Log this at a few points in the job. If memory rises steadily with each loop iteration, you have a leak or an unbounded collection. If it jumps once, one operation loads too much. For detail, Xdebug’s profiler and tools such as Blackfire show allocations per function.
Usual causes and fixes
Loading a whole table into an array. Iterate in chunks or with a cursor:
// Laravel
User::query()->lazyById(1000)->each(fn (User $user) => $this->export($user));
// PDO: fetch one row at a time
$stmt = $pdo->query('SELECT * FROM orders');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { /* ... */ }
With MySQL, PDO buffers the full result by default; set PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false for huge exports.
Building a giant array or string. Write rows to a file or stream as you go (fputcsv() to php://output) instead of collecting them. Generators (yield) let you keep a pipeline lazy.
Doctrine or Eloquent keeping every entity. Doctrine’s unit of work remembers each loaded entity; call $em->clear() every few hundred rows in batch jobs. Disable query logging in long-running commands.
Infinite recursion. Usually fails with a memory error deep in the same function; check the stack trace for repeating frames.
Long-running workers. Queue workers accumulate memory across jobs. Restart them periodically: php artisan queue:work --max-jobs=500 --memory=256.
When raising the limit is right
Some jobs genuinely need more memory, such as image processing or large spreadsheet imports. Raise it for that script only rather than globally:
ini_set('memory_limit', '512M');
or php -d memory_limit=512M bin/console app:import. Avoid -1 in web requests: one bad request could take down the server.