Race conditions in a Laravel app: reproduce them, then fix them · Part 1 of 5

Concurrency12 min read

The shop, the races, and a test that fires ten checkouts at once

A small shop written the usual way oversells, over-redeems its coupons, overspends a gift card, issues order numbers twice, turns one click into two orders and records one payment five times. A test helper that fires an action from ten processes at the same instant reproduces every one, every run.

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 part builds a shop with every race a shop can have, written the way checkout code usually is, and then does the one thing that turns a race from a story into a bug report: it reproduces each one on purpose, from a test, every time. The fixes start in part 2. 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 method

Six steps, the same for every part:

  1. Name the invariant. Not "the stock check works" but "the number of units sold never exceeds the number there were", a sentence that is true or false whatever the timing.
  2. Write a test that fires the action from several processes at the same instant and checks the invariant afterwards. Not a mock, not a sequence of calls in one process: real parallel requests against a real database.
  3. Watch it fail, then read the code for the shape that let it: a check followed by an act, or a read followed by a write, with nothing holding the world still in between.
  4. Fix it at the lowest layer that can hold the invariant. A unique index holds without any cooperation from the code; an atomic update holds without a lock; a lock holds if everyone takes it; a check in PHP holds for one process.
  5. Keep the test. It is the only proof that survives the next refactor.
  6. Audit for the damage already done, because the bug was there before the test was.

Steps 2 and 6 need tools, and most of this part is building them.

The shop, as written

ShopMini sells stationery: twenty-four products, three with stock in single digits, three coupons with a redemption limit, three gift cards with a balance. A shopper adds things to a session cart, checks out with an email and optionally a coupon code and a gift card code, and gets an order page. Payment is a gateway's job: it calls a signed webhook when the money clears, the order turns paid and a receipt goes out. An admin list shows the orders with an edit form for the status and an internal note. A scheduled command cancels orders that were never paid and puts their stock back.

The whole checkout is one method, and it reads like most checkouts do:

final class Checkout
{
    /** @param  array<int, int>  $items  product id => quantity */
    public function place(array $items, string $email, string $checkoutToken, ?string $couponCode = null, ?string $giftCardCode = null): Order
    {
        $products = Product::whereIn('id', array_keys($items))->get()->keyBy('id');

        $subtotal = 0;
        foreach ($items as $productId => $quantity) {
            $product = $products[$productId] ?? throw new CheckoutFailed('That product no longer exists.');
            if ($product->stock < $quantity) {
                throw new CheckoutFailed("Only {$product->stock} of {$product->name} left.");
            }
            $subtotal += $product->price_cents * $quantity;
        }

        $coupon = null;
        $discount = 0;
        if ($couponCode) {
            $coupon = Coupon::where('code', strtoupper($couponCode))->first()
                ?? throw new CheckoutFailed('That coupon does not exist.');
            if ($coupon->redemptions >= $coupon->max_redemptions) {
                throw new CheckoutFailed("Coupon {$coupon->code} has been fully redeemed.");
            }
            $discount = intdiv($subtotal * $coupon->percent_off, 100);
        }

        $card = null;
        $fromCard = 0;
        if ($giftCardCode) {
            $card = GiftCard::where('code', strtoupper($giftCardCode))->first()
                ?? throw new CheckoutFailed('That gift card does not exist.');
            if ($card->balance_cents <= 0) {
                throw new CheckoutFailed("Gift card {$card->code} has no balance left.");
            }
            $fromCard = min($card->balance_cents, $subtotal - $discount);
        }

        $total = $subtotal - $discount - $fromCard;

        $order = Order::create([
            'number' => OrderNumber::next(),
            'checkout_token' => $checkoutToken,
            'email' => $email,
            'status' => $total === 0 ? 'paid' : 'pending',
            // …totals, coupon_id, gift_card_id
        ]);

        foreach ($items as $productId => $quantity) {
            $product = $products[$productId];
            $order->items()->create(['product_id' => $product->id, 'quantity' => $quantity, 'unit_price_cents' => $product->price_cents]);
            $product->stock = $product->stock - $quantity;
            $product->save();
        }

        if ($coupon) {
            $coupon->redemptions = $coupon->redemptions + 1;
            $coupon->save();
        }

        if ($card) {
            $card->balance_cents = $card->balance_cents - $fromCard;
            $card->save();
        }

        SendOrderConfirmation::dispatch($order);

        return $order;
    }
}

