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."
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
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: Usespcntl_fork(CLI/Linux only).process: Spawns isolated CLI subprocesses viaphp artisan(compatible across web and CLI runtimes).
Configure the driver in config/concurrency.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:
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:
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
Concurrency::run()slashes I/O latency by executing closures in parallel.Context::add()unifies request trace IDs across HTTP lifecycles and background queue jobs.
About the Author
huud
@huud
Systems architect and software engineer building high-performance distributed platforms.