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

Concurrency8 min read

Duplicates: double submits, repeated webhooks and the unique index

Two of the races are about something that must exist once. The fix is a unique index and code that expects it to say no: createOrFirst, a claim before any side effect, a transaction that releases the claim on failure, and the migration that failed halfway because the bug had already left duplicates.

By Abhishek Fouzdar

Two of the six races in part 1 are about something that must exist exactly once: an order for a cart, and a payment record for a gateway event. Both had a check in the code, both checks passed for every request at once, and both were fixed in this part by the one layer that can promise "once" without asking the code to cooperate, a unique index, plus code written to expect the index to say no. Along the way: why firstOrCreate is a race and what Laravel does about it, what a transaction adds to a claim, and the migration that failed halfway because the bug it was fixing had already left its mark.

The shape

Here is the webhook handler's defence against duplicate deliveries, from part 1:

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]);

Five deliveries of one event, in flight together. Each asks "does this event exist?", each hears "no", because none of them has inserted yet. Each inserts. The check is correct about the world at the moment it ran and wrong about the world a millisecond later, and no amount of care in PHP changes that, because the five PHP processes do not know about each other. The only party that sees all five inserts is the database, and the only thing it can be told that covers all five is a constraint.

The double submit is the same shape without the check. Two POSTs with the same checkout token, two Order::create, two orders, and a checkout_token column that was recorded but never enforced.

Three indexes, three migrations

Three things in ShopMini must exist once: an order per checkout token, a number per order, and a record per gateway event. Each is one migration:

Schema::table('orders', function (Blueprint $table) {
    $table->dropIndex(['checkout_token']);
    $table->unique('checkout_token');
});
Schema::table('orders', function (Blueprint $table) {
    $table->dropIndex(['number']);
    $table->unique('number');
});
Schema::table('payment_events', function (Blueprint $table) {
    $table->dropIndex(['event_id']);
    $table->unique('event_id');
});

They were one migration at first, and the last section is about why they are three now.

The index on number is the odd one out. The order number is issued by a counter with a read-modify-write race, and that race is a lost update, which is part 3's subject, not a duplicate. The index does not fix it. What it does is change what the race produces: before, two orders quietly filed under one number; after, the second insert fails with Duplicate entry 'SM-1001' for key 'orders.orders_number_unique' and the shopper sees an error page. That is a worse experience for one shopper and a far better one for the shop, which now learns about the bug from its error tracker in the first hour instead of from a customer with someone else's invoice. Every uniqueness the business depends on should have an index whether or not the code is believed to be correct, for exactly this reason: the index turns a silent corruption into a loud failure.

Code that expects no

A unique index refuses the second insert by throwing. Code that wants the second request to behave well has to catch that and decide what "well" means. For the double submit, well means: the second click gets the same order the first click made. For the webhook, well means: the second delivery is told duplicate and nothing else happens.

The tempting tool is firstOrCreate, and it has the same bug as the handler above: a first(), then a create(), with the same gap between them. Laravel knows. Since the unique constraint exception was introduced, firstOrCreate runs its first() and then, instead of a plain create(), falls through to createOrFirst:

public function createOrFirst(array $attributes = [], Closure|array $values = [])
{
    try {
        return $this->withSavepointIfNeeded(fn () => $this->create(array_merge($attributes, value($values))));
    } catch (UniqueConstraintViolationException $e) {
        return $this->useWritePdo()->where($attributes)->first() ?? throw $e;
    }
}

Insert first. If the index says no, read the row that won, from the writer connection so that a lagging replica cannot say it is not there yet. If even that finds nothing, the violation was on a different index than the one being matched on, and the exception is rethrown. That last clause matters in ShopMini: a checkout whose token is new but whose number collides gets the rethrow, and the error page, which is the loud failure the previous section asked for.

withSavepointIfNeeded is for PostgreSQL, where a failed statement poisons the whole transaction until a rollback to a savepoint. MySQL carries on after a failed statement, so inside a MySQL transaction the catch is enough on its own.

Checkout: claim the token, then take the stock

The checkout now creates the order with createOrFirst on the token, and everything that takes from the shop happens only on the request that created it:

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

if (! $order->wasRecentlyCreated) {
    return $order;
}

foreach ($items as $productId => $quantity) {
    // take the stock, as before
}
// take the redemption and the balance, dispatch the confirmation, as before

wasRecentlyCreated is Eloquent's record of which branch createOrFirst took. The losing request returns the winner's order, the controller redirects to its page, and the shopper who pressed the button twice sees the same confirmation twice, which is the right thing for them to see. The order of operations is the whole fix: the claim comes before any side effect, so a lost claim costs nothing.

The checkout token was already there in part 1, generated once per cart and carried in a hidden field, which is why the fix was small. A token like this has a general name, an idempotency key: a value the client chooses before the request, so that a retry of the request carries the same value and the server can recognise it. Gateways and payment APIs ask for one on every request that moves money, under a header usually called Idempotency-Key, and store the first response under it so that a retry gets the same answer. The checkout token is the same idea at form scale. The gateway's event id is the same idea from the other direction.

