DEV Community

Cover image for PHP is a Single-Threaded Language, So How Does Laravel Handle Queue Jobs Asynchronously?
Mahfuzur Rahman
Mahfuzur Rahman

Posted on

PHP is a Single-Threaded Language, So How Does Laravel Handle Queue Jobs Asynchronously?

PHP is known as a single-threaded language, meaning it can only execute one task at a time within a single process. However, Laravel provides a robust queue system to handle multiple tasks “asynchronously.” If PHP is single-threaded, how does Laravel achieve this magic? Let’s break it down in simple terms.

What is a PHP Process?

Before diving into queues, we need to understand what a PHP process is.

A process is like a worker hired to complete a task. When you execute a PHP script (e.g., php my_script.php), the operating system creates a new process. This process:

  • Loads the PHP script.
  • Executes the code step-by-step.
  • Stops and “dies” when the task is done. For example:
echo "Hello World!";
Enter fullscreen mode Exit fullscreen mode

When you run this script, PHP starts a process, displays “Hello World!”, and then the process ends.

PHP in Web Applications

In web applications:

  • A web server (like Apache or Nginx) receives an HTTP request from a browser.
  • The server creates a new PHP process to handle the request.
  • PHP processes the request (e.g., fetching data from a database or rendering a page).
  • The process ends after sending a response to the browser.
  • PHP processes are short-lived. They handle one request at a time and then stop. This design makes PHP simple and efficient for web applications.

What is Single-Threaded?

PHP is single-threaded, meaning:

  • A PHP process can only handle one task at a time.
  • It doesn’t perform multiple tasks simultaneously in the same process. For example:
echo "Task 1";
// Waits for Task 1 to finish before starting Task 2
echo "Task 2";
Enter fullscreen mode Exit fullscreen mode

PHP executes Task 1 first. Only after it’s done does it move to Task 2. This behavior is different from languages like JavaScript, where tasks can run in parallel in the same process.

How Does Laravel Handle Queues Then?

Laravel’s queue system allows you to run multiple tasks in the background without blocking the main application. For example:

  • Sending emails.
  • Processing image uploads.
  • Sending notifications. These tasks run in the background, so your main application can respond to users faster.

But PHP can only handle one task at a time, right? How does Laravel make it seem asynchronous? The answer lies in workers and multiple processes.

What is a Worker?

A worker in Laravel is a long-running PHP process that listens for jobs in a queue and executes them.

When you run the command:

php artisan queue:work
Enter fullscreen mode Exit fullscreen mode

A new PHP process (or worker) starts. This process:

  • Connects to the queue system (like Redis or a database).
  • Waits for new jobs (tasks) to arrive in the queue.
  • Picks up and processes jobs one by one. Example: Imagine you have a task to send 1,000 emails: The main application sends 1,000 jobs to the queue. A worker process picks up one job, sends the email, and moves to the next job.

How Does Laravel Achieve Asynchronous Behavior?

Laravel achieves “asynchronous” behavior by running multiple workers at the same time. Each worker is a separate PHP process.

Here’s how it works:
When you run php artisan queue:work, it starts with one worker (one PHP process).
You can start multiple workers to process jobs in parallel on different tabs locally and in production using the process manager like the supervisor.
This will start multiple PHP processes. Each worker handles jobs independently, making it seem like tasks are running simultaneously.

What Happens When a Job is Queued?

When you queue a job in Laravel, here’s what happens step-by-step:

  1. Job Creation: The job (e.g., send an email) is serialized (converted into a storable format) and added to the queue backend (like Redis or a database).
  2. Worker Polls the Queue: Workers continuously check the queue for new jobs. If a job is found, the worker picks it up.
  3. Job Execution: The worker deserializes the job and runs its handle() method. Once done, the job is marked as completed.
  4. Job Completion: The worker removes the job from the queue.

If the job fails, Laravel retries it or moves it to a “failed jobs” list (based on your configuration).

Example Scenario: Sending Emails
Imagine you have a Laravel application where users submit a contact form. When the form is submitted:

  • The main application processes the form and responds to the user immediately.
  • Instead of sending the email right away, it adds the email-sending task to a queue.

In the background:

  • A worker picks up the email-sending job.
  • Sends the email.
  • Moves to the next job.
  • This way, the user doesn’t have to wait for the email to be sent, making the app faster.

How Do Workers Run in Production?

In production, Laravel workers are managed by tools like Supervisor. The supervisor keeps workers running 24/7 and restarts them if they crash.

Supervisor Configuration Example:

[program:laravel-worker]
command=php /path/to/artisan queue:work --tries=3
numprocs=5
Enter fullscreen mode Exit fullscreen mode

