Not every slow request needs a queue job. Laravel ships two lightweight tools for the in-between cases: the Concurrency facade, which runs independent closures in parallel and returns their results, and the defer() helper, which runs a closure after the HTTP response has been sent. This tutorial shows how to use both, how to test them, and where they stop being safe.
The problem: sequential work that does not need to be sequential
A dashboard endpoint often looks like this:
public function __invoke()
{
return view('dashboard', [
'revenue' => $this->reports->monthlyRevenue(), // 400ms
'signups' => $this->reports->newSignups(), // 350ms
'churn' => $this->reports->churnRate(), // 500ms
]);
}
The three queries are independent, yet the user waits for about 1.25 seconds because they run one after another.
Running work in parallel with Concurrency
use Illuminate\Support\Facades\Concurrency;
[$revenue, $signups, $churn] = Concurrency::run([
fn () => app(ReportService::class)->monthlyRevenue(),
fn () => app(ReportService::class)->newSignups(),
fn () => app(ReportService::class)->churnRate(),
]);
Concurrency::run() executes each closure in a separate PHP process and returns the results in the same order. Total time drops towards the slowest single query rather than the sum.
Drivers
The default driver is process. Others you can select in config/concurrency.php:
process: spawns child processes through Artisan. Works in web and CLI contexts.fork: faster because it forks the current process, but it needs thespatie/forkpackage and only works in the CLI, so it suits Artisan commands, not web requests.sync: runs closures one at a time in the current process. Useful in tests and for debugging.
Rules for closures
- Closures are serialized and run in a fresh process, so you cannot rely on request state, the authenticated user, or variables you did not pass in. Pass IDs or plain values with
use, and resolve services inside the closure. - Return only serializable values. Return arrays or scalars rather than open resources or large Eloquent graphs.
- Each child process opens its own database connection, so watch your connection limit. Parallelism of three or four is sensible; fifty is not.
- Exceptions thrown in a closure are rethrown in the parent, so a failing branch fails the request. Catch inside the closure if a partial result is acceptable.
$tenantId = $request->user()->tenant_id;
[$revenue, $signups] = Concurrency::run([
fn () => Report::forTenant($tenantId)->monthlyRevenue(),
fn () => Report::forTenant($tenantId)->newSignups(),
]);
Running work after the response with defer()
Some work should not delay the user, but is too small or too best-effort to justify a queued job: touching a last_seen_at column, recording an analytics hit, warming a cache key.
use function Illuminate\Support\defer;
public function show(Article $article)
{
defer(fn () => $article->increment('views'));
return view('articles.show', compact('article'));
}
The closure runs after the response is sent to the browser. By default deferred functions run only if the response was successful (not a 4xx or 5xx). Chain ->always() if it must run regardless:
defer(fn () => AuditLog::record($request->path()))->always();
You can also name a deferred function and cancel it before it runs, which prevents duplicates:
defer(fn () => Metrics::flush(), 'flush-metrics');
// later in the same request
defer()->forget('flush-metrics');
Outside a web request (in Artisan commands and queue jobs) deferred closures run when the command or job finishes.
Defer versus queues: how to choose
| Need | Use |
|---|---|
| The result is needed to build this response, and the parts are independent | Concurrency::run() |
| Small, cheap, best-effort follow-up work | defer() |
| Must not be lost, needs retries, backoff, or rate limiting | A queued job |
| Long-running (more than a few seconds) or heavy memory use | A queued job |
| Needs visibility in Horizon or failed-job handling | A queued job |
Deferred work lives and dies with the PHP worker. If the process crashes or is restarted during a deploy, the work is gone, and there is no retry. Anything involving money, email delivery guarantees, or webhooks belongs on a queue.
Testing
In tests, deferred functions execute immediately in the test process, which keeps assertions simple. If you want to assert that nothing runs inline, disable deferral:
it('counts a view', function () {
$article = Article::factory()->create(['views' => 0]);
$this->get(route('articles.show', $article))->assertOk();
expect($article->fresh()->views)->toBe(1);
});
For Concurrency, set CONCURRENCY_DRIVER=sync in phpunit.xml or .env.testing so tests do not spawn processes and database transactions from RefreshDatabase remain visible. A child process would use a separate connection and would not see uncommitted test data.
Measuring the win
Do not guess. Wrap the endpoint with a timer or use Pulse or Telescope to compare before and after. Parallelism helps most when branches are I/O-bound, such as slow queries, HTTP calls to third-party APIs, or report aggregation. It helps little if every branch hits the same locked table or if process start-up costs more than the work itself, which is typically around tens of milliseconds per process.
Checklist
- Identify independent, slow branches in a request and group them in
Concurrency::run(). - Pass plain values into closures and return plain values out.
- Move trivial post-response work to
defer(); use->always()deliberately. - Keep anything that must be reliable on a queue.
- Use the
syncdriver in tests and measure in production.
If a Laravel app of yours is slow and you are not sure whether the answer is concurrency, caching, query fixes, or queues, our performance optimization team can profile it and recommend the cheapest fix. Get in touch.