image

Laravel Queues: Everything You Need to Know

28 Oct, 2023 Abdelrahman Etry
If you're developing a Laravel application that includes intensive or long-running processes, you might have come across Laravel Queue. Queues are used to handle tasks that may take a longer time to complete, run asynchronously, and reduce the time it takes to get the response back to the browser. In this blog post, we'll explore what Laravel Queues are, how they work, and how you can implement them in your Laravel application.


What Are Laravel Queues?

In simple terms, queues are a mechanism for distributing tasks over several processors to make processing more efficient. In Laravel, queues execute tasks asynchronously in the background, separate from the usual request-response cycle. This means that even if a task takes a long time, it won't affect the application's performance.


How Laravel Queues Work?

Laravel Queue works by creating jobs, which are essentially just classes that execute specific tasks. You can dispatch a job by adding it to a queue. Laravel's built-in queue system uses an open-source background job processing system named "Redis" as a backend for persisting and dispatching the task. However, Laravel allows you to configure various driver options for queues, such as Amazon SQS or even MySQL. The most common use of queues is to send emails. Imagine that you have ten thousand subscribers, and a user subscribed today. If you're running a big project with 10,000 emails being sent at once, your server will undoubtedly feel the effect of severe traffic, too many requests, and other performance issues. You can make use of queues here to send the email jobs to the queue, and Laravel will handle the rest of the processing. This will distribute the Ten Thousand jobs over several workers or processors and prevent overloading your server.


Implementing Laravel Queues

Before you start sending jobs to your application's queue, you need to configure your Redis backend by updating queues in your Laravel application's ".env" file with the required credentials. In Laravel, there are two methods to dispatch a Laravel queue.
  • Sync Queue : This method runs the tasks in the current thread or request itself and makes sense to finish before shipping it to production. While it's good for development purposes, it's not recommended to use in the production phase.
  • Queue Worker : A queue worker receives any or multiple jobs from the queue and processes them, which is suitable for the production phase. To get a queue worker running, you have to execute the following command in your terminal: 
php artisan queue:work
Once your queue worker is up and running, you can start dispatching jobs to the queue using the following code:
dispatch(new SendMailJob());
In Laravel, the `dispatch()` method is used to send jobs to queues. You can pass any parameter that your queue's job requires in the `dispatch()` method.


To create a function for handling mail services and pass this function to the queue, you have to create a specific job class, as shown below:
class SendMailJob implements ShouldQueue{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;

    /**
     * Create a new job instance.
     *
     * @param $user
     */
    public function __construct($user){
        $this->user = $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(){
        Mail::to($this->user)->send(new WelcomeEmail());
    }
}


To send the jobs, you can run the following command on your terminal:
php artisan queue:work
This command runs indefinitely to process any queued jobs in the background. You don't have to keep this process active in your development environment. However, in production environments, the task is often defined to run in the background as a service or container.


In addition to the basics of Laravel Queues, there are some advanced concept concepts you should have a working knowledge of, including:
1. Delayed Jobs : Delayed jobs are used when you want to execute jobs in the queue but not immediately. Instead, you can set a delay time for the job execution, after which the job will be executed. For example, if you want to execute a job to send a reminder email to a user after 24 hours, you can set the delay time to 24 hours, and the job will be executed after that much time.
dispatch((new SendReminderEmail($user))->delay(now()->addHours(24)));


2. Event Broadcasting : Laravel enables you to broadcast the events of the application so that you can track various activities within an application. It allows you to broadcast specific database events, and upon the occurrence of these events, subscribers are notified of the changes made, and actions are taken where necessary. For example, when a new order is created in eCommerce, it should be broadcasted so that subscribers can be notified to process the order.
broadcast(new OrderCreated($order));


3. Chaining Jobs: You can also chain jobs in Laravel when you need to execute a series of jobs in a particular order. Laravel provides an intuitive way to do this using the `then()` method.

dispatch(new Job1())->then(new Job2())->then(new Job3());


4. Prioritizing Jobs: Laravel also allows you to prioritize the execution of jobs in a queue, so you can determine which jobs are executed first.

dispatch((new EmailReminder)->onQueue('high'));
dispatch((new LogSomething)->onQueue('low'));


Conclusion

Laravel Queues are a powerful tool that every Laravel developer should be familiar with. They allow you to handle long-running tasks and distribute them across multiple processors, thereby improving application performance. Laravel provides an easy-to-use queue system with various drivers to get started. With the right configuration, you can build scalable applications that prioritize the responsiveness and speed of your Laravel web application. Overall, Queues are a powerful tool that helps improve your application's performance and speed, and anyone developing a Laravel application should strive to incorporate it into their project. Laravel Queue is a versatile tool that enables you to manage the complexity of processing jobs. It allows you to handle long-running tasks or distribute them across multiple processors, improving the application's overall performance and speed. With further understanding of its advanced concepts, you can better leverage the queue system to handle more complicated tasks in your Laravel applications.


Recent Posts
image

Laravel Livewire

12 Sep, 2024 Abdelrahman Etry
image

Deployment with Envoyer and Laravel

30 Oct, 2023 Abdelrahman Etry
image

Laravel Request Lifecycle

28 Oct, 2023 Abdelrahman Etry
image

Laravel Queues: Everything You Need to Know

28 Oct, 2023 Abdelrahman Etry
image

Laravel Repository Pattern

28 Oct, 2023 Abdelrahman Etry
image

Laravel Packages You Should Know About

26 Oct, 2023 Abdelrahman Etry