Webhook: claim the event, inside a transaction

public function handle(array $event): string
{
    return DB::transaction(function () use ($event) {
        $claim = PaymentEvent::createOrFirst(['event_id' => $event['id']], ['type' => $event['type'], 'payload' => $event]);

        if (! $claim->wasRecentlyCreated) {
            return 'duplicate';
        }

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

        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';
    });
}

The claim is the insert of the event row, and the index lets exactly one through. The transaction adds two things.

First, a failure after the claim releases it. If the order lookup throws, or the payment insert does, the rollback removes the event row, the gateway gets a 5xx, and its next retry finds no claim and processes the event properly. Without the transaction the event row would stay, every retry would be told duplicate, and the payment would never be recorded. The feature suite has a test for exactly that: an event for an order number that does not exist gets a 404, and the same event id with the right number is then processed.

Second, the losers wait. When a transaction inserts a row with a unique key and a second transaction tries to insert the same key before the first commits, InnoDB does not return the duplicate error straight away: the second insert blocks until the first transaction commits or rolls back, and only then learns whether the key is taken. So the four duplicate deliveries are answered after the winning delivery has finished its work, not during it. A gateway that got duplicate can rely on the payment having been recorded.

There is one thing in that transaction that should not be there, and it is left in on purpose: SendReceipt::dispatch($order) runs before the transaction commits. If the commit were to fail, a worker could pick the job up for an order that is not paid, or that does not exist. Part 5 reproduces it and fixes it.

The results

The race suite after this part:

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

  Failed asserting that 1 is identical to 5.
  Failed asserting that 2 is identical to 5.
  Failed asserting that 5600 is equal to 2000 or is less than 2000.
  Failed asserting that 2 is identical to 10.

  Tests:    4 failed, 3 passed (10 assertions)

Two more green, and the four red ones fail differently from part 1. Ten buyers of five units used to produce ten orders; now they produce one or two, with the rest of the runners reporting Duplicate entry 'SM-1001' for key 'orders.orders_number_unique'. The exact count varies from run to run, because it depends on how many of the ten counter increments happened to land on distinct values. The oversell is gone for now, by accident, because most checkouts crash before they take stock. The gift card is still overspent by the few that get through. None of this is a fix; it is the unique index doing what the previous section promised, loudly.

Over HTTP, from a reset shop each time:

Scenario Shoppers Result Audit
webhook 5 deliveries of one event payments_recorded: 1, deliveries_called_duplicate: 4, p95 49 ms no problems
double-submit, one shopper 1, posting twice orders_placed: 2 (both clicks land on the order page), one order no problems
double-submit, five shoppers 5, each posting twice orders_placed: 2, requests_failed: 8 no duplicate orders, no problems
checkout 20, five pens orders_placed: 5, requests_failed: 15, p95 1.5 s stock now 2, drift 2

The five-shopper double submit is the honest row. The token fix works: no cart became two orders. But eight of the ten clicks failed, because five shoppers at the same instant collide on the counter, and the index on number refuses the collisions. The p95 of 1.5 seconds on the checkout row is the cost of rendering Laravel's debug error page fifteen times, not of the database. Part 3 fixes the counter and the stock, and the same scenarios come back with every click succeeding.

What went wrong

The migration failed halfway, and the second run failed differently. The three indexes were one migration at first. On the development database it stopped at the second with Duplicate entry 'SM-1001' for key 'orders.orders_number_unique': the part 1 races had already filed twenty orders under three numbers, and a unique index cannot be built over duplicates. MySQL cannot roll back a schema change, so the first index was in and the migration was recorded as not run. The next attempt stopped at the first line with Can't DROP 'orders_checkout_token_index'; check that column/key exists. Two lessons. A migration that adds a unique index is also an assertion about the data, and shop:audit had already listed the rows that would fail it, which is the step 6 of the method applied to a deploy. And one index per migration, so that a failure leaves a boundary a person can reason about rather than a state nobody wrote down. The development database was repaired by hand and the migration records with it, which is a sentence that should never be needed in production.

The queue workers were running code that did not exist any more. Every confirmation email since part 1 had failed with Call to undefined function money(): 604 entries in the log. The helper was added to Composer's autoload after the two worker containers had started, and a worker is a long-lived process that loaded the autoloader once. docker compose restart queue fixed it, php artisan queue:restart is the production form, and a deploy that forgets it ships old code to the queue for as long as the workers live. Part 5 has more to say about workers.

The k6 scenario counted failures as duplicates. Its first version put every response that was not ok under deliveries_called_duplicate, which during the broken migration counted four 500s as four well-behaved duplicates and printed "no problems" over a handler that had not run. A counter per outcome now, with the body of anything unexpected logged. Count the thing the assertion is about, not its complement.

Part 3 takes the four races that are still red, the stock, the coupon counter, the gift card and the order number, which are all one bug with four faces, a read followed by a write: Lost updates and oversold stock: atomic writes, locks and versions.

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.