The order number comes from a counter row:

final class OrderNumber
{
    public static function next(): string
    {
        $counter = Counter::firstOrCreate(['key' => 'order'], ['value' => 1000]);
        $counter->value = $counter->value + 1;
        $counter->save();

        return sprintf('SM-%d', $counter->value);
    }
}

And the webhook handler knows that gateways retry, so it checks for the event before it acts on it:

final class RecordPayment
{
    public function handle(array $event): string
    {
        if (PaymentEvent::where('event_id', $event['id'])->exists()) {
            return 'duplicate';
        }

        $order = Order::where('number', $event['order_number'])->firstOrFail();

        PaymentEvent::create(['event_id' => $event['id'], 'type' => $event['type'], 'payload' => $event]);

        if ($event['type'] === 'payment.succeeded') {
            $order->payments()->create(['event_id' => $event['id'], 'amount_cents' => $event['amount_cents']]);
            $order->update(['status' => 'paid', 'paid_at' => now()]);
            SendReceipt::dispatch($order);
        }

        return 'ok';
    }
}

Every line of this is tested, and every test passes: the stock check refuses a second unit when one is left, the coupon refuses its sixth use, the gift card covers what it can, the webhook handler says duplicate the second time it sees an event. Eleven tests, forty-five assertions, green. The suite runs the requests one after another, and one after another is the one order in which this code is correct.

Why it is wrong

Look at the stock check and the stock write. Between if ($product->stock < $quantity) and $product->save() there are a few milliseconds and a couple of queries, and during those milliseconds the database is not holding anything still. PHP-FPM runs this method in sixteen worker processes at once on this stack, each with its own copy of $product, each having read stock = 5 from the same row. All sixteen pass the check. All sixteen write back 4.

The same shape, a check followed by an act, is in the coupon limit and the gift card balance. A second shape, a read followed by a write of the same value, is in $counter->value + 1, $coupon->redemptions + 1, $card->balance_cents - $fromCard and $product->stock - $quantity: two processes read 1000, both write 1001, one increment is lost. The webhook handler has a third, an exists followed by an insert: two deliveries of the same event, both find nothing, both insert.

None of this is exotic. It is what the code says, run twice at the same time. The question is how to run it twice at the same time from a test.

A test that fires ten checkouts at once

Laravel ships a Concurrency facade whose default driver runs each closure in a separate PHP process, through php artisan invoke-serialized-closure, and collects what each returns. That is most of a race test: ten processes, one action, the database afterwards. The missing piece is timing. Each child process boots the framework, which takes a few hundred milliseconds and varies, so ten closures handed to Concurrency::run start spread out over a second and the actual work, a few milliseconds each, might not overlap at all. The fix is a starting gun: compute a moment a little in the future before spawning, and have every process spin until that moment before it does anything.

function gun(int $runners, Closure $task): array
{
    $task = new SerializableClosure(Closure::bind($task, null, null));
    $startAt = microtime(true) + 1.5;

    $tasks = [];
    for ($i = 0; $i < $runners; $i++) {
        $tasks[] = function () use ($startAt, $task) {
            while (microtime(true) < $startAt) {
                usleep(500);
            }
            try {
                return $task->getClosure()();
            } catch (Throwable $e) {
                return 'failed: '.$e->getMessage();
            }
        };
    }

    return Concurrency::run($tasks);
}

Three lines of that took longer than the rest of the part, and they are in the last section. With it, a race test is as short as the invariant it checks:

it('sells five units to ten buyers, and not one more', function () {
    $id = Product::factory()->stock(5)->create()->id;

    gun(10, fn () => Shopper::buy($id));

    expect(Order::count())->toBe(5)
        ->and(Product::find($id)->stock)->toBe(0);
});

Shopper::buy calls Checkout::place for one unit with a fresh checkout token; it lives in a class under tests/Support rather than as a helper function in the test file, because the child processes load only what Composer autoloads. The tests use DatabaseTruncation rather than RefreshDatabase: a row inside a test's transaction is invisible to every other connection, and other connections are the whole point.

Six invariants, one per race:

it('sells five units to ten buyers, and not one more');
it('lets a coupon with five uses be used five times');
it('never spends more than a gift card holds');
it('never issues the same order number twice');
it('turns one checkout into one order even when the button is pressed twice');
it('records one payment when the same event is delivered five times at once');

