Quick answer: A race condition in a Laravel app almost always looks like read, then decide, then write, with nothing stopping a second request from reading the same old value in between. Find them by searching for check-then-act code around money, stock and status fields, prove them with parallel requests, and fix them with a database transaction plus lockForUpdate(), an atomic update, or a unique constraint.
I'm Muhammad Ali Mughal, a Principal Software Engineer in Karachi, and I build Laravel and custom web apps at Loop Origin. One of the most-read #laravel posts on DEV this week was titled "The race condition that prints free money, and how I stopped it in my Laravel payment gateway", and another popular #webdev post warned against unbounded Promise.all fan-out crashing APIs. Both are the same lesson: code that is correct for one request at a time can be wrong for two at once.
This post starts a new series on race conditions in production Laravel apps. I wrote it with help from AI tools and checked the code against the Laravel 11/12 documentation and MySQL 8 / PostgreSQL locking behaviour.
📚 Series Navigation — Race Conditions in Production Laravel
- Part 1 (This Post): Double Charges and Double Submits: Finding Race Conditions in Laravel
- Part 2: lockForUpdate, Cache::lock or a Unique Index? Picking the Right Guard (coming next)
- Part 3: Lost Updates: Optimistic Locking With Version Columns
- Part 4: Bounded Concurrency: Stop Unbounded Fan-Out in PHP and Node
- Part 5: Stock, Seats and Quotas Without Overselling
- Part 6: Reproducing Races in Tests Before Your Users Do
Related earlier posts: Idempotent Jobs & Exactly-Once Effects: Designing Safe Retries · Multi-Tier Caching & Stampede Protection · Zero-Downtime Database Migrations in Laravel & Node.js SaaS
The shape of almost every race
Here is a wallet withdrawal I found in a client codebase. It passed every test.
public function withdraw(Request $request, Wallet $wallet)
{
$amount = (int) $request->input('amount');
if ($wallet->balance < $amount) { // 1. read + decide
abort(422, 'Insufficient balance');
}
$wallet->balance = $wallet->balance - $amount; // 2. compute from stale value
$wallet->save(); // 3. write
Payout::create(['wallet_id' => $wallet->id, 'amount' => $amount]);
return response()->noContent();
}
Send two requests for 100 against a balance of 100 at the same moment. Both read 100, both pass the check, both write 0, and two payouts are created. The user withdrew 200 from a 100 balance. Nothing threw an error, and the final balance even looks right.
That's the pattern: read, decide, write, with a gap between the read and the write. Under PHP-FPM or Octane, every request is its own worker, so the gap is real whenever two requests arrive close together. Double-clicks, mobile retries on flaky networks, webhook redeliveries and impatient users pressing back and resubmitting all produce exactly that timing.
Where I look first
When I audit a Laravel app for races, I search for these patterns:
# check-then-act on numeric fields
grep -rnE "if \(\$[a-z]+->(balance|stock|quantity|credits|seats|remaining)" app/
# read-modify-write instead of atomic increments
grep -rnE "->(balance|stock|credits)\s*=\s*\$[a-z]+->(balance|stock|credits)\s*[-+]" app/
# "does it exist? then create it"
grep -rnE "if \(!?\s*[A-Z][a-zA-Z]+::where\(.*\)->exists\(\)\)" app/
# status transitions without a guard
grep -rnE "->status\s*=\s*'(paid|confirmed|approved|shipped)'" app/
Every hit is a candidate, not a bug. The question for each one is: what happens if two requests run this block at the same time?
The usual hotspots are payments and refunds, wallet or credit balances, coupon redemption, inventory and seat booking, "create if not exists" for user-level records, and order status changes triggered by both a webhook and a redirect.
Proving it before fixing it
I always reproduce a race before fixing it, because the fix is easy to get subtly wrong. You don't need a load-testing tool; parallel curl is enough on a local or staging copy you own:
# 20 concurrent withdrawals of 100 against a wallet holding 100
seq 20 | xargs -P 20 -I{} curl -s -o /dev/null -w "%{http_code}\n" \
-X POST http://localhost:8000/api/wallets/1/withdraw \
-H "Authorization: Bearer $TEST_TOKEN" -d amount=100 | sort | uniq -c
php artisan tinker --execute="echo App\Models\Payout::where('wallet_id',1)->count();"
If the payout count is more than 1, you've proved the bug. Run it a few times; races are timing-dependent and may need several attempts on a fast machine. Part 6 turns this into an automated test.
Three fixes, and when each one fits
Fix 1: transaction plus row lock. Lock the row you read, so the second request waits until the first commits, then reads the new value.
public function withdraw(Request $request, int $walletId)
{
$amount = (int) $request->input('amount');
DB::transaction(function () use ($walletId, $amount) {
$wallet = Wallet::whereKey($walletId)->lockForUpdate()->firstOrFail();
if ($wallet->balance < $amount) {
abort(422, 'Insufficient balance');
}
$wallet->decrement('balance', $amount);
Payout::create(['wallet_id' => $wallet->id, 'amount' => $amount]);
});
return response()->noContent();
}
Note the model is loaded inside the transaction with the lock. Locking a model that was already route-model-bound outside the transaction does nothing for the earlier read.
Fix 2: a single atomic conditional update. When the logic is simple, push the check into the UPDATE itself and check affected rows:
$updated = Wallet::whereKey($walletId)
->where('balance', '>=', $amount)
->decrement('balance', $amount);
if ($updated === 0) {
abort(422, 'Insufficient balance');
}
The database evaluates the condition and the write as one statement, so there is no gap. Wrap it with the Payout::create in a transaction so you never get one without the other.
Fix 3: a unique constraint. For "only once" rules (one redemption per coupon per user, one payment per order), let the database refuse duplicates:
Schema::table('coupon_redemptions', function (Blueprint $table) {
$table->unique(['coupon_id', 'user_id']);
});
try {
CouponRedemption::create(['coupon_id' => $coupon->id, 'user_id' => $user->id]);
} catch (UniqueConstraintViolationException $e) {
abort(409, 'Coupon already used');
}
UniqueConstraintViolationException exists in Laravel 10.20+; older versions need to catch QueryException and check the error code.
| Guard | Best for | Cost under load | Common mistake |
|---|---|---|---|
lockForUpdate() in a transaction |
Multi-step logic on one row (balances, order state) | Requests on the same row wait in line | Reading the row before the transaction starts |
Atomic conditional UPDATE
|
Simple counters and thresholds | Lowest; one statement | Ignoring the affected-row count |
| Unique index | "Only once" rules | Very low | Catching the exception too broadly |
Cache::lock() (Redis) |
Work outside the DB, like calling a payment API | Low, but lock can expire | Lock TTL shorter than the work |
| Idempotency key | Client retries and webhook redelivery | Low | Storing the key after the side effect, not before |
Part 2 compares these in depth, including deadlocks and what happens when a Redis lock expires mid-request.
The payment-gateway version
The "free money" class of bug usually combines two flows that mark the same order paid: the user's browser returning from the gateway, and the gateway's webhook. If both run if ($order->status !== 'paid') { credit(); $order->update(['status' => 'paid']); } at once, the customer is credited twice. The fix is a guarded transition:
$claimed = Order::whereKey($orderId)
->where('status', 'pending')
->update(['status' => 'paid', 'paid_at' => now()]);
if ($claimed === 1) {
CreditCustomer::dispatch($orderId)->afterCommit();
}
Only the request that actually moved the order from pending to paid does the side effect. The other one sees 0 affected rows and stops. If you need help reviewing payment and wallet flows like this, it's the kind of work we do in Laravel development engagements.
Diagnostic checklist
- [ ] Searched for check-then-act code on balances, stock, credits, seats and status fields.
- [ ] Every money-moving path runs in a
DB::transaction. - [ ] Rows that are read and then updated are loaded with
lockForUpdate()inside the transaction. - [ ] Counters use atomic
increment/decrementwith a condition, and the affected-row count is checked. - [ ] "Only once" rules are backed by a unique index, not just an
exists()check. - [ ] Status transitions use
where('status', old)->update(). - [ ] Side effects (emails, credits, payouts) run only after the guarded write succeeds, using
afterCommit. - [ ] Each suspected race was reproduced with parallel requests before and after the fix.
FAQ
Does PHP being single-threaded protect me?
No. Each PHP-FPM worker or Octane worker handles its own request. Two workers run your code at the same time against the same database.
Will lockForUpdate() slow my app down?
Only for requests touching the same row, which is exactly what you want serialised. Keep transactions short and never call external APIs while holding a row lock.
Can I just disable the submit button?
Do it for user experience, but it's not a fix. Retries, scripts, multiple tabs and webhooks all bypass the front end.
Does SQLite in tests show these bugs?
Rarely. SQLite serialises writes differently from MySQL and PostgreSQL. Reproduce races against the same database engine you run in production.
What isolation level should I use?
The MySQL InnoDB default (REPEATABLE READ) and PostgreSQL default (READ COMMITTED) both still allow these races for plain reads. Explicit locks or atomic updates are clearer than raising the isolation level everywhere.
How do I fix this in a legacy app without a rewrite?
Start with the money paths: add transactions and guarded updates around them one at a time. It's a contained change. Get in touch if you'd like a second pair of eyes on the riskiest flows.
What's next
Part 2 compares lockForUpdate, Cache::lock and unique indexes side by side, including deadlocks, lock timeouts and the expired-lock trap.
Follow & Connect
- Website: Loop Origin
- Watch on YouTube: Resume Boost AI · PixelValut · Daily AI News By Ali
- LinkedIn: Loop Origin
- X: Muhammad Ali Mughal (@AliMughal887)
- GitHub: Loop Origin (@LoopOrigin)

Top comments (1)
The guarded
where('status','pending')->update()is the pattern I trust most for the webhook-plus-redirect case. One thing to think about: the request that loses the claim (0 rows) is often the browser redirect, and by then the credit job may still be queued, so the user lands on a "paid" page with an unchanged balance. How do you handle that in the UI: poll, or show a "processing" state until the credit is written?