Two customers see one product left, click Buy within milliseconds, and both receive an order confirmation. Each request read the same stock value before either saved its update. This is a classic example of race conditions in web applications: the result depends on the unpredictable timing of concurrent operations. Code that works perfectly during ordinary testing can consequently create duplicate orders, duplicate payments, negative inventory, incorrect balances and lost updates under real traffic.
The solution is not simply to make PHP execute faster or to check the data twice. Correct systems define which operations must happen together, enforce those rules inside the database and remain safe when requests, queue workers or application servers overlap.
Race condition, concurrency issue or database deadlock?
Concurrency means multiple operations make progress during overlapping periods. It is normal and desirable. Concurrency issues in web applications arise when that overlap is not handled correctly.
A race condition is a correctness defect in which the outcome depends on operation order or timing. Lost updates are a common form: two requests read a balance of 100, independently add 20 and save 120, losing one addition.
A database deadlock is different. Transaction A locks row 1 and waits for row 2, while transaction B holds row 2 and waits for row 1. Neither can continue, so the database detects the cycle and aborts one transaction. Deadlocks are an operational possibility of locking, not another name for every race condition.
Where races enter an application
- Check-then-update logic: code reads stock, checks that it is positive and later writes a new value.
- Simultaneous HTTP requests: double-clicks, browser retries and genuinely different users can reach the same endpoint together.
- Queue workers: multiple workers may claim or modify the same job-related record.
- Webhook retries: payment providers deliberately redeliver events when acknowledgements are delayed or lost.
- Scheduled jobs: overlapping schedules can recalculate or settle the same records.
- Distributed instances: several containers or servers share the database but not local process memory.
An application-level mutex stored only in a PHP process cannot protect another process, worker or server. A distributed lock can coordinate instances, but it introduces expiry, ownership and failure-mode concerns. Database transactions and constraints should still protect database invariants.
Why the obvious PHP implementation fails
This simplified PHP race condition checks inventory before changing it:
$stock = (int) $pdo->query(
'SELECT stock FROM products WHERE id = 42'
)->fetchColumn();
if ($stock > 0) {
$pdo->exec('UPDATE products SET stock = stock - 1 WHERE id = 42');
createOrder($pdo, 42);
}Two requests can both observe stock = 1. Wrapping only the update in a transaction does not fix the decision because the availability check occurred outside the protected operation.
Prefer an atomic conditional update
When one SQL statement can express the invariant, an atomic database operation is often the simplest solution:
$stmt = $pdo->prepare(
'UPDATE products
SET stock = stock - 1
WHERE id = ? AND stock > 0'
);
$stmt->execute([42]);
if ($stmt->rowCount() !== 1) {
throw new RuntimeException('Out of stock');
}The database evaluates the condition and performs the decrement as one operation. Put this statement and order creation in the same database transaction so either both commit or both roll back.
The concurrency-control toolkit
Database transactions
A transaction creates an all-or-nothing unit for related writes. Begin the transaction before reading data that controls a later write, commit only after every required change succeeds and roll back on exceptions. Transactions provide the boundary; isolation level, locking strategy and SQL structure determine how concurrent transactions interact.
Unique constraints
A unique database constraint is an essential final safeguard for values such as an order idempotency key, payment provider reference or processed webhook ID. An application-level existence check can race. A unique index makes the rule authoritative even when two requests insert simultaneously; one succeeds and the other receives a constraint violation that the application can handle.
Optimistic locking
Optimistic locking assumes conflicts are uncommon. Add a version column, read its value and include it in the update:
UPDATE accounts
SET balance = :balance, version = version + 1
WHERE id = :id AND version = :expected_version;If zero rows change, another transaction modified the record. Reload and retry or report a conflict. This prevents lost updates without holding a lock while application code works.
Pessimistic locking
Pessimistic locking assumes contention is likely and locks selected rows. SELECT ... FOR UPDATE blocks competing writers and locking readers until the transaction ends. Keep transactions short and acquire multiple locks in a consistent order to reduce database deadlocks.
A shared lock permits compatible readers but normally blocks conflicting writes. It is useful when records must remain unchanged during a transaction, although exact behavior depends on the database and isolation level.
Safe inventory decrement with Laravel lockForUpdate()
This Laravel race condition is prevented by locking the product row, validating stock and creating the order inside one transaction:
use IlluminateSupportFacadesDB;
$order = DB::transaction(function () use ($productId, $customerId, $key) {
$product = DB::table('products')
->where('id', $productId)
->lockForUpdate()
->first();
if (!$product || $product->stock < 1) {
throw new RuntimeException('Out of stock');
}
DB::table('products')
->where('id', $productId)
->update(['stock' => $product->stock - 1]);
return DB::table('orders')->insertGetId([
'customer_id' => $customerId,
'product_id' => $productId,
'idempotency_key' => $key,
'status' => 'pending'
]);
}, 5);The second argument allows Laravel to retry the transaction when it identifies a deadlock. The orders.idempotency_key column should also have a unique index. Laravel’s sharedLock() requests a shared read lock, while lockForUpdate() is appropriate when the selected row will be changed.
For this single counter, a conditional update may be more efficient than reading and locking. Use SELECT FOR UPDATE when the decision depends on multiple columns or related rows.
Prevent duplicate payments and transfer funds safely
Do not hold a database transaction open while waiting for a remote payment API. Network calls may take seconds or produce uncertain results. First create a uniquely identified local payment attempt, commit it, call the provider with an idempotency key, and then record the result in a short transaction. Place unique constraints on both the local idempotency key and the provider transaction reference.
DB::transaction(function () use ($providerRef, $orderId, $amount) {
DB::table('payments')->insert([
'order_id' => $orderId,
'provider_reference' => $providerRef,
'amount' => $amount,
'status' => 'captured'
]);
DB::table('orders')
->where('id', $orderId)
->update(['status' => 'paid']);
});If a webhook repeats, the unique provider reference rejects a duplicate payment record. The handler can then load the existing record and return success.
A wallet transfer must lock both accounts and update both balances atomically. Always lock account IDs in a consistent order:
DB::transaction(function () use ($fromId, $toId, $amount) {
$ids = collect([$fromId, $toId])->sort()->values();
$accounts = DB::table('wallets')
->whereIn('id', $ids)
->orderBy('id')
->lockForUpdate()
->get()->keyBy('id');
if ($accounts[$fromId]->balance < $amount) {
throw new RuntimeException('Insufficient funds');
}
DB::table('wallets')->where('id', $fromId)->decrement('balance', $amount);
DB::table('wallets')->where('id', $toId)->increment('balance', $amount);
});An exception rolls back both changes. In production, use fixed-precision decimal values or integer minor units rather than floating-point amounts.
MySQL and PostgreSQL concurrency control
Both MySQL InnoDB and PostgreSQL support transactions, row-level locks and locking reads, but their defaults and implementations differ. MySQL InnoDB commonly uses REPEATABLE READ by default and may take record or gap locks depending on the query, index and isolation level. Queries should use suitable indexes so they lock the intended range rather than scanning broadly. See the MySQL locking-read documentation.
PostgreSQL defaults to READ COMMITTED and uses multiversion concurrency control, so ordinary reads generally do not block writes. SELECT FOR UPDATE still obtains row-level locks for explicit coordination. PostgreSQL also provides lock strengths such as FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE. Its explicit-locking documentation explains their conflicts.
Higher isolation is not a substitute for error handling. Serializable transactions can reject an unsafe execution, and both databases can abort deadlock victims. Applications must roll back and retry eligible transactions with bounded attempts and brief backoff.
An idempotency key identifies one intended operation, allowing repeated submissions to return the original result instead of performing it again. It is ideal for checkout requests, payment creation and webhook processing.
However, idempotency does not independently prevent two different customers from buying the final item, nor does it make a multi-row wallet transfer atomic. Store keys under a unique constraint and combine them with database transactions, conditional updates or locks. Concurrency control protects shared state; idempotency controls repeated intent.
How to test race conditions realistically
- Create a database state with one remaining product or a wallet balance close to the transfer amount.
- Start many requests simultaneously using a load-testing tool, parallel test processes or a synchronization barrier.
- Run multiple queue workers and application instances against the same real database engine used in production.
- Add controlled delays after reads to widen vulnerable timing windows. Do not rely on delays in the final implementation.
- Assert invariants: stock never becomes negative, only one qualifying order exists, balances conserve value and provider references remain unique.
- Repeat tests under the production isolation level. SQLite or transaction-wrapped unit tests may not reproduce MySQL row locking or PostgreSQL concurrency behavior.
- Exercise deadlocks, lock timeouts, exceptions and retries. Verify that failed attempts leave no partial records.
Production prevention checklist
- Identify every read-modify-write sequence and shared business invariant.
- Prefer atomic SQL updates when one statement can enforce the rule.
- Start transactions before decision-making reads and keep them short.
- Use optimistic locking for infrequent conflicts and pessimistic locking for contended records.
- Lock multiple rows in a consistent order.
- Add unique constraints for order keys, payment references and processed events.
- Handle rollbacks, deadlocks, serialization failures and lock timeouts explicitly.
- Use idempotency keys without treating them as a replacement for locking.
- Monitor constraint violations, retry counts, deadlocks and long transactions.
Frequently asked questions
Does a database transaction automatically prevent every race condition?
No. A transaction provides an atomic boundary, but a weak query pattern can still make decisions from stale or non-locked data. Use an appropriate isolation level, atomic conditional update, row lock or optimistic version check.
Should I always use SELECT FOR UPDATE?
No. It is useful when a transaction must inspect a row before changing related state. Atomic updates are often faster for counters, while optimistic locking works well when conflicts are rare. Excessive locking reduces throughput and can increase deadlocks.
Can Redis or a framework mutex replace database locking?
Not reliably for database integrity by itself. Distributed locks can coordinate work, but lease expiration, process pauses and network failures complicate correctness. Keep critical constraints and transactional invariants in the database.
What is the best defense against duplicate orders?
Use several layers: a client-provided idempotency key, a unique database constraint, a transaction covering stock allocation and order creation, and an atomic update or row lock that prevents inventory overselling.
Preventing race conditions requires designing for overlap rather than assuming requests arrive one at a time. When business rules are expressed as atomic operations, protected transactions and database constraints, concurrent requests become routine events instead of sources of silent data corruption.