Concurrency6 min read

Race conditions in a Laravel app: reproduce them, then fix them

A small shop with every race a shop can have, each reproduced from a test that fires the action from ten processes at once, then fixed at the lowest layer that holds: a unique index, an atomic update, a WHERE clause, a locking read, a version column, a retried transaction. Five parts.

By Abhishek Fouzdar

A race condition is a bug that needs two requests to show itself, which is why it is never in the test suite and always in production. This series builds a small shop with every race a shop can have, written the way checkout code usually is, and then does the thing that turns a race from a story into a bug report: it reproduces each one from a test, on purpose, every run, and fixes it at the lowest layer that can hold the invariant. Five parts, ten invariants, every number measured. Laravel 13.17, PHP 8.5, MySQL 8.4, on 4 November 2026.

The ShopMini home page: a grid of stationery with prices, stock counts and an Add to cart button; the Limited edition fountain pen shows 5 left

The shop is ShopMini: twenty-four products with stock, a session cart, a checkout with a coupon field and a gift card field, a signed payment webhook, an admin form, and a scheduled cleanup of unpaid orders. It is small enough to read in an afternoon and has, as written in part 1, six race conditions that a feature suite of eleven passing tests says nothing about.

Who this is for

You build Laravel applications that take orders, payments, bookings or anything else that must not happen twice or go below zero, and you have either had the support ticket already or know it is coming. Nothing about InnoDB is assumed; the locking and isolation behaviour is read off the server's own records when it comes up, not described from memory. The interview question this series answers is "how would you prevent overselling?", and the answer is longer and more specific than "use a transaction".

What you will end up with

The application, ShopMini, in the shipbytes/blog-examples repository, one commit per part, with a race suite that fires the same action from ten processes at the same instant, k6 scenarios that do the same over HTTP, an audit command that scores the damage, a second database connection for isolation experiments, and a gateway simulator with retries. And a short list of tools, in order of preference, that between them fixed every race the shop had.

Piece What it teaches
The method and the tools Name the invariant, fire the action from several processes at once, read the failure, fix at the lowest layer, keep the test, audit. A starting gun built on Laravel's Concurrency facade, and the three serialisation rules it took to make it work.
Duplicates A check followed by an insert cannot be made safe in PHP. A unique index can, and createOrFirst is how code expects the index to say no. The migration that failed halfway because the bug had already left duplicates.
Lost updates A read, arithmetic in PHP, a write. The database doing the arithmetic, the invariant as a WHERE clause, lockForUpdate where the write depends on the read, a version column where the gap has a human in it, and the two deadlocks foreign keys cause.
Isolation and deadlocks What REPEATABLE READ shows a plain read and what it shows a write, the gap locks in performance_schema.data_locks, a deadlock in SHOW ENGINE INNODB STATUS, and a fix measured with the deadlock counter: retry first, then a consistent lock order.
The queue A job queued before its transaction committed, a job that ran on two workers at once, a scheduled command that overlapped itself, and the workers that kept running code that no longer existed.

The numbers

Each race from a reset shop, over HTTP with k6, before and after:

Race Shoppers As written After the fix
Twenty buy the last five pens 20 20 orders, stock shows 3 left, three order numbers for twenty orders 5 orders, 15 refused, stock 0
Twenty use a five-redemption coupon 20 20 orders used it, its counter says 2 5 orders, 15 refused, counter 5
Ten pay with one $20 gift card 10 $140 spent, balance shows $6 $20 spent, balance $0
Five press "Place order" twice 5 × 2 10 orders 5 orders, both clicks land on the same page
One payment event delivered five times 5 5 payments, 5 receipts 1 payment, 4 told duplicate
Ten carts with the same two products, mixed order 10 6 orders, 4 deadlocks 10 orders, 0 deadlocks
The cleanup runs twice at once over twenty orders 2 "Cancelled 20" and "Cancelled 20" "Cancelled 6" and "Cancelled 14"

