Getting Started with Laravel Concurrency: A Beginner's Guide

Author

Kritim Yantra

Mar 01, 2025

Getting Started with Laravel Concurrency: A Beginner's Guide

In modern web applications, running tasks one after the other can sometimes slow things down—especially if those tasks are independent of one another. Laravel’s new Concurrency facade makes it easier to run multiple tasks at the same time, giving your application a performance boost without a lot of extra hassle.

What Is Laravel Concurrency?

Laravel Concurrency is a new feature (currently in beta) that allows you to execute several slow or independent tasks concurrently. Instead of waiting for one task to finish before starting the next, you can run them simultaneously. This can be especially useful when you need to run multiple database queries, API calls, or other time-consuming operations.

Why Use Concurrency?

  • Performance Improvements: By running tasks at the same time, you reduce overall wait times.
  • Simplicity: Laravel provides an easy-to-use API to execute closures concurrently.
  • Flexibility: You can run tasks immediately or defer them to run after the HTTP response is sent.

How Does It Work?

Laravel handles concurrency by doing a couple of clever things behind the scenes:

  • Serialization: The closures (or anonymous functions) you pass to the Concurrency facade are serialized.
  • Dispatching: Laravel dispatches these closures to a hidden Artisan CLI command.
  • Separate Process: Each closure is executed in its own PHP process.
  • Result Handling: Once a task is complete, its result is serialized back to the main process.

This means that even if you’re running multiple tasks at the same time, they don’t block one another.

Concurrency Compatibility

If you’re upgrading from Laravel 10.x to Laravel 11.x or 12.x, you may need to add the ConcurrencyServiceProvider to your configuration. Open your config/app.php file and add the following line to the providers array:

'providers' => ServiceProvider::defaultProviders()->merge([
    /*
     * Package Service Providers...
     */
    Illuminate\Concurrency\ConcurrencyServiceProvider::class,

    /*
     * Application Service Providers...
     */
    App\Providers\AppServiceProvider::class,
    App\Providers\AuthServiceProvider::class,
    // App\Providers\BroadcastServiceProvider::class,
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,
])->toArray(),

The Three Concurrency Drivers

Laravel’s Concurrency facade supports three different drivers:

  1. Process (Default):
    • Each task is executed in its own PHP process.
    • Works out-of-the-box.
  2. Fork:
    • Offers better performance by forking the process.
    • Only works in PHP’s CLI context (not for web requests).
    • To use this driver, install the package with:
      composer require spatie/fork
  3. Sync:
    • Executes tasks sequentially in the parent process.
    • Useful for testing when you want to disable concurrent execution.

Running Concurrent Tasks

To run tasks concurrently, use the run method provided by the Concurrency facade. For example, if you want to count the number of users and orders simultaneously, you can write:

use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\DB;

[$userCount, $orderCount] = Concurrency::run([
    fn () => DB::table('users')->count(),
    fn () => DB::table('orders')->count(),
]);

If you want to choose a specific driver, simply chain the driver method:

$results = Concurrency::driver('fork')->run([
    fn () => DB::table('users')->count(),
    fn () => DB::table('orders')->count(),
]);

Deferring Concurrent Tasks

Sometimes, you might have tasks that don’t need to block your user’s request. For example, if you want to log metrics or send emails after the user receives a response, you can “defer” these tasks. With the defer method, Laravel will run your tasks in the background once the HTTP response is sent:

use App\Services\Metrics;
use Illuminate\Support\Facades\Concurrency;

Concurrency::defer([
    fn () => Metrics::report('users'),
    fn () => Metrics::report('orders'),
]);

This allows your application to respond quickly to user requests while still performing important background tasks.

When Should You Use Laravel Concurrency?

  • Independent Tasks: When tasks don’t depend on each other, such as separate database queries or API calls.
  • Performance Boosts: In scenarios where waiting for one task to complete before starting the next is inefficient.
  • Post-Response Processing: For tasks like logging or sending notifications that can be deferred until after the response is sent.

Considerations and Best Practices

  • Resource Usage: Each concurrent task boots a new process, which could mean extra database connections and increased memory usage.
  • Error Handling: If one of the tasks fails, you might need to handle the error appropriately to avoid breaking your entire process.
  • Testing: Use the sync driver during testing to ensure predictable behavior.

Conclusion

Laravel’s Concurrency facade is a powerful new tool that can help you make your applications faster by running independent tasks at the same time. Whether you’re counting database records, making multiple API calls, or deferring non-critical tasks, concurrency can make your application more efficient without adding a lot of extra complexity.

Since this feature is still in beta, experimenting with it on non-critical parts of your application is a great way to get comfortable with concurrent programming in Laravel. As you gain more experience, you’ll be able to harness the full power of concurrency to build more responsive and robust applications.

Happy coding!

Tags

Laravel Vue

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Continue with Google

Related Posts

Understanding SOLID Design Principles in Laravel (For Beginners)
Kritim Yantra Kritim Yantra
Feb 24, 2025
Laravel 12 & AdminLTE Integration: Setup Your Stunning Admin Dashboard
Kritim Yantra Kritim Yantra
Feb 28, 2025