command: Runs the queue:work command.
numprocs=5: Starts 5 workers (5 PHP processes) to handle jobs.

Is It Truly Asynchronous?

Technically, Laravel queues are not asynchronous in the way JavaScript or Node.js handle tasks. Instead:

Each worker handles one job at a time.
Multiple workers (processes) provide parallelism, giving the appearance of asynchronous execution.

Key Points to Remember

  • PHP is single-threaded, so a single PHP process handles one task at a time.
  • Laravel uses workers (long-running PHP processes) to process queue jobs.
  • Multiple workers can run simultaneously, allowing jobs to be processed in parallel.
  • Queue backends (like Redis) act as middlemen to store jobs until workers pick them up.
  • Tools like Supervisor ensure workers run continuously in production.

Laravel’s queue system is a smart way to handle tasks in the background, improving application performance and user experience. While PHP itself is single-threaded, Laravel achieves parallelism by running multiple processes (workers). This simple yet effective design allows Laravel to handle heavy workloads, even with PHP’s limitations.

Top comments (17)

Collapse
 
ilearnbydoing profile image
Durgesh Gupta

There is something called Laravel Octane you must checkout it works well with high-powered application servers, including FrankenPHP, Open Swoole, Swoole, and RoadRunner. Octane boots your application once, keeps it in memory, and then feeds it requests at supersonic speeds.

Collapse
 
devmahfuz profile image
Mahfuzur Rahman

Thanks for your suggestion. I will definitely look into it.

Collapse
 
shawn_mcallister_109fd3fb profile image
Shawn McAllister

PHP itself is single threaded but most httpd servers are multi-threaded.

Collapse
 
vicentimartins profile image
Vicente Martins

Perfect! To deep on any tech is the best way to learn and develop itself. Congrats!!!

Collapse
 
perisicnikola37 profile image
Nikola Perišić

Thank you for sharing this

Collapse
 
miguelgilmartinez profile image
Miguel Gil Martínez

What about fibers? Is it not used by Laravel to achieve multiparalelism?

Collapse
 
devmahfuz profile image
Mahfuzur Rahman

Actually no, php fiber is not a multi-paralelism. It just helps you to stop a function's execution and later resume it. It doesn't run in background or in a separate thread. And when you resume a fiber function it runs synchronously in the main PHP process.

Collapse
 
markuszeller profile image
Markus Zeller

I would prefer calling it concurrency instead of parallelism.

Collapse
 
dan_le_brown profile image
Brown • Edited

Based on my understanding of the two concepts, I believe parallelism is the most-suited word:
Each spun worker executes "just" one task per time and they do so in parallel.

This is different from a concurrent operation where you have "just" one worker executing various tasks but toggling between them as each task runs into an operation, say, a network call, that cannot be resolved in that same moment (but will be, later).
The same worker keeps toggling/switching until all the tasks are executed eventually

In parallelism, you have processes like this:

worker 1
o – o – o – o

worker 2
o – o – o – o – o – o

In concurrency, you have a process like this:

worker 1
Image description

(where "o" signifies the executed task, and "–' represents the current path of execution)

Let me know if this makes any sense.

Collapse
 
devmahfuz profile image
Mahfuzur Rahman

Nicely explained !!

Thread Thread
 
dan_le_brown profile image
Brown

Thank you for your kind words! It's something that has confused me in the past, so it feels great to be able to articulate the difference to another person

Collapse
 
markuszeller profile image
Markus Zeller

I get your point and totally agree for modern systems and simplified explanation.

Here's my view: Technically speaking, I think it depends on the system. As long as each worker runs on its own CPU at the same time, it is real parallelism. If you have only one CPU, there is no parallelism, but you can achieve it looking the same with concurrency. Note, that even multi-threading may still be concurrency, the OS handles it for us.

Thread Thread
 
dan_le_brown profile image
Brown

Ah, thank you for elaborating. I like your point about how the deciding factor is the no of CPUs. It's intuitive and easier to understand

Collapse
 
eshimischi profile image
eshimischi

ReactPHP reactphp.org/

Collapse
 
mohmd_naeem_k profile image
Mohammed Naeem

Actually you can do this in native php with pheanstalk (php library for beanstalkd queue management) ... Just run the php watcher script using supervisor.

Collapse
 
jaskaran_singh_4d13d7c4e1 profile image
Jaskaran Singh

Good

Collapse
 
dilsha_test_b7f4fbd18c650 profile image
dilsha Test

Perfect 🔥

Some comments may only be visible to logged-in visitors. Sign in to view all comments.