The race suite went from one green of seven in part 1 to ten green of ten in part 5, three runs in a row each time it was measured, and the feature suite of twenty-two tests stayed green through every part. The median checkout request went from 59 ms to 126 ms under twenty concurrent buyers of one product, which is the cost of taking a contended row one request at a time, and is paid only on contended rows.

The parts

  1. The shop, the races, and a test that fires ten checkouts at once. The method; the shop as written and the three shapes in it; gun(), a starting gun on Laravel's Concurrency facade; the race suite, six red; k6 scenarios with a shared start; shop:audit, the scoreboard.
  2. Duplicates: double submits, repeated webhooks and the unique index. Three unique indexes, one per migration; what createOrFirst does and why firstOrCreate falls back to it; claim the token, then take the stock; claim the event inside a transaction; the index on the order number that turns a silent duplicate into a loud failure.
  3. Lost updates and oversold stock: atomic writes, locks and versions. decrement with the condition in the WHERE; whereColumn for the coupon's limit; lockForUpdate for the gift card; LAST_INSERT_ID(value + 1) for the counter, outside the transaction; the version column on the admin form; the snapshot that could not see the winner; two deadlocks from foreign keys.
  4. Isolation levels, gap locks and deadlocks, from the server's own records. A second connection; five, five, two; the four levels; data_locks while a range is locked; a lock-order deadlock in the status page; DB::transaction(…, attempts: 3) and ksort, measured separately with innodb_metrics.
  5. Jobs, workers and the scheduler racing each other. after_commit; a claim before the send; a claim per order in the cleanup, with withoutOverlapping and onOneServer on top; queue:restart; the barrier that replaced the timed gun.

The decisions

Reproduce first, every time. No fix in the series was written before a test showed the bug, and no test was kept that could not fail. Twice a race test passed on its first run and both times the reason was that it was not racing: once because the runs were a second apart, once because the thing it was racing for had already happened. A race test that passes is a test to be suspicious of until it has been seen red.

Real processes, a real database, no mocks. The race suite runs its action in separate PHP processes through Laravel's Concurrency facade against the test database, with every row committed, because the point is that other connections can see and fight over them. The isolation tests use a second connection in the same process for exact interleavings. Neither is a unit test, and neither could be.

Fix at the lowest layer that holds. From the bottom: a unique index, which holds without any cooperation from the code; an atomic update, which holds without a lock; an update with its condition in the WHERE, which makes the check and the act one statement; a locking read, when the write depends on the read; a version column, when the gap has a human in it; a transaction with a retry, for the deadlocks that remain; and only then a lock in the cache, for work that has no row to mark. Every fix in the series is the lowest one that applied, and the few that are higher say why.

MySQL's defaults, and what they mean. The shop runs at REPEATABLE READ because that is what InnoDB gives you, and the series says what that is: plain reads from a snapshot, writes and locking reads against the present, gap locks on ranges. Everything is also shown under READ COMMITTED where it differs. The deadlock log is on, the lock wait timeout is five seconds, and every lock and deadlock the posts describe is quoted from performance_schema or SHOW ENGINE INNODB STATUS rather than from the manual.

The audit is part of the fix. Every race was there before its test was. shop:audit compares what the orders say with what the shelf, the coupons and the cards say, and lists every disagreement; it ran after every scenario in the series and it is the step that tells you what the bug already cost.

Where it stands

ShopMini sells five pens to five people, and the sixth is told so. The ten invariants in its race suite are the ten sentences a shop's owner would want to be true whatever the timing, and the suite proves each of them under load in about fifteen seconds. The tools are ordinary: Eloquent's increment, a WHERE clause, lockForUpdate, a unique index, createOrFirst, DB::transaction with attempts, after_commit. What the series adds is the order to reach for them in, and a way to know, before the support ticket, that the one you reached for held.

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.