afterCommit() on Laravel Jobs: The Race Condition Is in the Design
Laravel's afterCommit() on queued jobs solves a real problem, but if you don't know why it exists, you'll eventually ship a subtle bug that's miserable to debug.
If you've ever had a queued job silently fail because it ran before the database transaction that created its data had committed, you already know why afterCommit() exists. If you haven't hit this yet, you will - and when you do, the logs won't help you because nothing technically went wrong.
The Problem
Here's the scenario. You have a controller action that wraps a few database writes in a transaction and then dispatches a job:
DB::transaction(function () use ($order) {
$order->save();
$order->items()->saveMany($this->items);
ProcessOrder::dispatch($order->id);
});
Looks fine. The job is dispatched after the saves. But here's what actually happens at the infrastructure level: Laravel pushes the job onto the queue (Redis, SQS, database, whatever) the moment dispatch() is called, inside the transaction. The queue worker on the other end picks it up and starts executing - potentially before your transaction commits.
When ProcessOrder runs and does Order::find($orderId), it either gets nothing or gets a stale partial record, because the write hasn't landed yet. The job fails, retries, maybe succeeds on the second attempt a few seconds later when everything is committed, and you never notice. Or it fails all three attempts at startup on a lightly loaded system where the commit takes 50ms longer than usual, and now you have a dead-letter queue entry and a confused client.
This isn't a code bug. The code is correct. It's a timing assumption baked into the design.
What afterCommit() Does
Laravel added afterCommit() specifically to fix this. When you configure a job to use it, Laravel won't actually push the job to the queue until the surrounding transaction commits. If the transaction rolls back, the job is never dispatched. That's exactly the behavior you want.
There are two ways to use it.
Option 1: Per-job in the constructor
class ProcessOrder implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(public int $orderId)
{
$this->afterCommit();
}
public function handle(): void
{
$order = Order::findOrFail($this->orderId);
// now this is safe - the record is guaranteed to exist
}
}
Option 2: Global default in config/queue.php
'connections' => [
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
'after_commit' => true, // <-- here
],
],
The global option is tempting because you don't have to remember to add it per job. I'll come back to why I don't use it globally.
A Real Scenario
Last year I built a lab results pipeline for a Seattle biotech. When a new sample result came in through their LIMS integration, we'd write the result record and immediately dispatch a job to notify the assigned researcher and update some downstream reporting tables.
The first version looked exactly like the bad example above. It worked fine in development. It worked fine in staging. It went sideways in production about two weeks after launch, under higher load, when the queue worker was running hot and picking up jobs in under 100ms. The notification job would grab the result record, find it missing, and fail. By the first retry the transaction had committed and everything was fine - but we'd already burned a retry and introduced a 30-second delay in notifications that nobody could explain.
Switching to afterCommit() on that job fixed it immediately and permanently.
class NotifyResearcherOfResult implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $tries = 3;
public $backoff = 10;
public function __construct(public int $resultId)
{
$this->afterCommit();
}
public function handle(ResearcherNotifier $notifier): void
{
$result = LabResult::with('sample', 'researcher')->findOrFail($this->resultId);
$notifier->send($result);
}
}
Simple. The job doesn't dispatch until the transaction closes cleanly. If the transaction rolls back because of a LIMS parsing error, the researcher never gets a phantom notification for a result that doesn't exist.
The Gotchas That Will Bite You
Dispatching outside a transaction
If you call dispatch() outside of any transaction, afterCommit() is a no-op - the job goes to the queue immediately as normal. That's the right behavior, but it means you can't rely on afterCommit() as a general "always wait" guarantee. It only defers if there's an active transaction to defer to.
Nested transactions and savepoints
Laravel supports nested transactions via savepoints. With afterCommit(), the job waits for the outermost transaction to commit, not just the savepoint. This is almost always what you want, but it can be surprising if you have deeply nested transaction logic and expect the job to fire when the inner block closes.
The global after_commit setting and jobs that should fire on rollback
This is why I don't flip the global after_commit to true and forget about it. Some jobs should fire even if the transaction rolls back - audit log entries, failure notifications, cleanup tasks. If everything is globally deferred to commit, those jobs silently disappear when a transaction fails. I'd rather be explicit per job and always know what I'm getting.
Model serialization inside transactions
When you pass an Eloquent model directly to a job constructor and let SerializesModels handle it, the model gets serialized to just its ID and re-fetched on the worker. With afterCommit() that's fine. Without it, you can hit the same race condition even though you're passing the model, not just the ID, because the worker's findOrFail happens after deserialize. Passing the ID explicitly and calling findOrFail in handle() makes the data flow more obvious.
Testing
In tests that use RefreshDatabase, you're already inside a transaction that never commits. If you're using Queue::fake() and asserting that jobs were dispatched, afterCommit() can cause jobs to never actually get faked-pushed because the wrapping test transaction never commits. The fix is to either not use transactions in those specific tests, or temporarily disable afterCommit behavior in tests. Laravel has WithoutDefer and similar test helpers depending on your version.
When I'd Reach for This
Every job that reads data it expects to have been written by the transaction that dispatched it. That's the whole decision. If your job is doing work that's independent of the dispatching transaction - sending a Slack message with static content, pinging an external webhook with no DB reads, whatever - afterCommit() doesn't hurt but it's not necessary either.
I make it a code review checklist item now. If I see dispatch() inside DB::transaction(), I look at the job and ask: does this job read anything written by this transaction? If yes and there's no afterCommit(), that's a flag.
The jobs I always add it to:
- Anything that re-fetches the model by ID
- Any job that queries related records (eager loads, pivot tables, child records) that were created in the same transaction
- Notification jobs where "fired for a thing that doesn't exist" would be a user-facing bug
- Reporting or aggregation jobs that build summaries from newly written data
The jobs I leave alone:
- Pure external API calls with all data passed through the constructor (no DB reads in handle)
- Scheduled maintenance jobs that have nothing to do with any particular transaction
- Audit / event log jobs that should fire regardless of commit/rollback
When I Wouldn't Rely on This
If your job genuinely cannot afford to have a race condition at all - meaning even a brief window between commit and queue pickup is unacceptable - afterCommit() doesn't fully solve that. It eliminates the transaction race, but there's still a gap between commit and the moment the worker picks up the job. For truly critical synchronous work, you're in synchronous territory anyway. afterCommit() is a correctness fix for async jobs, not a synchrony guarantee.
Also: if you're running a database queue driver and your queue table is in the same database as your app, you get some of this for free because the queue write is part of the same transaction. But you're still at the mercy of table-level visibility depending on your isolation level, and I wouldn't lean on that subtlety when afterCommit() is explicit and obvious.
Closing
The race condition between transactions and job dispatch is one of those bugs that looks like a flaky test or an overloaded server until you understand what's actually happening. afterCommit() is a one-liner fix for a class of bugs that can take hours to diagnose. Add it to any job that depends on data written by the transaction that dispatched it - no exceptions.
Need help shipping something like this? Get in touch.