Skip to content
Laravel & PHP•12 min read•Published

Laravel Race Condition Fix: Stop Double-Accepted Jobs

Two drivers tap Accept on the same delivery and both get a success screen. Here is how check-then-update causes it in Laravel, and four ways to fix it, from a conditional UPDATE to lockForUpdate.

Aqib Javaid
Aqib Javaid
Senior Full-Stack Engineer
Glass padlock on a delivery card with Driver A accepted (200) and Driver B rejected (409), Laravel and MySQL labels

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:

php
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:

TimeDriver A's requestDriver B's request
t0reads delivery, status = pending
t1reads delivery, status = pending
t2passes the check, writes driver_id = A
t3passes 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.

ApproachHow it worksStrengthCost
Conditional UPDATE (compare-and-set)One statement: UPDATE ... WHERE status = 'pending', check affected rowsSimplest, no explicit locks, fastOnly guards one row's state
Pessimistic lock (lockForUpdate)Lock the row inside a transaction, then run any checksLets you validate several things before writingHolds a row lock; needs a transaction; can deadlock if misused
Atomic cache lock (Cache::lock)Redis-backed lock keyed by delivery idWorks across tables and servicesA second system to fail; lock can expire mid-work
Optimistic version columnWrite only if version matches what you readNo locks heldCallers 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:

php
$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.

Advertisement

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:

php
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:

php
$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.

php
// 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:

  • The check and the write are one statement, or one transaction holding a lock
  • Losing the race returns a clear 409 the mobile app can show
  • Every path that assigns a driver goes through the same method
  • Locks are always taken in the same order
  • No network calls inside a transaction
  • 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:

bash
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 409 from 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's WHERE clause and check the affected-row count.
  • Use lockForUpdate inside 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.

Share this technical insight with your network

Share to LinkedIn or Facebook with key takeaways, featured media, and direct links.

Aqib Javaid

About the author

Aqib Javaid

Senior Full-Stack Engineer

8+ years building Laravel, React/Next.js and AI-powered products for startups and growing businesses - SaaS platforms, APIs, integrations and the performance work that keeps them fast. Read the case studies to see how that plays out on real projects.

4.9 from 76 client reviews

📁 Production Case Study

Case Study: ION DASH - Logistics & Fleet Management Platform

ION DASH was transformed from a legacy delivery application into a modern logistics and fleet management platform combining Flutter Customer and Driver applications with a Laravel backend API. The platform handles custom quotes, automated dispatch, background GPS tracking, delivery confirmation, proof of delivery, Stripe PaymentIntents, Firebase Cloud Messaging, Google Maps navigation, onsite billing, and catalog synchronization.

Related Technical Articles

View all articles →
✦ Let's Build Together

Have a complex technical project in mind?

Available for full-stack engineering, performance audits, cloud deployments, and high-concurrency systems architecture.