And a seventh that checks the tooling, because a race test that quietly ran its children against the development database would be worse than none: every runner reports the name of the database it connected to, and it must be testing.

They live in their own suite, tests/Race, which the default bin/dev test leaves out: defaultTestSuite="Unit,Feature" in phpunit.xml. The feature suite stays green through the series and the race suite turns green one part at a time. Here is where it starts:

$ bin/dev test --testsuite=Race

  ✓ it runs every runner against the test database                         3.95s
  ⨯ it sells five units to ten buyers, and not one more                    1.77s
  ⨯ it lets a coupon with five uses be used five times                     2.05s
  ⨯ it never spends more than a gift card holds                            2.14s
  ⨯ it never issues the same order number twice                            2.30s
  ⨯ it turns one checkout into one order even when the button is pressed…  2.04s
  ⨯ it records one payment when the same event is delivered five times…    2.05s

  Failed asserting that 10 is identical to 5.
  Failed asserting that 10 is identical to 5.
  Failed asserting that 14000 is equal to 2000 or is less than 2000.
  Failed asserting that actual size 2 matches expected size 10.
  Failed asserting that 2 is identical to 1.
  Failed asserting that 5 is identical to 1.

  Tests:    6 failed, 1 passed (10 assertions)

Ten buyers, five units, ten orders. Ten uses of a five-use coupon. A $20 gift card paid $140. Ten orders with two distinct numbers between them. One cart, two orders. One event, five payments. Every one, every run, in about two seconds each. That reliability is the gun's doing: without the shared start time the same suite fails some of its tests some of the time, which is exactly the behaviour that keeps races out of test suites.

The same races over HTTP

A test that calls Checkout::place directly proves the method races. It does not prove the shop does, through nginx, PHP-FPM, sessions and CSRF, with each shopper on their own cookie jar. k6 does, and it also produces the numbers that go in the audit.

Each scenario is a handful of lines over a shared library. Every virtual user gets its own session, adds the product to its cart, loads the checkout form for its tokens, and then waits for the same moment, which setup() chose three seconds after the start and handed to every VU:

const PRODUCT = __ENV.PRODUCT || 6; // PN-FTN-LE, Limited edition fountain pen, stock 5
export const options = raceOptions(Number(__ENV.VUS || 20));
const placed = new Counter('orders_placed');
const refused = new Counter('orders_refused');

export function setup() { return startIn(3); }

export default function ({ startAt }) {
  addToCart(PRODUCT);
  const form = checkoutForm();
  waitUntil(startAt);
  const result = placeOrder(form, `buyer${__VU}@example.com`);
  result.placed ? placed.add(1) : refused.add(1);
}

bin/dev race checkout runs it from the k6 container against the web service. Twenty shoppers, the last five fountain pens:

orders_placed..................: 20     6.215667/s
http_req_duration..............: min=13.25ms med=59.22ms p(95)=120.08ms max=199.88ms
http_reqs......................: 120    37.294002/s

Twenty orders placed, none refused, and a request took sixty milliseconds in the median. The window between the check and the write is a few of those milliseconds, and twenty requests across sixteen workers put plenty of them inside it.

The admin order list after the race: twenty orders of $89.00 for the fountain pen, all pending, sharing the numbers SM-1001, SM-1002 and SM-1003

The scoreboard

Step 6 of the method needs a way to see the damage, and the k6 counters only see what the shopper saw. shop:audit compares what the orders say happened with what the shelf says. For every product: the units the non-cancelled orders contain, against the stock it started with and the stock it has now. For every coupon: the orders that used it, against its limit and its counter. For every gift card: the cents the orders took from it, against what it held and what it holds. Then three counts: order numbers that appear on more than one order, checkout tokens that appear on more than one order, and orders with more than one payment.

After the checkout race:

Stock:                                   1
+-----------+-----+------+-----------+-------------+-------------+
| sku       | had | sold | stock now | oversold by | stock drift |
+-----------+-----+------+-----------+-------------+-------------+
| PN-FTN-LE | 5   | 20   | 3         | 15          | 18          |
+-----------+-----+------+-----------+-------------+-------------+
Coupons:                                 ok
Gift cards (cents):                      ok
Order numbers issued twice:              2
Carts that became more than one order:   ok
Orders paid more than once:              ok

