Two drivers tap Accept on the same delivery within the same second. Both phones show a green "Job accepted" screen. Both drivers start driving. One of them arrives to find the job already gone, or worse, the customer has two vehicles outside. This is the classic Laravel race condition, and if you run any dispatch, booking or claim-the-job workflow, you will meet it the first week you have real traffic.
I hit exactly this shape of problem while rebuilding the dispatch layer on ION DASH, a logistics and fleet platform (Flutter apps for customers and drivers on a Laravel API). The rule the client wanted was simple: the first driver who successfully accepts a delivery secures it, and nobody else can. Making that rule true under concurrency took more care than the feature name suggests. This article is the version of that fix I would hand to another Laravel developer: why the obvious code fails, four ways to fix it, which one I reach for first, and how to prove it works.
The bug report that starts it
The symptom is never "race condition". It is a support message: "Two drivers say they got the same order." Nothing in your logs is red, because each request succeeded.
Here is the code that produces it. It reads like correct code, and in a single-user test it is correct:
public function accept(Request $request, Delivery $delivery)
{
$driver = $request->user();
if ($delivery->status !== 'pending') {
return response()->json(['message' => 'Already taken'], 409);
}
$delivery->update([
'status' => 'assigned',
'driver_id' => $driver->id,
]);
return response()->json($delivery->fresh());
}
The bug is the gap between the if and the update. This is a check-then-act sequence, and the database can serve two requests inside that gap:
| Time | Driver A's request | Driver B's request |
|---|---|---|
| t0 | reads delivery, status = pending
|
|
| t1 | reads delivery, status = pending
|
|
| t2 | passes the check, writes driver_id = A
|
|
| t3 | passes its (stale) check, writes driver_id = B
|
B's write silently overwrites A's. Both got a 200. The window between t0 and t3 is only milliseconds wide, but a busy dispatch queue, a push notification that wakes many phones at once, and flaky mobile networks that retry requests all push traffic into that window. On a mobile-backed product it happens far more often than you expect, because every driver receives the same "new job" push at the same moment.
Important
You cannot fix this in PHP with an
if. PHP processes (FPM workers, queue workers, Octane workers) don't share memory. Only the database, or a shared lock service, can decide who wins.
Four ways to fix it, and what each costs
There are four patterns I consider. They are not equal, and the right one depends on how much state the decision touches.
| Approach | How it works | Strength | Cost |
|---|---|---|---|
Conditional UPDATE (compare-and-set) |
One statement: UPDATE ... WHERE status = 'pending', check affected rows |
Simplest, no explicit locks, fast | Only guards one row's state |
Pessimistic lock (lockForUpdate) |
Lock the row inside a transaction, then run any checks | Lets you validate several things before writing | Holds a row lock; needs a transaction; can deadlock if misused |
Atomic cache lock (Cache::lock) |
Redis-backed lock keyed by delivery id | Works across tables and services | A second system to fail; lock can expire mid-work |
| Optimistic version column | Write only if version matches what you read |
No locks held | Callers must retry; more code |
I'll go through them in the order I would try them.
1. Conditional update: my default
The cleanest fix removes the gap entirely. Don't read, then write. Write with the condition inside the same statement and let the database tell you whether you won:
$won = Delivery::query()
->whereKey($delivery->id)
->where('status', 'pending')
->whereNull('driver_id')
->update([
'status' => 'assigned',
'driver_id' => $driver->id,
'assigned_at' => now(),
]);
if ($won === 0) {
return response()->json(['message' => 'Already taken'], 409);
}
update() returns the number of rows changed. InnoDB takes a row lock while it evaluates and applies that single statement, so when two requests collide, one updates the row and the second sees status = 'assigned' in its WHERE, matches zero rows and returns 0. The decision and the write are one atomic step. In the ION DASH flow, this is the shape of "first driver to accept secures the job": the loser gets a clean 409 and the app shows "this job was just taken", instead of a false success.
Use this whenever the winning condition is a property of one row. It is also the pattern I'd suggest for the claim step of any job board, booking slot or inventory reservation.
2. Pessimistic locking: when you must check more than one thing
Dispatch is rarely just "is the row pending". In our case the backend also enforces a driver capacity limit (a driver cannot hold more assignments than their configured maximum) and online/offline eligibility. Those rules live on other rows, so a single-row conditional update is not enough.
That is where lockForUpdate earns its place. Lock the rows you are about to reason about, inside a transaction, in a fixed order:
return DB::transaction(function () use ($deliveryId, $driverId) {
// Lock the driver first, then the delivery. Always in this order.
$driver = Driver::whereKey($driverId)->lockForUpdate()->firstOrFail();
if (! $driver->is_online) {
return ['ok' => false, 'reason' => 'offline'];
}
$active = Delivery::where('driver_id', $driver->id)
->whereIn('status', ['assigned', 'picked_up'])
->count();
if ($active >= $driver->max_active_jobs) {
return ['ok' => false, 'reason' => 'at_capacity'];
}
$delivery = Delivery::whereKey($deliveryId)->lockForUpdate()->firstOrFail();
if ($delivery->status !== 'pending') {
return ['ok' => false, 'reason' => 'taken'];
}
$delivery->update(['status' => 'assigned', 'driver_id' => $driver->id]);
return ['ok' => true];
});
Locking the driver row is the detail people miss. If you lock only the delivery, the same driver can accept two different jobs at the same moment, both pass the capacity count, and now they are one over their limit. Locking the driver serialises that driver's own accepts.
Two rules keep this safe:
-
Always lock in the same order (driver, then delivery). Two transactions taking the same locks in opposite orders is how you get deadlocks. Laravel retries the closure for you if you pass a second argument:
DB::transaction($callback, 3). -
Keep the transaction short. No HTTP calls, no push notifications and no file uploads inside it. Send the Firebase push after the commit, for example with
DB::afterCommit()or a queued job dispatched->afterCommit().
MySQL's own documentation on locking reads is worth ten minutes, particularly the parts on which rows get locked when your WHERE clause doesn't hit an index. An unindexed lock query can lock far more rows than you intended.
3. Atomic cache locks: for work that spans systems
Cache::lock() gives you a Redis-backed mutex:
$lock = Cache::lock("delivery-accept:{$delivery->id}", 10);
if (! $lock->get()) {
return response()->json(['message' => 'Busy, try again'], 409);
}
try {
// ... decide and write ...
} finally {
$lock->release();
}
I use this when the thing being protected is not a single database row: a call to an external carrier API, a document being generated, a report being rebuilt. For dispatch I avoid it as the primary guard, for a reason that matters: the lock and the data live in different systems. If the lock expires after 10 seconds while a slow request is still working, a second request walks in. The database lock cannot expire out from under the transaction that holds it. Treat a cache lock as a traffic cop in front of the real guard, not the guard itself.
4. Optimistic versioning: for edit conflicts, not races to claim
Add a version integer, read it, and write with WHERE version = :seen, incrementing on success. It's the right tool when many people might edit the same record over minutes (an admin editing a quote, say) and you would rather show a "someone else changed this" message than block anyone. For a first-come-first-served claim, the conditional update does the same job with less code.
Auto-assignment makes the race worse
Accept-by-tap is one writer. The other writer is your own scheduler. On ION DASH, an order that stays in the queue for 15 minutes is automatically assigned to an available driver. That means a driver tapping Accept and the scheduled auto-assign command can target the same delivery at the same instant.
The fix is the same principle applied to both paths: they must go through one method that performs the guarded write, rather than each carrying its own copy of the rules. When I see two code paths that both set driver_id, I treat that as a bug waiting to happen.
// One door in. The controller and the scheduled command both call this.
class ClaimDelivery
{
public function __invoke(int $deliveryId, int $driverId): bool
{
// conditional update + capacity checks live here, nowhere else
}
}
Also stop the scheduler overlapping itself. If the command takes longer than its interval, two copies run at once, which is another source of double assignment. Laravel's withoutOverlapping() uses an atomic lock for exactly this, and onOneServer() covers multi-server deployments.
Test it with real concurrency
A feature test that calls the endpoint twice in a row will pass against the broken code, because the second call runs after the first has finished. To expose a race you need two database connections acting at the same time.
My checklist when I review claim logic:
- [x] The check and the write are one statement, or one transaction holding a lock
- [x] Losing the race returns a clear 409 the mobile app can show
- [x] Every path that assigns a driver goes through the same method
- [x] Locks are always taken in the same order
- [x] No network calls inside a transaction
- [x] A concurrency test fires 20 or more simultaneous accepts at one delivery and asserts exactly one winner
For that last item, a small script is enough. Run it against a real MySQL database, not SQLite, because SQLite serialises all writes and hides the problem:
echo "20 parallel accepts" >&2
seq 1 20 | xargs -P 20 -I{} curl -s -o /dev/null -w "%{http_code}\n" \
-X POST https://staging.example.test/api/deliveries/42/accept \
-H "Authorization: Bearer $(cat tokens/driver-{}.txt)"
You expect exactly one 200 and nineteen 409 responses. Against the check-then-update version, you can see more than one 200, and an assigned row whose driver_id is whichever request wrote last.
When not to over-engineer this
Not every status change needs a lock. I skip all of this when:
- There is only ever one writer. A background job that owns a record doesn't need to protect it from itself.
- The operation is naturally idempotent. Marking an already-delivered order as delivered again is harmless. (Retries of payments are different, and need idempotency keys.)
-
Traffic is tiny. An internal tool with three users can live with a
409from a unique constraint.
A database unique index is also worth knowing as a backstop. If a business rule says "one active assignment per delivery", enforce it with a unique key on a nullable active_driver_slot or a similar column, so that even a bug in your application code cannot create a double assignment. The code is your first defence and the schema is your last.
What I'd do again, and what I'd change
What worked on ION DASH: one claim method, conditional update first, row locks only where the capacity rules needed them, and pushes sent after commit. Losing drivers get an immediate, explicit "already taken" response instead of a ghost job.
What I'd watch for next time: lock-wait timeouts under heavy load. If many drivers fight for the same hot row, MySQL's SKIP LOCKED (available in 8.0+) lets workers skip rows that are already locked, which suits a queue where any available job will do. It doesn't suit a case where drivers want one specific job, but it is the right tool for pulling "the next available" item. Queue workers raise the same class of problem, and I covered the design side in the Laravel queue architecture guide.
Frequently asked questions
Is lockForUpdate enough to prevent double booking in Laravel?
Only inside a database transaction. Outside one, the lock is released the moment the statement ends. Wrap the read and the write together in DB::transaction(), and lock every row whose state your decision depends on.
Should I use Redis locks or database locks for first-come-first-served claims?
Prefer the database when the thing being claimed is a row. The lock lives with the data and can't expire mid-decision. Use Redis locks to protect work that spans several systems.
Why does my concurrency test pass on my machine but fail in production?
Local tests often run on SQLite or run requests one at a time. Test against MySQL or PostgreSQL with real parallel connections.
Does this apply to mobile app backends specifically?
It applies to any API, but mobile backends hit it sooner. A single push notification can wake hundreds of devices at once, and flaky networks make clients retry requests.
Key takeaways
- Read-then-write is a race. Move the condition into the
UPDATE'sWHEREclause and check the affected-row count. - Use
lockForUpdateinside a short transaction when the decision involves more than one row, and lock in a consistent order. - Put one claim method behind every code path, including scheduled auto-assignment.
- Redis locks are a traffic cop, not the source of truth. A unique index is your last line of defence.
- Prove it with 20 parallel requests against MySQL, expecting exactly one winner.
If you are building dispatch, booking or marketplace logic and want it reviewed by someone who has shipped it, book a call and we can look at your claim flow together.
Originally published at aqibjavaid.site.
Top comments (3)
Small catch in the 20-accepts script: the
$(cat tokens/driver-{}.txt)runs once in your shell before xargs starts, so{}is never replaced. I ran it against a local endpoint and got "No such file" plus twenty 401s, all sent asBearerwith no token.Wrapping it in
sh -cmakes each request read its own file:The conditional update is the right default, but it has one sharp edge with exactly the flaky mobile networks you mention. Driver A taps Accept, the update wins, the response gets lost on the way back, and the app retries. Now the retry matches zero rows and A gets a 409 "Already taken" for a job that is actually theirs.
Cheap fix: when
$won === 0, re-read the row and return 200 ifdriver_idis already the current driver. Accept becomes idempotent per driver, and the 409 only goes to people who really lost.This is the clearest version of this problem I've seen written up for Laravel, and the "one door in" point is the one I'd underline. In a travel booking flow I work on, the same shape shows up when two users try to claim the same seat at once — both requests return 200, and the overwrite only surfaces later as a support ticket.
One thing I'd add from that side: the conditional UPDATE plus a unique index backstop pair well together, but the backstop only helps if the loser gets a clean 409 rather than a 500 from the constraint violation, so it's worth catching that exception explicitly and returning "already claimed" instead of a generic error.
On your lock-wait timeout watch-out: have you found a practical ceiling for how many contenders you let queue on lockForUpdate before switching to SKIP LOCKED, or do you reach for SKIP LOCKED as soon as the claim is first-come-first-served?