Race conditions in a Laravel app: reproduce them, then fix them · Part 3 of 5
Lost updates and oversold stock: atomic writes, locks and versions
Four races, one bug: a read, arithmetic in PHP, a write. Fixed by letting the database do the arithmetic, the invariant as a WHERE clause, a locking read where the write depends on the read, and a version column for the admin form. Plus two deadlocks and a snapshot that could not see the winner.
By Abhishek Fouzdar
Four of the race tests are still red after part 2: the stock, the coupon counter, the gift card balance and the order number. They are one bug with four faces. The code reads a value, does arithmetic on it in PHP, and writes the result back, and between the read and the write another request did the same. This part fixes all four, with four tools in order of preference: let the database do the arithmetic, make the invariant a WHERE clause, lock the row when the write depends on the read, and carry a version when the gap has a human in it. By the end the race suite is green, and getting there produced two deadlocks and a snapshot that could not see the future, all three of which are in the last section.
The shape, in SQL
Here is what Eloquent sent for the stock in part 1:
SELECT * FROM products WHERE id IN (6);
-- a few milliseconds of PHP: stock is 5, 5 >= 1, subtract 1
UPDATE products SET stock = 4 WHERE id = 6;
The 4 is the problem. It is a fact about the row as this request saw it, written back as if nothing had happened since. Twenty requests saw 5 and twenty wrote 4. The database was told the answer twenty times and never asked the question.
Tool one: the database does the arithmetic
UPDATE products SET stock = stock - 1 WHERE id = 6;
The same statement with the subtraction moved inside it. InnoDB takes an exclusive lock on the row before it changes it, so two of these cannot run on the same row at once; the second waits for the first to finish and then subtracts from what the first wrote. Twenty of them leave stock at -15, which is wrong in a new way, but every one of the twenty sales is counted, which is more than part 1 managed. In Eloquent this is increment and decrement, on a model or on a query, and it is the right call for every counter that is only ever adjusted: views, redemptions, balances, stock.
A subtlety worth knowing: $product->decrement('stock') on a model instance sends stock = stock - 1 and also subtracts one from the attribute in memory. The attribute is now a guess about the row, not a copy of it. Nothing should be decided on it without reading again.
Tool two: the invariant as a WHERE clause
The stock must not go below zero, which is a condition on the row at the moment of the write. So say it to the database in the write:
// UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?
$taken = Product::whereKey($product->id)->where('stock', '>=', $quantity)->decrement('stock', $quantity);
if ($taken === 0) {
throw new CheckoutFailed("Only {$product->fresh()->stock} of {$product->name} left.");
}
decrement on a query returns the number of rows it changed. One means the stock was there and is now taken; zero means someone else got there first, and the message reads the row again to say how many are left, which by then is usually none. The check and the act are a single statement, and the database evaluates the WHERE against the row as it is when the statement runs, under the row lock, not against whatever this request read earlier. That is true even under REPEATABLE READ, where plain SELECTs see a snapshot: an UPDATE always reads the current row. Part 4 is about the difference between those two kinds of read.
The coupon is the same tool with the limit on the row:
// UPDATE coupons SET redemptions = redemptions + 1 WHERE id = ? AND redemptions < max_redemptions
$redeemed = Coupon::whereKey($coupon->id)->whereColumn('redemptions', '<', 'max_redemptions')->increment('redemptions');
if ($redeemed === 0) {
throw new CheckoutFailed("Coupon {$coupon->code} has been fully redeemed.");
}
Twenty requests, five redemptions, and the sixth UPDATE changes nothing because the condition is false by the time it runs.
Tool three: a locking read, when the write depends on the read
The gift card does not fit tool two. How much to take from it depends on how much it holds: min(balance, amount due). The amount is computed in PHP from a read, so the read has to stay true until the write. That is what SELECT … FOR UPDATE is for:
$card = GiftCard::where('code', strtoupper($giftCardCode))->lockForUpdate()->first()
?? throw new CheckoutFailed('That gift card does not exist.');
$fromCard = min($card->balance_cents, $subtotal - $discount);
// …later, after the order exists
$card->decrement('balance_cents', $fromCard);
lockForUpdate takes the exclusive lock at the read, and the lock is held until the transaction commits. A second checkout with the same card blocks on its own locking read until the first commits, then reads the reduced balance and computes from that. Ten shoppers with the $20 card are served one at a time for the few milliseconds each one needs: two orders, $14 and $6, eight refused with "no balance left", $0.00 on the card, nothing overspent.
The cost is that nobody else can touch that row while the lock is held, which is the whole point and also the reason to hold it briefly. The locking read is the first thing the checkout does after pricing, and the commit is a few queries later. The lock-free alternative, for a row with more contention than a gift card, is tool two with a retry: compute the amount, UPDATE … WHERE balance_cents >= ?, and if zero rows changed, read again and recompute. ShopMini does not need it.
Tool one again: the order number
The counter was the first race in the suite to produce a visible symptom and is the easiest to fix:
public static function next(): string
{
if (self::advance() === 0) {
DB::table('counters')->insertOrIgnore(['key' => 'order', 'value' => 1000]);
self::advance();
}
return sprintf('SM-%d', DB::getPdo()->lastInsertId());
}
private static function advance(): int
{
return DB::update('update counters set value = last_insert_id(value + 1) where `key` = ?', ['order']);
}
LAST_INSERT_ID(expr) is a MySQL idiom: it sets the connection's last-insert-id to the expression's value as a side effect of the UPDATE, so the increment and the read of what it produced are one statement, and lastInsertId() on the PDO connection returns it without a second query. The INSERT IGNORE handles the first order ever without a race, since an ignored duplicate is not an error.
next() is called before the checkout's transaction opens. Inside it, the UPDATE would hold the counter's row lock until the commit, and every checkout in the shop would queue behind every other for the length of a transaction. Outside it, the lock lasts one statement. The trade is gaps: a checkout that takes a number and then fails keeps it. Nothing in ShopMini minds. A business whose invoice numbers must be gapless by law needs the lock inside the transaction and the queue that comes with it, and should know that is what it is choosing.
The transaction
All of this is inside one DB::transaction. The reason is the second item. A cart with two products takes the stock for the first, finds the second sold out, and throws; without a transaction the first product's stock is gone and there is no order. With it, the throw rolls everything back, including the order row and the stock, and the feature suite checks exactly that.
The transaction changes one thing from part 2 that is easy to miss, and it is the first item in the last section.
Tool four: a version column, when the gap has a human in it
The admin form has the same read-modify-write shape stretched over minutes. Two people open order SM-1001. One types a note about gift wrapping and saves. The other changes the status to shipped and saves, and the form they are saving still has an empty note, because that is what it had when they opened it. The note is gone, and nobody did anything wrong.
No lock can hold a row for the length of a coffee break. What works is to record which version of the row the form was rendered from and make the save conditional on it, which is tool two with a human in the loop:
$saved = Order::whereKey($order->id)->where('version', $data['version'])->update([
'status' => $data['status'],
'note' => $data['note'],
'version' => $data['version'] + 1,
]);
if ($saved === 0) {
return redirect()->route('admin.orders.edit', $order)
->withErrors(['version' => 'Someone else changed this order while you were editing it. Their changes are shown; apply yours again if they still make sense.']);
}
The form carries version in a hidden field. Zero rows updated means the row has moved on, the second person's save is refused, and they see the order as it now is, with the colleague's note in it:

