DevPath
Mid lesson · 12 min

Dispatch work after a transaction commits

Prevent workers from reading data that has not committed.

Recognize the race

A controller creates a record inside a transaction and dispatches a job immediately. A fast worker may start before commit and fail to find the record. If the transaction rolls back, the job may still represent work that never existed. This is a timing problem that local synchronous queues can hide.

Choose commit-aware dispatch

Laravel can defer dispatch until the open transaction commits through a connection setting or an afterCommit call. Use it when the job depends on newly written rows. Keep the job idempotent, because after-commit dispatch does not make queue delivery exactly once.

DB::transaction(function () use ($order) {
    $order->save();
    SendReceipt::dispatch($order->id)->afterCommit();
});

Test both timelines

Assert that a rollback does not enqueue the dependent job, and a commit does. Then test a worker retry after the receipt was already sent. For critical cross-system delivery, consider an outbox as well: a successful commit followed by a process crash can still interrupt dispatch before the message reaches the queue.

Check your understanding

What problem does afterCommit solve, and what problem remains?

Show explanation

It stops a job from running for uncommitted or rolled-back data. It does not eliminate duplicate delivery or every crash gap.

You can read for free. Create an account to save your progress.

← Previous lesson: Make failures diagnosable

Put this lesson into practice

A practice activity at this level in the same module.

Try: Deduplicate a payment webhook

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.