#laravel#php#concurrency#backend

Laravel 11 Concurrency & Context: Parallel Execution and Log Tracing

"Deep dive into Laravel 11 Concurrency and Context features for lightweight parallel processing and request log tracing."

By huud
0 views
~2 min read
Laravel 11 Concurrency & Context: Parallel Execution and Log Tracing

Laravel 11 Concurrency & Context: Parallel Execution and Log Tracing

Laravel 11 introduces two core primitives: Concurrency for running asynchronous tasks in parallel and Context for unified request state tracking and log observability.


1. Concurrency: Parallel Task Execution

Previously, running parallel I/O-bound tasks required setting up queue workers or third-party packages like spatie/async. Laravel 11 natively supports this via the Concurrency facade.

Example: Concurrent Third-Party API Requests

php
use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\Http;

[$weather, $crypto, $news] = Concurrency::run([
    fn () => Http::get('https://api.weather.test/current')->json(),
    fn () => Http::get('https://api.crypto.test/prices')->json(),
    fn () => Http::get('https://api.news.test/headlines')->json(),
]);

Concurrency Drivers

  • fork: Uses pcntl_fork (CLI/Linux only).
  • process: Spawns isolated CLI subprocesses via php artisan (compatible across web and CLI runtimes).

Configure the driver in config/concurrency.php:

php
'default' => env('CONCURRENCY_DRIVER', 'process'),

2. Context: Observability & Log Tracing

HTTP requests pass through multiple layers: Middleware, Controllers, Services, Queued Jobs, and Event Listeners. The Context facade stores metadata that is automatically appended to every subsequent log entry.

Middleware Setup:

php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;

class TraceContextMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        Context::add([
            'trace_id' => (string) Str::uuid(),
            'user_id' => $request->user()?->id,
            'ip' => $request->ip(),
        ]);

        return $next($request);
    }
}

Automatic Log Correlation:

php
Log::info('Order checkout initiated');
// JSON log output automatically includes { "message": "Order checkout initiated", "context": { "trace_id": "...", "user_id": 1, ... } }

Context Propagation to Queues

When a job is dispatched within a request cycle, the current Context data is automatically serialized and passed to the background queue worker without manual parameter plumbing.


Summary

  1. Concurrency::run() slashes I/O latency by executing closures in parallel.
  2. Context::add() unifies request trace IDs across HTTP lifecycles and background queue jobs.

About the Author

huud

huud

@huud

About →

Systems architect and software engineer building high-performance distributed platforms.