Preventing Double Charges and Race Conditions in MySQL 8 with Row-Level Locking
Two simultaneous clicks on a checkout or seat-reservation button can silently oversell a cohort or duplicate a ledger entry. Learn how to fix it properly with InnoDB transactions and lockForUpdate().
Every backend developer eventually runs into a bug that cannot be reproduced locally: a cohort with 20 seats somehow ends up with 22 enrolled students, or a wallet balance goes negative even though the code clearly checked if ($balance >= $amount).
The culprit is almost always a check-then-act race condition. Under normal single-user testing, Request A finishes before Request B starts. In production, two users—or one impatient user double-clicking a submit button on a slow mobile connection—hit the server within the same 5 milliseconds.
How the Race Condition Happens
Consider naive seat reservation code:
// Vulnerable to overselling under concurrent requests
$cohort = Cohort::findOrFail($cohortId);
if ($cohort->seats_left <= 0) {
abort(422, 'Cohort is full.');
}
Enrollment::create([...]);
$cohort->decrement('seats_left');
If seats_left is 1, both Request A and Request B run the SELECT at the exact same moment. Both see seats_left === 1. Both pass the if check. Both insert an enrollment row, and the cohort now has -1 seats left.
Fixing It Properly with InnoDB lockForUpdate()
MySQL 8's InnoDB engine supports pessimistic row-level locking via SELECT ... FOR UPDATE. Inside a database transaction, Laravel exposes this through lockForUpdate():
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
$enrollment = DB::transaction(function () use ($cohortId, $studentId): Enrollment {
// Locks only this cohort row until the transaction commits
$cohort = Cohort::whereKey($cohortId)
->lockForUpdate()
->firstOrFail();
if ($cohort->seats_left <= 0) {
throw ValidationException::withMessages([
'cohort_id' => 'All seats for this cohort have been filled.',
]);
}
$enrollment = Enrollment::create([
'student_id' => $studentId,
'cohort_id' => $cohort->id,
'agreed_fee_pkr' => 35000,
]);
$cohort->decrement('seats_left');
return $enrollment;
}, attempts: 3);
What Happens Behind the Scenes
When Request A runs lockForUpdate(), InnoDB places an exclusive write lock on that single row (not the entire table, because id is the primary key index). When Request B arrives 2 milliseconds later, MySQL pauses Request B's SELECT until Request A commits. Once Request A commits, Request B reads the updated value (0) and cleanly rejects the request.
Four Mistakes That Break Row Locking
- Forgetting the transaction wrapper: Calling
lockForUpdate()outsideDB::transaction()releases the lock immediately after the query returns, making it useless. - Locking without an index: If your
WHEREclause scans a non-indexed column, InnoDB may lock every scanned row in the table and stall unrelated traffic. Always lock by primary key or a unique indexed column. - Running external HTTP calls inside the transaction: Never send an email, call a payment gateway, or hit an AI API while holding a database lock. Commit the transaction first, then dispatch queued notifications.
- Ignoring unique database constraints: Pair row locks with composite unique indexes (for example,
UNIQUE(student_id, cohort_id)) so the database schema itself acts as a final safety net.
When you combine InnoDB transactions, indexed row locks, and unique constraints, your financial and inventory tables stay accurate even under sudden traffic spikes.
Need help architecting a Laravel backend, Kotlin Android app, or joining our weekend engineering cohort?