Fixing 'Allowed Memory Size Exhausted' in Laravel & PHP-FPM
When generating large CSV/PDF exports, running heavy background jobs, or querying large tables, PHP may terminate execution with a fatal error:
Symfony\Component\ErrorHandler\Error\FatalError
Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)
Because this is a fatal engine-level crash rather than a standard exception, PHP halts the worker immediately. Raising memory_limit in php.ini often masks an underlying memory leak in how Eloquent hydrates models.
Quick Byte-to-Megabyte Reference
When reading the raw byte count in your logs, use this table to identify which limit your process just hit:
| Error Byte Count | Megabyte Equivalent | Typical Source |
|---|---|---|
134217728 bytes |
128 MB | Default PHP-FPM web request or queue:work default ceiling |
268435456 bytes |
256 MB | Standard production web server override |
536870912 bytes |
512 MB | Heavy CLI / reporting worker ceiling |
1073741824 bytes |
1 GB | Composer or unthrottled CLI script ceiling |
Step 1: Replace Unbounded .get() Calls with lazyById() or cursor()
The most common cause of memory exhaustion in Laravel is calling Model::all() or ->get() on a table with tens of thousands of rows. Eloquent loads every row into an array and constructs a full Model object in RAM for each record.
The Broken Pattern (Loads Everything into RAM):
// Crashes at 128MB when processing 50,000+ rows
$orders = Order::where('status', 'completed')->get();
foreach ($orders as $order) {
$this->exportRow($order);
}
Fix A: Use lazyById() (Best When Updating Records or Loading Relations)
lazyById() fetches records in small internal chunks (e.g., 1,000 at a time) while giving you a clean single-loop syntax:
Order::where('status', 'completed')
->lazyById(1000)
->each(function (Order $order) {
$this->exportRow($order);
});
Fix B: Use cursor() (Lowest Memory Footprint for Read-Only Streams)
cursor() uses a PHP Generator to fetch one single row at a time from the PDO buffer, keeping memory usage flat regardless of table size:
foreach (Order::where('status', 'completed')->cursor() as $order) {
$this->exportRow($order);
}
Step 2: Break Circular $with Eager-Loading Loops
If a simple single-row query (User::find(1)) crashes with Allowed memory size exhausted, you almost certainly have an infinite eager-loading loop between two models.
The Broken Pattern:
// Inside app/Models/User.php
protected $with = ['posts'];
// Inside app/Models/Post.php
protected $with = ['user'];
When User loads, it automatically loads posts, which automatically loads user, repeating infinitely until 128MB of RAM is consumed in milliseconds.
The Fix:
Remove $with from at least one side of the relationship (or avoid default $with entirely) and load relationships explicitly in your controllers:
$user = User::with('posts')->findOrFail($id);
Step 3: Prevent Memory Leaks in Long-Running Queue Workers
Laravel queue daemons (php artisan queue:work) do not reset memory between jobs unless instructed. If telemetry packages (like Telescope, Debugbar, or custom query loggers) stay active in production, they append every query to an in-memory array until the worker crashes.
1. Disable Query Logging in Heavy Jobs
use Illuminate\Support\Facades\DB;
public function handle(): void
{
DB::disableQueryLog();
// Heavy batch processing here...
}
2. Enforce --memory Limits in Supervisor
Always configure your queue worker command to gracefully restart after crossing a safe memory threshold:
php artisan queue:work --memory=128 --max-jobs=500 --tries=3
Step 4: Increase memory_limit Properly (When Legitimately Required)
If you are generating complex PDFs (DomPDF), manipulating high-resolution images (Intervention/GD), or running large data imports that genuinely require more than 128MB, increase the limit selectively rather than globally.
Option A: Per-Job / Per-Controller Override (Safer)
Raise the ceiling only for the specific script or background job:
ini_set('memory_limit', '512M');
Option B: PHP-FPM Pool Configuration (Linux Production)
Check which php.ini file is active for your web server vs CLI:
php --ini
Update /etc/php/8.3/fpm/php.ini:
memory_limit = 256M
Restart PHP-FPM to apply the change:
sudo systemctl restart php8.3-fpm
Prevention Checklist
- Never run unbounded
->get()or::all()on tables that grow over time; usepaginate(),lazyById(), orcursor(). - Audit models for mutual
protected $with = [...]properties that trigger infinite recursion. - Disable Telescope and Debugbar in production environments (
TELESCOPE_ENABLED=false). - Pass
--memory=128and--max-jobs=500to all Supervisorqueue:workprocesses.