Laravel Queue: A Practical Guide to Speed Up Your Application
Picture a signup controller that creates the user, sends a welcome email, resizes the uploaded avatar and posts a note to a Slack channel, all before it returns a response. Each step is only a few lines, so nobody thinks twice about it. Then the mail server has a slow afternoon, and every new signup sits on a spinner until it finishes. Or it fails halfway and leaves someone with an account but no avatar and no email.
Queues exist for exactly this. You keep the work that has to happen before the response (creating the user) and push everything else into a job that a separate process picks up a moment later. The request ends sooner, and the slowest dependency no longer decides how fast your site feels.
One thing to say early, since the title promises speed: a queue does not make the work itself faster. The email takes just as long to send as before. What changes is who waits for it. That distinction matters later, when we get to what you should not queue.
What actually happens when you dispatch a job
Dispatching a job serialises it and writes it to a queue backend. Nothing runs at that point. A second process, started with php artisan queue:work, reads jobs from that backend and calls each job's handle() method. So there are always two moving parts: the code that dispatches, and a worker that has to be running somewhere. Most "my queue does nothing" problems come down to the second one not existing.
Choosing a driver you can actually run
Laravel supports the database, Redis, Amazon SQS and Beanstalkd. Redis is the usual choice once you have real volume, but it is one more service to install, secure and keep alive. For a small business site that sends a few hundred emails a day, the database driver is a perfectly reasonable place to start, and from Laravel 11 it is the default for new applications.
QUEUE_CONNECTION=database
New projects already include the migration that creates the jobs and failed_jobs tables. On an older app you create them yourself:
php artisan queue:table
php artisan queue:failed-table
php artisan migrate
There is also a sync driver, which runs the job immediately, inside the request. It is handy when you want to step through a job in a debugger. It is also the reason some people dispatch jobs for weeks and see no difference in response time: the connection was set to sync and nothing was ever queued. Check your .env first.
A first job
php artisan make:job SendInvoiceEmail
Here is a job that emails an invoice and retries a few times if the mail server is unavailable:
<?php
namespace App\Jobs;
use App\Mail\InvoiceMail;
use App\Models\Invoice;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;
class SendInvoiceEmail implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public array $backoff = [30, 120, 600];
public function __construct(public Invoice $invoice)
{
}
public function handle(): void
{
Mail::to($this->invoice->customer->email)
->send(new InvoiceMail($this->invoice));
}
}
The ShouldQueue interface is what tells Laravel to queue the job instead of running it on the spot. The Queueable trait lives in Illuminate\Foundation\Queue from Laravel 11; on older versions you will see Illuminate\Bus\Queueable plus a few other traits in the stub. $backoff is the wait in seconds before each retry: half a minute, two minutes, ten minutes.
Dispatching it from a controller:
$invoice = Invoice::create($data);
SendInvoiceEmail::dispatch($invoice)->afterCommit();
return redirect()->route('invoices.show', $invoice);
The afterCommit() call is easy to leave out and annoying to debug. If you dispatch inside a database transaction, a fast worker can pick the job up before the transaction commits and find no invoice. It fails with a "model not found" error, and then works when you retry it by hand, which is the worst kind of bug to chase. Calling afterCommit() on the dispatch, or setting after_commit to true on the connection in config/queue.php, makes Laravel wait for the commit.
Related: when you pass an Eloquent model to a job, Laravel stores only its class and id. The worker loads a fresh copy when the job runs. That is usually what you want, but it means any change you made in memory and did not save is invisible to the job, and if the row has been deleted by then the job fails. If a missing record is fine for a particular job, add public bool $deleteWhenMissingModels = true; and Laravel will quietly drop it.
You can also send different kinds of work to different queues, which helps when a long report generator shouldn't hold up password-reset emails:
SendInvoiceEmail::dispatch($invoice)->onQueue('emails');
php artisan queue:work --queue=emails,default
Queues listed first are checked first, so emails is drained before default gets a turn.
Running the worker, and the deploy trap
queue:work boots the framework once and then keeps looping. That is why it is fast, and it is also why it will happily keep running last week's code after you deploy. If a job behaves as if your fix never shipped, the worker is almost always the explanation. Add this to your deploy routine:
php artisan queue:restart
It tells workers to finish the job they are on and exit. Something has to start them again, and on a server you control that something is usually Supervisor. A configuration along the lines of the one in the Laravel documentation looks like this:
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/app/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/app/storage/logs/worker.log
stopwaitsecs=3600
--max-time=3600 makes each worker exit after an hour so Supervisor replaces it with a fresh one, which keeps memory from creeping up.
Queues on cPanel and shared hosting
Many shared hosts do not let you leave a process running in the background, which rules Supervisor out. The workable alternative is to let cron start a short-lived worker every minute. It processes whatever is waiting and then exits:
* * * * * cd /home/USERNAME/app && /usr/local/bin/ea-php82 artisan queue:work --stop-when-empty --max-time=50 >> /dev/null 2>&1
Two details in that line are worth explaining. --stop-when-empty makes the worker leave as soon as the queue is empty, and --max-time=50 stops it picking up new jobs after fifty seconds, so one run is normally finished before the next one starts. And the full path to the PHP binary matters. On cPanel the plain php on the command line is often not the version your website runs. On the server this site is hosted on, the CLI reported PHP 8.1 while the site itself ran 8.2, which is why Laravel's Composer platform check refused to start from the terminal. I wrote about that mismatch in the PHP 8.1 end-of-life post. Calling the versioned binary by its full path avoids the problem; check which ones your host provides.
The trade-off is latency. A job can wait up to a minute before anything touches it. That is fine for emails, exports and image processing, and not fine for anything a person is actively waiting on.
When jobs fail
A job that throws an exception is retried according to $tries and $backoff. When it runs out of attempts, Laravel records it in the failed_jobs table. From there:
php artisan queue:failed
php artisan queue:retry 5
php artisan queue:retry all
If you want something to happen when a job gives up for good, such as notifying yourself, define a failed() method on the job class. It receives the exception.
The setting that trips people up is retry_after in the connection settings of config/queue.php. It is how long Laravel waits before deciding a job has died and handing it to another worker. If a job legitimately runs longer than that, a second worker starts the same job while the first is still going, and you get duplicates. Keep the job's $timeout comfortably below retry_after, and raise both together if a job really needs more time.
Duplicates can also come from retries and crashed workers, so assume any job may run more than once and write handle() accordingly:
public function handle(): void
{
if ($this->invoice->emailed_at) {
return;
}
Mail::to($this->invoice->customer->email)
->send(new InvoiceMail($this->invoice));
$this->invoice->update(['emailed_at' => now()]);
}
This does not make it perfect. If the process dies between sending and saving, the email goes out twice. It does remove the most common case, a plain retry, and for anything involving money you would go further, with a unique key on the other side or an idempotency token on the API call.
Mail, chains and testing
Mailables have a shortcut so you do not need a job class for every email: Mail::to($user)->queue(new WelcomeMail($user)). When several steps must run in order, and the later ones should be skipped if an earlier one fails, chain them:
use Illuminate\Support\Facades\Bus;
Bus::chain([
new GenerateReport($report),
new NotifyUser($report),
])->dispatch();
For tests, Queue::fake() stops anything from being pushed and lets you assert what would have been:
use Illuminate\Support\Facades\Queue;
public function test_invoice_email_is_queued(): void
{
Queue::fake();
// ...create the invoice through your normal code path
Queue::assertPushed(SendInvoiceEmail::class);
}
To test what the job does rather than that it was queued, run it directly with SendInvoiceEmail::dispatchSync($invoice) or call handle() yourself.
What not to queue
If the next screen depends on the result, such as a payment confirmation or a price calculation the visitor is waiting to see, a queue makes things worse. You would have to poll or push the result back to the browser, and the user waits at least as long as before. Very small jobs are not worth it either. A task that takes a few milliseconds costs more in serialisation and database writes than it saves.
Queued work also needs someone to look at it. Failed jobs pile up silently in a table, and a worker that died on Tuesday looks exactly like a quiet queue. Even a weekly glance at queue:failed is better than nothing, and php artisan queue:monitor can alert you when a queue grows past a limit. If you move to Redis, Laravel Horizon gives you a proper dashboard.
If you are starting from nothing, move the one slow thing out of the request, usually an email, run a worker through cron or Supervisor, and check failed_jobs after a week. You will know by then whether the rest is worth moving. And if the queue setup on your hosting is what is stopping you, that is the kind of thing our hosting and technical support work covers.
Builds Laravel and WordPress websites and handles hosting and technical support at Dydaltix.
Related articles
Get more like this
Occasional notes on websites, hosting and PHP. No spam.