4 problems.

Five pens, twenty sold, and the stock column says three are left, which is the number that would have been shown to the next shopper. Twenty read 5, each wrote back one less than what it read, and two of those writes were the last ones to land. The "oversold by" column is the number of customers who will get an apology; the "stock drift" column is how far the shelf's own count is from the truth, and it is larger, because the lost updates hide most of the sales.

The other four scenarios, each from a reset shop:

Scenario Shoppers What they share Orders placed Audit
coupon 20 FIRST5, five redemptions 20 20 orders used it, counter says 2, over by 15
giftcard 10 GC-BBBB, $20.00, for a $14.00 notebook 10 $140.00 spent by orders, balance now $6.00, overspent by $120.00
double-submit 5, each posting twice their own cart 10 5 carts became more than one order
webhook 5 deliveries of one event one paid order 1 payments_recorded: 5, 1 order paid more than once

The coupon counter is the most striking line. Twenty orders used the coupon and its own counter says two: the counter is behind by eighteen, the limit was enforced against a number that never got above two, and the shop will keep honouring a coupon that is fifteen uses past its limit until someone looks at the orders table. The gift card is the same bug with money: ten read $20.00, ten took $14.00, the balance went to $6.00 once, and the shop paid $120.00 of its own money.

The webhook scenario delivers the same signed event five times in flight together, which is what a gateway's retries look like when the first delivery was slow to answer. All five got ok. Five payment_events rows with one event id, five payments rows for one order, five receipts queued, and a handler that was written to prevent precisely this.

What the parts fix

Each race is a different shape, and each shape has a different lowest layer that can hold it.

  • Part 2, duplicates. The double submit and the repeated webhook: an insert that must happen once. A unique index is the layer, and the code has to be written to expect the index to say no.
  • Part 3, lost updates. The stock, the counter, the coupon counter, the gift card balance: a read and a write of the same value. Atomic updates where the database can do the arithmetic, conditional updates where the invariant can be a WHERE clause, lockForUpdate where the check needs several rows, and a version column for the admin form, which has the same bug with a human in the middle.
  • Part 4, isolation. What REPEATABLE READ does and does not promise, the gap locks that appear when part 3's locks meet an index, and the deadlock that two orders with the same two products produce, read from SHOW ENGINE INNODB STATUS.
  • Part 5, the queue. A job that runs twice, a scheduled command that overlaps itself, and the confirmation email dispatched inside a transaction that had not committed yet.

What went wrong

The child processes returned a closure instead of running one. The first version of gun() built its wrappers with array_map(fn () => function () use ($startAt, $task) { … }, range(1, $runners)), and every runner failed with Serialization of 'Closure' is not allowed, thrown from inside the child. Laravel's serializable closure finds a closure's source by file and line and takes the first closure on that line, which here was the arrow function, so the child received fn () => function () …, called it, got a closure back and tried to serialise that as the result. One closure per line, in a for loop, and the error went away. It is the kind of rule nothing documents until it bites.

A closure written in a Pest test belongs to the test class. Pest compiles each test file into a class the child processes do not have, so a task closure serialised from a test failed to unserialise with Class "P\Tests\Race\CheckoutRaceTest" not found. Closure::bind($task, null, null) drops both the bound $this and the scope before serialisation; the closure keeps its code and its captured variables, which is all it needs.

A helper function in the test file does not exist in the children. The first race tests called a buy() function declared next to them and every runner returned failed: Call to undefined function buy(), which the assertions reported as zero orders, which looked like a passing stock check. It is now Tests\Support\Shopper::buy(), autoloaded. The seventh test, the one that checks the database name, was added at the same time, because the next quiet failure would be the children connecting to the wrong database. They connect to the right one because PHPUnit sets its <env> entries in $_ENV and Symfony's Process passes $_ENV to the child; putenv() alone, which a quick probe used, does not carry across.

The first green suite was the trap. Eleven passing tests over code with six race conditions is the normal state of a Laravel application. Nothing in the method is a substitute for asking, of every check and every read-modify-write, what happens when this runs twice.

Part 2 takes the two duplicates, the double submit and the repeated webhook, and fixes them where the fix cannot be forgotten: Duplicates: double submits, repeated webhooks and the unique index.

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.