Fixing 'Allowed memory size of bytes exhausted' & Queue Worker Timeouts in Laravel
When processing heavy background jobs—such as large CSV exports, PDF generation, webhook batches, or third-party API syncs—your Laravel queue workers or web requests can fail abruptly with one of three fatal exceptions in storage/logs/laravel.log.
A PHP fatal out-of-memory crash:
Symfony\Component\ErrorHandler\Error\FatalError
Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)
A hard worker process timeout (SIGKILL / exit code 137 or 143):
Illuminate\Queue\TimeoutExceededException
App\Jobs\GenerateMonthlyReportJob has timed out.
Or a job failing after running multiple times simultaneously, even though $tries = 1:
Illuminate\Queue\MaxAttemptsExceededException
App\Jobs\ProcessStripePayoutsJob has been attempted too many times or run too long. The job may have previously timed out.
Unlike normal controller exceptions, memory exhaustion and process timeouts terminate the underlying PHP worker immediately, often leaving jobs stuck in an inconsistent state or triggering duplicate execution across concurrent workers.
Quick Diagnostic Reference
Match your exact error signature to jump directly to the permanent fix:
| Error / Symptom | Root Cause | Jump to Fix |
|---|---|---|
MaxAttemptsExceededException or jobs running twice simultaneously |
retry_after in config/queue.php is smaller than or equal to the job’s $timeout |
Fix 1 |
Allowed memory size of X bytes exhausted during Eloquent queries |
Loading thousands of Eloquent models into RAM with .get() instead of lazyById() |
Fix 2 |
| Worker memory climbs steadily over hours until Supervisor kills it | Long-lived daemon holding static state without --max-jobs or --max-time limits |
Fix 3 |
Raised memory_limit in php.ini, but Allowed memory size persists |
Edited the FPM php.ini instead of CLI php.ini, or hit Nginx/PHP-FPM timeouts |
Fix 4 |
1. The retry_after vs. $timeout Collision (Why Jobs Run Twice)
The most dangerous configuration bug in Laravel queues happens when a job takes longer than 90 seconds to run. You set public $timeout = 300; on the job class, yet the job still crashes with MaxAttemptsExceededException—or worse, a second worker picks up the exact same job at the 90-second mark while the first worker is still running it.
Why This Happens
In config/queue.php, Laravel defines a retry_after value (defaulting to 90 seconds). This setting tells Redis or your database queue how long to wait before assuming a worker has crashed and releasing the job lock back to the queue for another worker to pick up.
$timeout(or--timeout): How many seconds a single worker is allowed to run a job before PHP kills the child process.retry_after: How many seconds the queue driver waits before unlocking the job and handing it to another worker.
Rule: retry_after must always be strictly greater than your longest job $timeout.
Step 1: Update config/queue.php
Open config/queue.php and set retry_after (or DB_QUEUE_RETRY_AFTER / REDIS_QUEUE_RETRY_AFTER in .env) to at least 30 to 60 seconds higher than your longest job’s $timeout:
// config/queue.php
'connections' => [
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
// ❌ BROKEN if any job has $timeout = 300:
// 'retry_after' => 90,
// ✅ WORKING: Always keep retry_after higher than your maximum --timeout
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 360),
'block_for' => null,
'after_commit' => false,
],
],
(Note: If switching your queue driver to Redis throws a port 6379 socket error, follow our guide on Fixing Connection refused [tcp://127.0.0.1:6379] in Laravel & Docker).
Step 2: Configure Job-Level Timeouts Cleanly
In your job class, explicitly define $timeout, $tries, and $failOnTimeout:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class GenerateMonthlyReportJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of seconds the job can run before timing out.
*/
public int $timeout = 300;
/**
* The number of times the job may be attempted.
*/
public int $tries = 2;
/**
* Indicate if the job should be marked as failed on timeout.
*/
public bool $failOnTimeout = true;
public function handle(): void
{
// Job logic...
}
}
2. Fixing Allowed memory size of X bytes exhausted in Eloquent
134217728 bytes equals exactly 128 MB—PHP’s default memory ceiling. When a job or controller runs User::where('active', true)->get(), Laravel hydrates an entire Collection of Eloquent model instances, relationships, and attribute arrays into RAM all at once.
Step 1: Replace .get() with lazyById() or chunkById()
Instead of loading 50,000 rows into memory simultaneously, stream records in small batches using lazyById() so PHP garbage-collects previous batches automatically:
use App\Models\Invoice;
// ❌ CRASHES RAM: Loads all 50,000 Eloquent models into memory at once
$invoices = Invoice::where('status', 'paid')->get();
foreach ($invoices as$invoice) {
$this->exportRow($invoice);
}
// ✅ CONSTANT MEMORY (~15MB): Hydrates only 500 records into memory at a time
Invoice::where('status', 'paid')
->lazyById(500)
->each(function (Invoice $invoice) {
$this->exportRow($invoice);
});
Step 2: Disable Query Logging in Bulk Import Jobs
If a third-party package or telescope/debugging listener enables DB::enableQueryLog(), Laravel appends every executed SQL statement to an in-memory array until PHP runs out of RAM. Explicitly disable it inside heavy batch jobs:
use Illuminate\Support\Facades\DB;
public function handle(): void
{
DB::disableQueryLog();
// Perform bulk inserts or updates...
}
3. Preventing Daemon Memory Leaks in Supervisor & Horizon
Because php artisan queue:work is a long-running daemon, the PHP process does not shut down between jobs. If a PDF library, image manipulator (Intervention/GD), or static service container singleton leaks 2 MB of memory per job, the worker will inevitably crash after 60 jobs.
Step 1: Add --max-jobs, --max-time, and --memory Flags
Configure your Supervisor worker command (/etc/supervisor/conf.d/laravel-worker.conf) to automatically recycle the worker process after processing a fixed number of jobs or running for an hour:
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/artisan queue:work redis --sleep=3 --tries=3 --timeout=300 --memory=256 --max-jobs=500 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=4
redirect_stderr=true
stdout_logfile=/var/www/html/storage/logs/worker.log
stopwaitsecs=360
--max-jobs=500: Gracefully exits the PHP process after 500 jobs so Supervisor immediately spawns a fresh, zero-leak process.--max-time=3600: Recycles the worker every 60 minutes.--memory=256: Tells Laravel to gracefully exit after finishing the current job if RAM usage crosses 256 MB.stopwaitsecs=360: Ensures Supervisor waits longer than--timeout=300before forcefully killing a stopping worker during deployments.
(Note: Ensure user=www-data matches your web server user so worker logs don’t trigger permission conflicts. If your deployments fail to write to worker.log or laravel.log, see Fixing storage/logs/laravel.log Permission Denied in Linux & Docker).
Step 2: Configuring config/horizon.php (If Using Laravel Horizon)
If you manage queues with Laravel Horizon, configure the equivalent memory and timeout boundaries inside config/horizon.php:
'environments' => [
'production' => [
'supervisor-1' => [
'maxProcesses' => 10,
'balanceMaxShift' => 1,
'balanceCooldown' => 3,
'memory' => 256,
'tries' => 3,
'timeout' => 300,
],
],
],
4. Separating CLI php.ini vs. PHP-FPM php.ini Memory Limits
A common frustration on Ubuntu servers and Docker images is updating memory_limit = 512M in php.ini, restarting PHP-FPM, and still getting Allowed memory size of 134217728 bytes exhausted (128 MB) in your web requests or queue workers.
1. Check Which php.ini Is Active
Ubuntu maintains two separate configuration files:
- Web Requests (Nginx + PHP-FPM):
/etc/php/8.3/fpm/php.ini - Queue Workers & Artisan CLI:
/etc/php/8.3/cli/php.ini
If your web route crashes with memory exhaustion, edit /etc/php/8.3/fpm/php.ini:
memory_limit = 512M
Then restart PHP-FPM:
sudo systemctl restart php8.3-fpm
(Note: If a heavy web route runs too long and Nginx cuts the connection with a 502 error before PHP finishes, see our guide on Fixing 502 Bad Gateway (Nginx & PHP-FPM) in Laravel, Ubuntu & Docker).
2. Setting memory_limit in Docker Containers
Inside a Dockerized PHP image (php:8.3-fpm or Alpine), create a custom .ini file inside /usr/local/etc/php/conf.d/:
RUN echo "memory_limit=512M" > /usr/local/etc/php/conf.d/memory-limit.ini \
&& echo "max_execution_time=300" >> /usr/local/etc/php/conf.d/memory-limit.ini
(Security Note: While updating your Dockerfile or PHP-FPM packages, ensure your container base image includes the latest SAPI security patches. Check our remediation guide on How to Patch PHP2Shell (CVE-2026-109618 & CVE-2026-109619)).
Verification: Confirm Memory Limits & Restart Workers
Verify your active CLI memory limit from the terminal:
php -r "echo ini_get('memory_limit').PHP_EOL;"
# Expected output: 512M (or -1 for unlimited on CLI)
Verify your PHP-FPM pool’s memory limit:
php-fpm8.3 -i | grep memory_limit
# Expected output: memory_limit => 512M => 512M
Finally, clear your cached configuration and signal all running queue workers to reboot so they load your updated retry_after and memory settings:
php artisan config:clear
php artisan queue:restart
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl restart all
If your workers process outbound HTTPS webhooks inside those jobs and fail on SSL verification after restarting, check our guide on Fixing cURL error 60: SSL certificate problem in Laravel & Docker.