This is optimistic locking: no lock at all, just a refusal to overwrite what was not seen. An integer column is better than comparing updated_at, which has one-second precision in a default Laravel schema and lets two saves in the same second pass as one.
The results
The race suite, three runs in a row:
✓ it runs every runner against the test database 4.92s
✓ it sells five units to ten buyers, and not one more 1.93s
✓ it lets a coupon with five uses be used five times 2.26s
✓ it never spends more than a gift card holds 2.63s
✓ it never issues the same order number twice 2.99s
✓ it turns one checkout into one order even when the button is pressed… 2.03s
✓ it records one payment when the same event is delivered five times… 2.19s
Tests: 7 passed (15 assertions)
The double-submit test is stricter than it was in part 2: it now also requires both clicks to come back with the same order number, since a click that crashes with a duplicate-number error is not a click that was handled.
Over HTTP, from a reset shop each time, with the part 1 numbers for comparison:
| Scenario | Part 1 | Part 3 | Audit |
|---|---|---|---|
checkout, 20 shoppers, 5 pens |
20 placed, stock now 3 | 5 placed, 15 refused, p95 214 ms | no problems |
coupon, 20 shoppers, 5 uses |
20 placed, counter 2 | 5 placed, 15 refused | no problems |
giftcard, 10 shoppers, $20 card |
10 placed, $140 spent | 2 placed, 8 refused | no problems |
double-submit, 5 shoppers × 2 clicks |
10 placed, 10 orders | 10 placed, 5 orders | no problems |
The fifteen refused shoppers saw "Only 0 of Limited edition fountain pen left.", which is the message the conditional update produces when it changes nothing. The median request went from 59 ms in part 1 to 126 ms: twenty checkouts for one product row now go through that row one at a time, and the ones at the back of the queue wait for the ones at the front. That is the price of the invariant, and it is paid only on rows that are actually contended. A checkout for a product nobody else is buying at that instant waits for nothing.
What went wrong
A snapshot from before the winner committed. Wrapping the checkout in a transaction broke the double-submit fix from part 2 in a way the race suite caught immediately: one of the two clicks came back with Duplicate entry … for key 'orders.orders_checkout_token_unique', the exception createOrFirst is supposed to swallow. It did catch it. Its recovery read found nothing and rethrew. Under REPEATABLE READ, InnoDB's default, a transaction's plain reads all see the database as it was at the transaction's first read. The losing click had read the products table, then tried its insert, waited for the winner to commit, got the violation, and then read the orders table through a snapshot taken before the winner's order existed. The webhook handler in part 2 has the same createOrFirst inside a transaction and never hit this, because its claim is the first statement in its transaction, so its snapshot starts after the winner. The checkout now inserts and, on a violation, recovers with lockForUpdate()->firstOrFail(): a locking read always reads the latest committed row, snapshot or not. The rule that falls out: claim first, or recover with a locking read. The same bug showed up a second time as Duplicate entry 'order' for key 'counters.PRIMARY', from ten firstOrCreate calls racing to create the counter row in the test database, which is why the counter now bootstraps with INSERT IGNORE.
Deadlock one: the foreign key's shared lock. With the arithmetic fixed, ten checkouts for one product produced Deadlock found when trying to get lock; try restarting transaction on most of them. SHOW ENGINE INNODB STATUS keeps the last one:
*** (1) TRANSACTION:
update `products` set `stock` = `stock` - 1 … where `products`.`id` = 1 and `stock` >= 1
*** (1) HOLDS THE LOCK(S):
RECORD LOCKS … index PRIMARY of table `testing`.`products` lock mode S locks rec but not gap
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS … index PRIMARY of table `testing`.`products` lock_mode X locks rec but not gap waiting
*** (2) TRANSACTION:
update `products` set `stock` = `stock` - 1 … where `products`.`id` = 1 and `stock` >= 1
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS … index PRIMARY of table `testing`.`products` lock mode S locks rec but not gap
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS … index PRIMARY of table `testing`.`products` lock_mode X locks rec but not gap waiting
*** WE ROLL BACK TRANSACTION (2)
Both transactions hold a shared lock on the product row and both want the exclusive one. Neither took the shared lock on purpose: inserting an order_items row whose product_id references the product makes InnoDB check the foreign key, and the check takes a shared lock on the parent row that lasts until commit. Two checkouts insert their items, each holding S, then each tries the stock UPDATE, each waits for the other's S to go, and InnoDB rolls one back. The fix was to take the stock before inserting the item, so that the transaction already holds X when the foreign key wants S.
Deadlock two: the same thing, through the order's coupon. The coupon test kept failing after that, two or four orders out of five. The status showed a cycle across two tables this time: one transaction holding S on the coupon and waiting for X on the product, the other holding X on the product and waiting for X on the coupon. The order row's coupon_id foreign key takes S on the coupon when the order is inserted, and the increment wants X afterwards. The order cannot be inserted after the increment, because the increment must only happen for the request that made the order. So the coupon is read with lockForUpdate() before anything else, the same way the gift card is: a transaction that already holds X on the row is not blocked by its own foreign key check, and no other checkout can hold S on it meanwhile. The rule: a row that will be updated after a child row references it must be exclusively locked before the child is inserted, or updated before. Part 4 is about the other deadlocks, the ones that come from lock order and from gaps.
The conflict page showed the copy that lost. The first version of the version check redirected withInput(), which made the form re-render the stale note the second person had submitted, directly under a message saying their colleague's changes were shown. Removing withInput() made the message true. A message that describes a behaviour is a test of that behaviour, and this one failed in the screenshot.
Part 4 reads the server's own records for what REPEATABLE READ promises and does not, why a locking read on a range locks the gaps between rows, and how a deadlock is retried rather than avoided: Isolation levels, gap locks and deadlocks, from the server's own records.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
3 / 5- OverviewRace conditions in a Laravel app: reproduce them, then fix them
- Part 1The shop, the races, and a test that fires ten checkouts at once
- Part 2Duplicates: double submits, repeated webhooks and the unique index
- Part 3Lost updates and oversold stock: atomic writes, locks and versions
- Part 4Isolation levels, gap locks and deadlocks, from the server's own records
- Part 5Jobs, workers and the scheduler racing each other