<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sayantan Das on Medium]]></title>
        <description><![CDATA[Stories by Sayantan Das on Medium]]></description>
        <link>https://medium.com/@das.sayantan94?source=rss-df57f99a40aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l8ETbWSyWyntxdMOEBT8cQ.jpeg</url>
            <title>Stories by Sayantan Das on Medium</title>
            <link>https://medium.com/@das.sayantan94?source=rss-df57f99a40aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:03:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@das.sayantan94/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Laravel Job Queue: peeking behind the curtain (Part 2)]]></title>
            <link>https://medium.com/codelogicx/laravel-job-queue-peeking-behind-the-curtain-part-2-9af9992b5565?source=rss-df57f99a40aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/9af9992b5565</guid>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sayantan Das]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 16:16:22 GMT</pubDate>
            <atom:updated>2022-07-06T12:28:06.078Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/fa7b5d1c0390/edit?source=your_stories_page-------------------------------------">Laravel Job Queue: Peeking Behind the Curtain</a> (Part 2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mfMjTEvbTC89tZUw" /><figcaption>Photo by <a href="https://unsplash.com/@max_duz?utm_source=medium&amp;utm_medium=referral">Max Duzij</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/codelogicx/laravel-job-queue-peeking-behind-the-curtain-part-1-fa7b5d1c0390">part 1</a>, we talked about how jobs are sent to the queue. In this section, we’ll find out how jobs are picked up from the queue and processed. We’ll also look into what happens if the job throws some exception or how timeouts are implemented. So let’s get started.</p><h3>Job Processing</h3><p>Up until now, we only dispatched the job to the queue, if there is no one processing them, they will just keep accumulating in the queue storage. This is where the queue worker comes into play. Worker processes are long-running processes that are started separately, usually monitored by some process monitor like supervisor so that it can be restarted if any of the processes stop. We start the worker by running php artisan queue:work, so this command is the first thing we’ll look into.</p><p>The queue:work command is defined inside Illuminate\Queue\Console\WorkCommand class, let’s look at the handle() method of this class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJGGV1vno2TC3zigp9ufiw.png" /><figcaption>WorkCommand::handle()</figcaption></figure><p>The first part just checks whether the application is in maintenance mode and the --once flag (this will process a single job and exit) was provided, and if so, the process will sleep for the configured duration and exit. The listendForEvents() method registers event handlers for job-related events and prints the output to the console. The next part determines from which connection the worker process should fetch the jobs, if the connection name was provided, it uses that connection, otherwise it will use the default connection. Similarly, if the queue was provided it is used otherwise the default queue will be used to fetch jobs. It is possible to provide multiple queues separating them by comma (e.g. --queue=emails,default ), here the queue name that comes first has a higher priority. We’ll see how that works a little bit later. Finally, it runs the runWorker() method passing in the connection name and queue name as arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_h6CJlkZcsIMihh-9bM8A.png" /><figcaption>WorkCommand::runWorker()</figcaption></figure><p>Processing of jobs is offloaded to the Illuminate\Queue\Worker class, depending on if the --once flag was provided, the runWorker() method will call runNextJob() or daemon() on the underlying worker instance. The runNextJob() takes one job off of the queue and processes it and then exits. The daemon() method on the other hand will start an infinite loop that keeps on pulling jobs from the queue and processing them. We’ll look into this daemon() method more closely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQIblaiUU-xXjGL04a1u3w.png" /><figcaption>Worker::daemon()</figcaption></figure><p>The supportsAsyncSignals() methods checks if the pcntl extension is loaded and sets up event listeners for SIGTERM, SIGUSER2 and SIGCONT. The SIGTERM signal is probably used for graceful shutdown of the worker process and the other two seem to be used for pausing and continuing the worker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LMba-iEc04yj5Fj9G6JfQ.png" /><figcaption>Worker::daemonShouldRun()</figcaption></figure><p>The first thing that happens inside the infinite loop is to check whether the current iteration of the loop should continue or not. The daemonShouldRun() method basically checks if the application is in maintenance mode (which you can override by passing the --force flag), whether the worker is paused, and if any event listener is preventing the loop or not. The line</p><pre>$this-&gt;events-&gt;until(new Events\Looping($connectionName, $queue)) === false)</pre><p>will trigger Events\Looping event and if any listener for this event returns false, then the loop will not proceed further. So if you want to pause the worker from processing jobs temporarily, you can use this event for that.<br>If the condition returns true, then it will call the pauseWorker() method which makes the process sleep for the configured duration and checks to see if the execution should continue or not. If the worker process is consuming more memory than configured, or you have set the --stop-when-empty flag and there is no job in the list to process, or you have run the queue:restart command then the current process will exit. Another interesting thing here is that the queue:restart command doesn’t actually restart the process, it just causes the current process to exit. You have to have a separate process monitor (supervisor) to start the worker back up. The way it works is like this: when the daemon process starts, it will fetch the last time the queue was restarted from the cache and store it in a local variable. Now if at any point the value in the cache differs from the value in the local variable, the worker will exit. And all the queue:restart command does is update the last restart timestamp in the cache with the current timestamp. This will cause all the running workers to exit and if you have supervisor set up, then supervisor will restart those workers again.</p><p>Anyway, at this point, it will call the getNextJob() method to get the next job to be processed from the queue. Before we go into details about the getNextJob() method, I want to first discuss how timeouts are implemented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNAvvBxs0Tu6Tv0xT3Z_dA.png" /><figcaption>Worker::registerTimeoutHandler()</figcaption></figure><p>The registerTimeoutHandler() will register a handler for the SIGALRMsignal. The handler will kill the current process if the alarm is raised. In the next lines, an alarm is configured to be triggered at the timeout duration for the job. If you have set the timeout in your job class that is used, otherwise it will use the default timeout for the worker. The markJobAsFailedIfWillExceedMaxAttempt() will make the current job fail if it has crossed the number of times it can be retried or the timeout duration has been crossed. If the job has not exceeded the max attempts, only the worker process will exit and this job will be picked up again by a different worker process to be retried. What happens when a job fails, we’ll see later. Now let’s dig into how jobs are fetched from the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttMAX2psTP9-MDxM6hkGjA.png" /><figcaption>Worker::getNextJob()</figcaption></figure><p>Remember, that to prioritize a particular queue you need to pass it like this --queue=high,low when you start the worker? The jobs from high queue will always be processed before processing jobs fromlow queue. Here is how it happens: after exploding the queue name against , , the queue names are looped and the queue driver would try to retrieve the job from the first available queue with $connection-&gt;pop($queue). That means if there are jobs in the high priority queue, jobs from the lower priority queues won’t be processed at all. Only after the high priority queue is empty, the worker would fetch jobs from the low priority queues. I am not sure what are the chances of that happening, but it is something to keep in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6LD35Ad3wMnq08CQ-PEGA.png" /><figcaption>RedisQueue::pop()</figcaption></figure><p>The pop() method is implemented inside Illuminate\Queue\RedisQueue class. The first thing it does is migrate the expired jobs from the delayed queue and if you have configured retry_after, and the job is stuck at processing more than that duration, it will be added back to the main queue to be processed again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWWRGhEhMbI_i4FWGEevlg.png" /><figcaption>RedisQueue::migrate() and RedisQueue::migrateExpiredJobs()</figcaption></figure><p>Remember when we talked about dispatching delayed jobs, that the delayed jobs are added in a sorted set with the time it should be available for processing as the score? This is where those jobs are pulled back to the main queue. All the jobs that have expired at the current time are pulled back from the delayed queue and put back into the main queue. If you remember the ZRANGEBYSCORE command, seeing the Lua script will make things clear for you. The pulled items are also removed from the previous queue using ZREMRANGEBYSCORE command. You’ll find out about the reserved queue just a bit later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUbuVHk8t16dGs2aCm_MmQ.png" /><figcaption>LuaScripts::migrateExpiredJobs()</figcaption></figure><p>After all the jobs that are eligible to be added to the main queue are added back to it, it will now retrieve the next job from the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1UWnrejGtMk-kJK7OWjmw.png" /><figcaption>RedisQueue::retrieveNextJob()</figcaption></figure><p>To pop a job off of the queue a Lua script is run. It basically does three tasks:<br>1) Calls LPOP on the main queue list.<br>2) If LPOP returned a job it is added to the reserved queue. If you remember from earlier, reserved queues are also sorted sets. Here the expiration time for the reserved jobs is the time after addingretry_after duration to the current timestamp. As seen in the earlier section, reserved jobs are added back to the main queue after they are expired for retrying. Every time a job is added to the reserve queue, the attempt count is incremented for that job.<br>3) An item from the notify list is removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYfwsvoxfL91ORAvSL8Z8A.png" /></figure><p>So far you’ve seen this notify queue everywhere, to know its purpose, let’s look at the following snippet from the retrieveNextJob() method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHb64KHi8HjucfbWe6heaw.png" /><figcaption>notify queue</figcaption></figure><p>Laravel provides a block_for config option for Redis queue, from the docs:</p><blockquote>When using the Redis queue, you may use the <em>block_for</em> configuration option to specify how long the driver should wait for a job to become available before iterating through the worker loop and re-polling the Redis database.</blockquote><p>This is where the notify queue comes into play. If you have specified a block_for option in your config, then the worker will callBLPOP on the notify queue and this call will block for the specified duration. As we’ve seen during job dispatching, when a new job is queued, a new element is added to the notify queue as well. When a new item is added to the notify queue, the BLPOP call returns and the method recursively calls itself to pick up the new job from the actual queue. Nifty, huh?<br>If no job is returned from the queue, the method calls just returns. Otherwise, an instance of Illuminate\Queue\Jobs\RedisJob is created and returned back to the worker process. Now it’s time to process the job.</p><p>Once the job is fetched from the queue, the worker daemon will call the runJob() method which in turn will call the process() method and catch any exception or error that occurred during processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAqgB8777XANtQBI2eNlww.png" /><figcaption>Worker::process()</figcaption></figure><p>It will first trigger the before job event and then check if the job has exceeded the number of times it can be re-attempted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUIpAQZGbp1SNELkzG1tRA.png" /><figcaption>Worker::markJobAsFailedIfAlreadyExceedsMaxAttempts()</figcaption></figure><p>First, it retrieves the max tries config option, which is either configured in your job class or during starting the worker process. You can also configure a timeout duration instead of the max tries, if timeout duration is configured that takes precedence and if the current time has not crossed the timeout duration it’s considered to be eligible for processing no matter how many times it has been tried before. Otherwise, it will cause the job to fail. What happens when a job fails we’ll look into it a bit later, for now just know that it will be marked as deleted and the process() in the previous step will check the deleted status and skip processing it. If all is okay, then the job is eligible for processing and it’s fired off by $job-&gt;fire() call. Before we see what happens when a job is fired, let me first show you what happens if an exception is thrown from inside the job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYQb_bNuD8rklkYZHlK3fw.png" /><figcaption>Worker::handleJobException()</figcaption></figure><p>When an exception occurs during processing a job, be it thrown directly from the job or from somewhere else while processing it, it first checks if the job has reached the maximum number of retries and if it has, it will cause the job to fail. The fail() method can be found in Illuminate\Queue\Jobs\Job class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8dzQuF2Ym3ONynpx1LI8A.png" /><figcaption>Job::fail()</figcaption></figure><p>When a job is considered failed it means all the available retry options are exhausted and no further attempt would be done to process the job anymore. Failing a job involves marking it as failed and deleting it. $this-&gt;delete() method is overridden in the child class RedisJob, which calls the deleteReserved method on the RedisQueue instance. As we have seen earlier, when a job is picked up from processing, it is added to the reserved queue; now when it fails, it gets removed from the queue altogether.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsiOFBoqexBcVskOEsG1ow.png" /><figcaption>RedisQueue::deleteReserved()</figcaption></figure><p>As the last step of exception handling, if the job can be retried at a later time, it is released back into the delayed queue. The $job-&gt;release() call, implemented in RedisJob::release(), will call the deleteAndRelease() method on the queue driver RedisQueue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21wR_zC00pyZnVC_TM0y5A.png" /><figcaption>RedisQueue::deleteAndRelease()</figcaption></figure><p>If you have configured a delay for the failed jobs, the job would be available for processing after that delay period. Otherwise, it will be available immediately to be retried by the next iteration of the worker loop. It essentially removes the job from the reserved queue and adds it to the delayed queue after adding the delay duration as expiration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTmx-ZPpjGjxl0VXozl0jw.png" /><figcaption>LuaScripts::release()</figcaption></figure><p>Now that we’ve seen how failures are handled, the only thing left to explore is how the logic from the job class is run. That process is triggered by the $job-&gt;fire() method. This method is defined in theIlluminate\Queue\Jobs\Job class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65yQazOdXZPdUZ63nsNfCA.png" /><figcaption>Job::fire()</figcaption></figure><p>The payload here is the raw payload that is stored in Redis. If you remember our earlier discussion about the payload generation during job dispatching, then you’ll know that $payload[&#39;job&#39;] was set to Illuminate\Queue\CallQueuedHandler@call and $payload[&#39;data&#39;] was an array containing the fully qualified class name of the job and serialized version of the job instance. This is where the actual processing begins. The fire() method simply instantiates the Illuminate\Queue\CallQueuedHandler class and calls the call() method on it. Let’s see what happens there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxisloVFhBcKVk1nPU5fxg.png" /><figcaption>CallQueuedHandler::call()</figcaption></figure><p>At first, it will unserialize the job instance and if the job includes the Illuminate\Queue\InteractsWithQueue trait, it will set the instance of RedisJob into the unserialized job instance. Then it will call the dispatchNow() method on the Dispatcher. Now we’re back to the Dispatcher. This same dispatchNow() method is called if you had dispatched the job synchronously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L3PMqJVt01apJo0omBeT7g.png" /><figcaption>Dispatcher::dispatchNow()</figcaption></figure><p>This method basically creates a callback function that executes the handle() method on the job class instance and sends it through the pipeline. Laravel pipeline is beyond the scope of this post, but what it essentially does is ultimately call the callback which in turn executes the handle method. Thus our journey from the job dispatching to its execution completes here. If any exception occurs here it is handled by the exception handling discussed earlier. And if the job runs successfully, the control now goes back to the daemon() method on the worker and it will iterate again trying to find a new job to process.</p><h3>Parting Words</h3><p>I hope you have enjoyed taking this journey with me. And I sincerely hope that I could explain all these details as good as I wanted to. If something is not clear you can ask in the comments, or, you could roll up your sleeves and dig through the source code just like I did. It’s definitely a rewarding journey in the end. To see the Redis commands run by the queue system you can run redis-cli monitor and you’ll be able to see all the commands that are processed by the Redis server. Do let me know what you think about this article in the comments section, and if you have any feedback, that is welcome too. Until then, <em>sayonara.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9af9992b5565" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codelogicx/laravel-job-queue-peeking-behind-the-curtain-part-2-9af9992b5565">Laravel Job Queue: peeking behind the curtain (Part 2)</a> was originally published in <a href="https://medium.com/codelogicx">codelogicx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Job Queue: Peeking behind the curtain (Part 1)]]></title>
            <link>https://medium.com/codelogicx/laravel-job-queue-peeking-behind-the-curtain-part-1-fa7b5d1c0390?source=rss-df57f99a40aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa7b5d1c0390</guid>
            <category><![CDATA[job-queue]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Sayantan Das]]></dc:creator>
            <pubDate>Wed, 22 Jun 2022 13:34:04 GMT</pubDate>
            <atom:updated>2022-07-27T13:26:23.654Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel Job Queue: Peeking Behind the Curtain (Part 1)</h3><figure><img alt="The ElePHPant" src="https://cdn-images-1.medium.com/max/1024/0*4TH7iPWDTnqMWfbs" /><figcaption>Photo by <a href="https://unsplash.com/@benofthenorth?utm_source=medium&amp;utm_medium=referral">Ben Griffiths</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro</h3><p>If you have used Laravel in any of your projects, you have most likely used its job queue as well. Job queues provide a great way to defer time-consuming tasks that are not required for the current request (e.g. sending emails or push notifications) for a later time. This will significantly improve the response time for the requests. Laravel supports multiple storage platforms such as Redis, Amazon SQS, or even a relational database as the queue backends. But, in this post, I’ll talk only about Redis as the queue backend. On another note, as we are using a fairly older version of Laravel (v5.8), the contents in this post might differ from the latest release of Laravel, but the general implementations should not differ too much.</p><p>Laravel provides a very simple interface to interact with its queue system. All the connection configurations for each queue driver that comes with the framework are stored in config/queue.php. Each piece of business logic that needs to be offloaded to a queue is encapsulated in a Job class. You create a new job when you run the make:job artisan command (e.g. php artisan make:job SendWelcomeEmail ). Now you <em>dispatch </em>this job to the queue by calling SendWelcomeEmail::dispatch($user) or using Laravel’s helper method dispatch(new SendWelcomeEmail($user)) from your controller (or wherever you see fit). A separate worker process, started by running php artisan queue:work , will pick up the job and process it. In this post, we’ll go through what happens from the time you dispatch the job and it gets processed by the queue worker. So buckle up and focus as we go through this journey together.</p><h3>Prerequisites</h3><p>As I am going to talk about Redis as the queue backend, let’s first briefly go over the data structures that are used by Laravel to implement its queue system.</p><p><strong><em>Lists:<br> </em></strong>Lists in Redis are lists of strings, sorted by insertion order. You can add elements to a list by pushing new elements on the head (on the left) or on the tail (on the right) of the list. The LPUSH command adds the new element to the head of the list, and RPUSH command will add it at the tail of the list. Similarly, you can remove elements from the head of the list with LPOP, and use RPOP to remove it from the tail. Lists are used by Laravel as the data structure to store the jobs, new jobs are pushed to the tail of the queue with RPUSH and the worker process will fetch jobs to process from the head of the queue with LPOP, thereby maintaining the FIFO structure for a queue. The job which gets into the queue first will be processed first. <br>Redis lists have another special feature that is used by the queue system. These are blocking operations on lists. When you call LPOP or RPOP on an empty list you get back null. To find out whether there is any new item in the list you need keep running one of those commands. This causes unnecessary processing on both the client and the redis server. So Redis implements commands called BLPOP and BRPOP which are similar to LPOP and RPOP , but the difference is that these commands will block for a user specified time unless a new element is added to the list. For example,<br>BLPOP mylist 5 will block for 5 seconds if the list is empty, but as soon as a new item is added to the list it will return that item. If no item is added within 5 seconds, it will return null just like its non-blocking version.</p><p><strong><em>Sorted Set:<br></em></strong>Sets in Redis are collections of unique, nonrepeating string elements. In sorted sets, each element in the collection is also assigned a floating-point number called <em>score, </em>and the elements are ordered based on the scores associated with them. The ZADD command will add a new item in the set, ZRANGE will output the contents of the set in sorted order. We can also operate on the scores, ZRANGEBYSCORE will return the elements whose score falls within the range provided in the command and ZREMRANGEBYSCORE will remove all the elements from the set whose score falls within the given range. Let’s see some examples. In the following example, we’ll have a list of tech companies with the year of their establishment as the score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIlFVe9ogG9Jw1EOkqUybw.png" /><figcaption>Redis sorted set operations</figcaption></figure><p>For more detailed information on the Redis commands consult their docs. When you dispatch a delayed job or retry a failed job, behind the scene Laravel stores those jobs in a sorted set inside Redis. In the next sections, we’ll see how the Laravel queue uses Redis and what happens behind the scenes when you dispatch a job and when your jobs are processed.</p><h3>Dispatching Jobs</h3><p>There are mainly two ways you dispatch a job, you either call SendWelcomeEmail::dispatch($user) or dispatch(new SendWelcomeEmail($user)). In the first case, the dispatch method is provided in the Dispatchable trait that is included in your job class and for the second case, the dispatch method is a helper method that is globally available throughout your project. They both essentially do the same thing, create an instance of Illuminate\Foundation\Bus\PendingDispatch class injecting the instance of your job class as arguments. ThePendingDispatch class doesn’t do much, it just sets the queue, connection, delay, etc information in the underlying job class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnlPQZN8-oPxgjcRfD-2rg.png" /><figcaption>Dispatching jobs</figcaption></figure><p>The interesting bit happens in the destructor for the class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQ7XY5AvezcEM9Ri53KX6g.png" /><figcaption>PendingDispatch::__destruct()</figcaption></figure><p>So during the shutdown sequence of the script, the destructor will create an instance of the Illuminate\Bus\Dispatcher class and call the dispatch() method on it. Before we look into the dispatch() method, let’s first see the constructor of the Dispatcher class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZCQHTjqx9JOZvwYR0ZNRw.png" /><figcaption>Dispatcher::__construct()</figcaption></figure><p>Here the closure $queueResolver is injected by the framework’s DI container, and is responsible for fetching the appropriate queue driver based on the configuration you set in your config/queue.php file. If you are curious, the binding happens in Illuminate\Bus\BusServiceProvider and the closure internally calls the Illuminate\Queue\QueueuManager@connection() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSCBXdqos4-0wdql9h_-SA.png" /><figcaption>Dispatcher::dispatch()</figcaption></figure><p>The dispatch() method in the Dispatcher class will dispatch the job class into the queue backend if your job class implements the Illuminate\Contracts\Queue\ShouldQueue interface otherwise it will run it synchronously by calling dispatchNow(). Remember this method, we’ll come back to it again later. Now let’s look at how the job is added to the queue, this happens in dispatchToQueue() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrDNI2Wl2Jc_W3wXKzoZRg.png" /><figcaption>Dispatcher::dispatchToQueue()</figcaption></figure><p>Here you can see, that it will first resolve a concrete implementation of the queue driver using the queue resolver we talked about earlier. If you have specified the connection where your job should be dispatched in the job class, then the queue driver for that specific connection is returned, otherwise, we’ll get the driver for the default connection. In our example, we’ll receive an instance of Illuminate\Queue\RedisQueue class. If your job has a method called queue(), the dispatcher will call that method passing in the queue driver and instance of the job class (I don’t think this behavior is documented), otherwise, it will call the pushCommandToQueue() which just sends the job to the queue driver instance for storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBB8c_XnlJ4vj9OkYy772w.png" /><figcaption>Dispatcher::pushCommandToQueue()</figcaption></figure><p>Depending on if you are pushing the job to a specific queue and/or adding any delay, it calls the appropriate methods on the queue driver implementation. We’ll first look into the normal job dispatching which is available for processing instantly and then we’ll look into how delayed jobs work.</p><p>The push() method in the RedisQueue class consists of only one line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VXi--9vWhkpilG763-Q0w.png" /><figcaption>RedisQueue::push()</figcaption></figure><p>It creates the payload and calls pushRaw() with the payload and queue name. The main payload generation happens in the createObjectPayload() method in the base Queue class the RedisQueue class inherits from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJNZWUqo7pL-7V7OMKR-3A.png" /><figcaption>Queue::createObjectPayload()</figcaption></figure><p>The payload basically stores information like the delay, timeout, no of times the job could be retried, etc. The job property in the payload array is set to Illuminate\Queue\CallQueuedHandler@call, what it is and what it does we’ll find out when we talk about how jobs are processed. The data property contains the full namespace of the job class itself and serialized version of the job instance. All this data is then stored in Redis. As I said earlier, Laravel uses Redis lists to store the queue data. The key for the list is generated like this:<br>1) If you specify the name during dispatch with $job-&gt;onQueue(&#39;emails&#39;) method, the generated queue name would be queues:emails.<br>2) Otherwise, the default queue name would be used from your queue configurations. e.g. queues:default.<br>So all the different queues that you use will create different lists in the Redis server, e.g queues:emails, queues:process_image, queues:default etc. The job payload is then pushed into one of the queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sgc7dWY937VpycvM0-i9w.png" /><figcaption>RedisQueue::pushRaw()</figcaption></figure><p>If an operation requires multiple calls to the Redis server, those are done using Lua scripts that are evaluated directly in the Redis server. Even if you don&#39;t know Lua, you can clearly understand that it basically calls RPUSH Redis command to add the job payload at the end of the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGs1R31dsx2Suv4pMa7G3w.png" /><figcaption>LuaScripts::push()</figcaption></figure><p>Other than pushing the job into the list, it is also pushing the number ‘1’ into the notify list for the queue. Keep this behavior in your mind, we’ll find out why when we look into how jobs are processed.</p><p>The delayed jobs are stored in a sorted set in Redis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hde-k93BjhtZVghirUyrQ.png" /><figcaption>RedisQueue::laterRaw()</figcaption></figure><p>The key for the sorted set is generated by appending :delayed at the end of the current queue name, for example queues:default:delayed, queues:emails:delayed etc. If you remember our earlier discussion about sorted sets, each element in sorted sets is added with a score. Here, the score would be the timestamp when the job would be available for processing. So if you added 5 minutes delay to your job, the score would be $currentTimeStamp + 300;. Now to get all the jobs available for processing you can just run ZRANGEBYSCORE queues:emails:delayed -inf current_timestamp, this will return all the jobs that are expired at the moment and are available to be processed. So this means, that if you add 5 minutes delay to your job, you can be sure that it won’t be processed before the 5 minutes are over, but there is no way you can make sure that it gets processed exactly after the 5 minutes threshold is crossed. It totally depends on the no of items in your current queue.</p><p>So that’s it about job dispatching. In the <a href="https://medium.com/@das.sayantan94/laravel-job-queue-peeking-behind-the-curtain-part-2-9af9992b5565">next part</a>, we’ll see how jobs are processed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa7b5d1c0390" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codelogicx/laravel-job-queue-peeking-behind-the-curtain-part-1-fa7b5d1c0390">Laravel Job Queue: Peeking behind the curtain (Part 1)</a> was originally published in <a href="https://medium.com/codelogicx">codelogicx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>