If you've worked with Laravel for a while, you've probably used DB::transaction() many times.
You wrap a few database operations in a transaction, commit everything together, and assume your data is safe.
But there is a problem: a database transaction does not automatically prevent every race condition.
Two requests can execute at the same time, read the same data, make decisions based on that data, and overwrite each other's changes.
This becomes especially dangerous in financial systems, inventory management, booking platforms, and any application where multiple users can modify the same resource concurrently.
In this article, we'll explore how race conditions happen, why transactions alone aren't always enough, and how to handle them using Laravel and database-level concurrency controls.
1. What Is a Race Condition?
A race condition occurs when the correctness of an operation depends on the timing or order of concurrent operations.
Imagine a user has a wallet balance of 100.
Two requests arrive almost simultaneously:
- Request A wants to withdraw 80.
- Request B also wants to withdraw 80.
Both requests read the balance before either one updates it.
Here's what can happen:
| Step | Request A | Request B |
|---|---|---|
| 1 | Reads balance: 100 | |
| 2 | Reads balance: 100 | |
| 3 | Checks if 100 >= 80 | |
| 4 | Checks if 100 >= 80 | |
| 5 | Updates balance to 20 | |
| 6 | Updates balance to 20 |
Both requests believe the withdrawal is valid.
The final balance is 20, even though the application accepted two withdrawals of 80.
The problem isn't that the database failed to execute an update.
The problem is that both requests made decisions using the same stale data.
This is a classic example of a race condition, specifically a lost update caused by concurrent read-modify-write operations.
2. Why Database Transactions Are Not Enough
A common first attempt is to wrap the operation in a transaction:
use Illuminate\Support\Facades\DB; DB::transaction(function () use ($userId, $amount) { $user = User::findOrFail($userId); if ($user->balance < $amount) { throw new RuntimeException('Insufficient balance.'); } $user->balance -= $amount; $user->save(); }); This gives us atomicity.
If an exception occurs, the database rolls back the transaction. If everything succeeds, it commits.
But atomicity doesn't necessarily mean that concurrent transactions cannot interfere with each other.
Depending on the database engine and transaction isolation level, both transactions may still read a balance of 100 before either writes its update.
A transaction protects a group of database operations from being partially committed. It does not automatically mean that every read is protected from concurrent changes.
This distinction is important:
- Atomicity ensures that a transaction succeeds or fails as a unit.
- Isolation determines how concurrent transactions interact.
- Locking and concurrency control help prevent conflicting operations.
To solve the problem, we need to choose the right mechanism for the operation.
3. Pessimistic Locking with lockForUpdate()
One solution is to lock the database row before reading it.
In Laravel, we can use lockForUpdate():
use Illuminate\Support\Facades\DB; DB::transaction(function () use ($userId, $amount) { $user = User::whereKey($userId) ->lockForUpdate() ->firstOrFail(); if ($user->balance < $amount) { throw new RuntimeException('Insufficient balance.'); } $user->balance -= $amount; $user->save(); }); What happens now?
- Request A starts a transaction.
- It selects the user row with
FOR UPDATE. - The database locks that row.
- Request B tries to acquire the same lock and has to wait.
- Request A updates the balance and commits.
- Request B can now acquire the lock and read the updated balance.
Request B sees 20 instead of 100 and rejects the withdrawal.
The race condition is prevented.
Important: Use It Inside a Transaction
lockForUpdate() is a pessimistic locking mechanism. The lock is generally held until the transaction ends.
That's why it should be used inside a transaction:
DB::transaction(function () { $user = User::whereKey(1) ->lockForUpdate() ->firstOrFail(); // Perform the operation. }); Without a surrounding transaction, the lock may not protect the subsequent operations in the way you expect.
When Should You Use Pessimistic Locking?
It's useful when:
- Multiple requests may modify the same record.
- The operation depends on the current state of that record.
- Conflicting operations should wait rather than fail immediately.
- The cost of accepting inconsistent data is high.
Financial balances and inventory reservations are common examples.
However, locks introduce contention. If many requests need the same row, they may spend significant time waiting.
Keep transactions short and avoid performing external API calls or other slow operations while holding database locks.
4. Atomic Updates: Sometimes You Don't Need to Read First
There is another approach that is often simpler and more efficient.
Instead of reading a balance, checking it in PHP, and then updating it, let the database perform the check and update in a single statement.
$updated = User::whereKey($userId) ->where('balance', '>=', $amount) ->decrement('balance', $amount); if ($updated === 0) { throw new RuntimeException('Insufficient balance.'); } The database executes the update conditionally.
Conceptually, it performs:
UPDATE users SET balance = balance - 80 WHERE id = 1 AND balance >= 80; The important part is that the condition and update happen in one database statement.
If two requests attempt to withdraw 80 from a balance of 100:
- The first update succeeds and changes the balance to 20.
- The second update cannot satisfy
balance >= 80. - Only one request succeeds.
This is an example of using the database's atomic update capabilities instead of implementing a read-modify-write operation in application code.
A useful rule: If your business operation can be expressed as a conditional SQL update, consider doing that before introducing explicit row locking.
Of course, if the operation involves multiple records or more complex business rules, you may still need a transaction.
5. Optimistic Locking: Detect Conflicts Instead of Waiting
Pessimistic locking assumes that conflicts may happen and locks the resource before modifying it.
Optimistic locking takes a different approach.
It assumes conflicts are relatively uncommon and detects whether another transaction has modified the record since it was read.
A common implementation uses a version column.
Imagine our products table has:
id name price version Every successful update increments the version.
For example:
id: 1 price: 100 version: 5 Two requests read the same product and both receive version 5.
Request A updates the product first:
UPDATE products SET price = 120, version = version + 1 WHERE id = 1 AND version = 5; The update succeeds. The version becomes 6.
Request B then tries to update using version 5:
UPDATE products SET price = 130, version = version + 1 WHERE id = 1 AND version = 5; No rows are updated because the version is now 6.
The application knows that another request modified the record.
Implementing Optimistic Locking in Laravel
A simple implementation looks like this:
$updated = Product::whereKey($productId) ->where('version', $currentVersion) ->update([ 'price' => $newPrice, 'version' => DB::raw('version + 1'), ]); if ($updated === 0) { throw new RuntimeException( 'The product was modified by another request.' ); } Here, $currentVersion is the version that was originally read.
The important part is that checking the version and updating the record happen in the same SQL statement.
When Should You Use Optimistic Locking?
It's useful when:
- Conflicts are relatively rare.
- You don't want requests waiting on database locks.
- Users may edit the same record simultaneously.
- You can detect a conflict and ask the user to retry or refresh.
For example, editing product details, updating configuration, or modifying documents can be good candidates.
Unlike pessimistic locking, optimistic locking doesn't prevent concurrent reads. It detects conflicting writes.
6. Unique Constraints: Let the Database Enforce Uniqueness
Not every race condition involves updating an existing record.
Sometimes the problem is inserting duplicate data.
Imagine a user can redeem a coupon only once.
A naive implementation might look like this:
if (!CouponRedemption::where('user_id', $userId) ->where('coupon_id', $couponId) ->exists()) { CouponRedemption::create([ 'user_id' => $userId, 'coupon_id' => $couponId, ]); } This looks reasonable, but it contains a race condition.
Two requests can both check for an existing redemption before either inserts a record.
Both requests see that no redemption exists.
Both insert a new row.
The solution is to enforce the rule at the database level.
Create a unique index:
Schema::table('coupon_redemptions', function (Blueprint $table) { $table->unique(['user_id', 'coupon_id']); }); Now the database guarantees that the same user cannot redeem the same coupon twice.
Even if two requests attempt the insertion simultaneously, only one can succeed.
The other receives a unique constraint violation.
You can catch that exception and handle it as an already-redeemed case.
Never rely exclusively on an application-level exists() check to enforce uniqueness.
The database should be the final authority for constraints that must always hold.
This principle also applies to idempotency keys, unique payment references, and other business identifiers.
7. Deadlocks and Retry Strategies
Concurrency control introduces another problem: deadlocks.
A deadlock happens when two transactions hold locks that the other transaction needs.
For example:
- Transaction A locks row 1 and waits for row 2.
- Transaction B locks row 2 and waits for row 1.
Neither transaction can continue.
Database engines can detect deadlocks and abort one of the transactions so the other can proceed.
Laravel provides a convenient retry mechanism:
DB::transaction(function () { // Database operations }, attempts: 5); Laravel will retry the transaction when a deadlock occurs, up to the configured number of attempts.
But there are a few things worth considering.
Keep Lock Ordering Consistent
If multiple operations need the same records, try to acquire locks in a consistent order.
For example, when transferring money between two accounts, always lock the account with the smaller ID first.
DB::transaction(function () use ($senderId, $receiverId) { $accountIds = collect([$senderId, $receiverId]) ->sort() ->values(); $accounts = Account::whereIn('id', $accountIds) ->orderBy('id') ->lockForUpdate() ->get() ->keyBy('id'); // Validate and update both accounts. }); This reduces the likelihood of two transactions acquiring the same locks in opposite orders.
Keep Transactions Short
Avoid doing things like these inside a transaction:
- Calling external APIs.
- Sending emails.
- Processing large files.
- Waiting for user input.
- Performing unnecessary calculations.
Long-running transactions hold locks longer and increase contention.
There is also an important detail when using Laravel's transaction retry mechanism:
The transaction closure may execute more than once.
Therefore, avoid placing non-idempotent external side effects inside a retryable transaction.
For example, sending a payment request to an external provider inside the closure could result in duplicate requests if the transaction is retried.
Keep the transaction focused on database work. For reliable external side effects, consider patterns such as the transactional outbox.
8. Choosing the Right Approach
There isn't one concurrency-control strategy that fits every situation.
The right choice depends on what you're protecting and how frequently conflicts occur.
| Strategy | Best use case |
|---|---|
| Atomic SQL update | Simple conditional updates |
lockForUpdate() | Conflicting operations that must wait |
| Optimistic locking | Conflicts are rare and can be detected |
| Unique constraints | Preventing duplicate records |
| Transaction retries | Recovering from deadlocks |
These mechanisms are not mutually exclusive.
For example, a financial operation might use:
- A database transaction to group multiple changes.
- Row-level locks to protect account balances.
- Unique constraints to prevent duplicate payment references.
- Idempotency keys to protect against repeated requests.
Each mechanism protects a different part of the business operation.
9. Final Thoughts
One of the most important lessons in building reliable applications is that correct code doesn't always produce correct results when executed concurrently.
A transaction is essential, but it isn't a universal solution to concurrency problems.
When multiple requests can access the same data, you need to think about:
- What happens if two requests read the same value?
- Can they overwrite each other's changes?
- Should one request wait, or should it detect a conflict?
- Can the database enforce the business rule?
- What happens if a transaction is retried?
The database is more than a place to store data. It is also responsible for enforcing the consistency rules your application depends on.
Don't just make your operations transactional. Make them concurrency-safe.
