Metainformationen zur Seite
Dies ist eine alte Version des Dokuments!
Write Notifications ⚙️ Demystifying Laravel Jobs & Queues: Best Practices for Scalable Task Processing Sandeeppant Sandeeppant 3 min read · May 28, 2025
While building your web application, you may have some tasks, such as parsing and storing an uploaded CSV file, sending emails, image processing, API calls, etc. that take too long to perform during a typical web request. Thankfully, Laravel allows you to easily create queued jobs that may be processed in the background. By moving time intensive tasks to a queue, application can respond to web requests with blazing speed and provide a better user experience to customers. #Creating Jobs
By default, all of the queueable jobs for your application are stored in the app/Jobs directory. If the app/Jobs directory doesn't exist, it will be created when you run the make:job Artisan command:
php artisan make:job SendEmail
This creates a job class in app/Jobs/SendEmail.php with a handle() method, where you write the job logic.
use App\Mail\WelcomeMail; use Illuminate\Support\Facades\Mail;
public function handle() {
Mail::to($this->user->email)->send(new WelcomeMail($this->user));
}
#Dispatching Jobs
To queue a job, you dispatch it like so:
SendEmail::dispatch($user);
You can delay it too:
SendEmail::dispatch($user)→delay(now()→addMinutes(10));
⚙️ Queue Configuration
Laravel supports different queue drivers out of the box, like: Press enter or click to view image in full size
Set your preferred driver in .env:
For high-throughput apps, Redis is often the go-to choice.
QUEUE_CONNECTION=redis
Configure Redis queues in config/queue.php, and ensure you have Redis installed or a cloud provider configured.
Then create the jobs table:
php artisan queue:table php artisan migrate
🧾 Running the Queue Worker
php artisan queue:work
You can also run it as a daemon with:
php artisan queue:work –daemon
#Job Chaining:
Laravel supports job chaining — a powerful way to run multiple jobs in sequence.
Bus::chain([
new ProcessPodcast($podcast), new OptimizePodcast($podcast), new ReleasePodcast($podcast),
])→dispatch();
If any job in the chain fails, the remaining jobs won’t be executed. Combine with catch() to handle failure:
Bus::chain([…])
- >catch(function (Throwable $e) {
Handle chain failure })→dispatch(); #Job Batching: Batching allows you to dispatch a group of jobs together and track their collective progress. Bus::batch([ new ResizeImage($image), new ApplyWatermark($image), new UploadToCDN($image), ])→then(function (Batch $batch) { All jobs completed })→catch(function (Batch $batch, Throwable $e) {
// Handle failed job
})→finally(function (Batch $batch) {
// After all jobs (success or failure)
})→dispatch();
To use batching, ensure Queue::batch()configure the database tables with:
php artisan queue:batches-table php artisan migrate
#Job Middleware
Middleware can apply behaviors before or after the job executes:
Rate limiting Preventing duplicates Locking
Example — prevent overlapping:
use Illuminate\Queue\Middleware\WithoutOverlapping;
public function middleware() {
return [new WithoutOverlapping($this->user->id)];
}
You can also use:
ThrottlesExceptions RateLimited Custom middleware for retry/backoff control.
#Retry Strategies and Backoff
Each job can define how long to wait before retrying:
public function backoff() {
return [10, 30, 60]; // retry after 10s, then 30s, then 60s
}
You can also control maximum retries:
public $tries = 5; public $maxExceptions = 3;
To globally set retry strategy, use config/queue.php. #Job Failures, Timeouts, and Alerts
Jobs may fail due to:
External API issues Timeouts Exceptions
You can handle job failure gracefully with failed():
public function failed(Throwable $exception) {
Log::error("Job failed: " . $exception->getMessage());
}
Timeouts:
public $timeout = 120; seconds
To alert via Slack or email, use Notification classes in failed().
#Scheduling Queued Jobs
Queued jobs can also be scheduled via Laravel’s task scheduler:
$schedule→job(new CleanUpTempFiles)→daily();
Press enter or click to view image in full size
Conclusion
Laravel’s job and queue system is not just about sending emails — it’s a gateway to building resilient, scalable, event-driven architectures. With advanced techniques like batching, chaining, middleware, and Horizon monitoring, you can turn your Laravel app into a finely-tuned asynchronous machine.
Laravel
Queue
Programming
PHP
Software Development
Sandeeppant
Written by Sandeeppant
88 followers
·
5 following
Laravel Vue Js Developer https://sandeepx.github.io/portfolio
No responses yet
Anton Hummel
Anton Hummel
More from Sandeeppant
Master the Art of API Design with Laravel: Best Practices for 2026
Sandeeppant
Sandeeppant
Master the Art of API Design with Laravel: Best Practices for 2026
Building a robust API is more than just returning JSON from a controller. It’s about creating a predictable, secure, and scalable interface…
Jan 9
4
IDEMPOTENCY IN LARAVEL CONSISTENT OPERATIONS
Sandeeppant
Sandeeppant
IDEMPOTENCY IN LARAVEL CONSISTENT OPERATIONS
In modern web applications, it is essential to guarantee that sensitive actions — such as processing payments or creating resources — are…
Feb 3
1
Mastering API Development in Laravel: A Step-by-Step Guide with Best Practices
Sandeeppant
Sandeeppant
Mastering API Development in Laravel: A Step-by-Step Guide with Best Practices
APIs (Application Programming Interfaces) are the backbone of modern web and mobile applications, enabling seamless communication between…
Apr 15, 2025
33
3
Middleware in Laravel 12: A Step-by-Step Guide
Sandeeppant
Sandeeppant
Middleware in Laravel 12: A Step-by-Step Guide
Starting in Laravel 11, the configuration of the middleware changed from using the HTTP Kernel to the application’s bootstrap file. Though…
Mar 29, 2025
15
2
See all from Sandeeppant
Recommended from Medium
Laravel Best Practices: SOLID, Clean Architecture & Design Patterns
Paulo Martins
Paulo Martins
Laravel Best Practices: SOLID, Clean Architecture & Design Patterns
Laravel Best Practices: SOLID, Clean Architecture & Design Patterns
Feb 9
25
1
Building Smooth CSV Imports with Laravel Job Batches and Real-time Progress Tracking
Developer Awam
Developer Awam
Building Smooth CSV Imports with Laravel Job Batches and Real-time Progress Tracking
Learn how to upload CSV in Laravel using Queue & Batch Job with a realtime Livewire progress bar for smooth data import.
Sep 2, 2025
71
1
Mastering the Strategy Pattern in Laravel: From Chaos to Clean Code
MasteryOfLaravel
MasteryOfLaravel
Mastering the Strategy Pattern in Laravel: From Chaos to Clean Code
Strategy Pattern in Laravel: Transform Payment Processing from If-Else Hell to Clean, Testable Code with Real-World Examples
Jan 4
5
Why Your Laravel App Slows Down in Production (And How to Fix It)
Gaál Gergely
Gaál Gergely
Why Your Laravel App Slows Down in Production (And How to Fix It)
Laravel in Production: 5 Critical Pitfalls You Must Avoid
Feb 4
Laravel DTO Mapper: Type-Safe Request Handling with PHP 8 Attributes
Jakub Skowron (skowron.dev)
Jakub Skowron (skowron.dev)
Laravel DTO Mapper: Type-Safe Request Handling with PHP 8 Attributes
The Problem We All Face
Oct 17, 2025
115
4
What Happens When You Misunderstand == vs === in PHP?
Ann R.
Ann R.
What Happens When You Misunderstand == vs === in PHP?
Discover why PHP’s loose comparison (= causes dangerous production bugs. Learn the mechanics of type juggling, see real-world failure…
Feb 9
163
See more recommendations
Help
Status
About
Careers
Press
Blog
Privacy
Rules
Terms
Text to speech