Race conditions in a Laravel app: reproduce them, then fix them · Part 5 of 5
Jobs, workers and the scheduler racing each other
Three queue races: a job queued for an order whose transaction rolled back, a confirmation sent twice because two workers ran the same job, and a cleanup that ran twice at once and cancelled everything twice. Fixed with after-commit dispatch and the same claims as the request side.
By Abhishek Fouzdar
Everything so far happened inside a request. The last part leaves the request for the queue and the scheduler, where the same bugs come back with different names and one new rule: the database is not the only place a race can hide. Three of them: a job that was queued for an order that never existed, a confirmation email sent twice because two workers ran the same job, and a cleanup command that ran twice at once and cancelled every order twice. Each is reproduced with the tools from part 1, which needed one more improvement to do it, and each is fixed with the tools from parts 2 to 4, which turn out to be enough.
A job that beat its own commit
Part 2 left this in the webhook handler on purpose, and part 3 put the same thing in the checkout:
return DB::transaction(function () use (…) {
// …create the order, take the stock
SendOrderConfirmation::dispatch($order);
return $order;
}, attempts: 3);
dispatch pushes the job to Redis immediately. The transaction commits a few statements later, or does not. Two things can go wrong, and the queue's two workers make both real. If a worker is idle, it pops the job before the commit, loads the order by id, and finds nothing: ModelNotFoundException, a failed job, and a retry that may or may not find the row depending on how fast the commit was. And if the transaction rolls back, the job is still in Redis, for an order that never existed, and every retry fails the same way.
The feature suite shows the second case with the real Redis queue, on a queue name no worker listens to so that the pushed jobs can be counted:
beforeEach(function () {
config(['queue.default' => 'redis', 'queue.connections.redis.queue' => 'tests']);
Redis::connection()->del('queues:tests', 'queues:tests:notify');
});
it('does not queue the confirmation for an order whose transaction rolled back', function () {
$product = Product::factory()->create();
try {
DB::transaction(function () use ($product) {
app(Checkout::class)->place([$product->id => 1], '[email protected]', (string) Str::uuid());
throw new RuntimeException('something after the checkout failed');
});
} catch (RuntimeException) {
}
expect(Order::count())->toBe(0)
->and(Queue::size('tests'))->toBe(0);
});
Failed asserting that 1 is identical to 0. No order, one job. The sync driver the rest of the suite uses cannot show this, because it runs the job inside dispatch(); the difference between "queued" and "queued after commit" only exists on a real queue.
The fix is a setting on the connection:
// config/queue.php
'redis' => [
// …
'after_commit' => true,
],
With it, a job dispatched inside a transaction is held by the connection until the outermost transaction commits, and dropped if it rolls back. Outside a transaction nothing changes. The same thing is available per job, SendOrderConfirmation::dispatch($order)->afterCommit(), or by implementing ShouldDispatchAfterCommit, and the connection-wide form is the one to want: a job that should run before its transaction commits is rare enough to ask for by name, with beforeCommit(). Events, mail and notifications have the same option. The test passes, the webhook's receipt is fixed by the same line, and the checkout's dispatch can stay where it reads best.
A job that ran twice
A queued job runs more than once whenever its first run did not end cleanly: it threw and was retried, the worker was killed mid-job, or, the one people forget, it ran longer than the connection's retry_after, which is 90 seconds by default, and a second worker picked it up while the first was still going. That last one is two workers running the same job at the same instant, and the confirmation email is what it looks like.
Here is the job as it stood, with the guard people write for it:
public function handle(): void
{
if ($this->order->confirmation_sent_at !== null) {
return;
}
Mail::to($this->order->email)->send(new OrderConfirmation($this->order));
$this->order->update(['confirmation_sent_at' => now()]);
$this->order->increment('confirmation_sends');
}
A check, then an act. Part 1's shape, in a worker instead of a request. The race test:
it('sends one confirmation when the same job runs on two workers at once', function () {
Queue::fake();
$product = Product::factory()->create();
$id = app(Checkout::class)->place([$product->id => 1], '[email protected]', (string) Str::uuid())->id;
$_ENV['MAIL_MAILER'] = 'smtp';
$runs = gun(2, function () use ($id) {
(new SendOrderConfirmation(Order::findOrFail($id)))->handle();
return 'ran';
});
unset($_ENV['MAIL_MAILER']);
expect(Order::findOrFail($id))->confirmation_sends->toBe(1)->confirmation_sent_at->not->toBeNull();
});
Two details in the setup are the subject of the last section. The result: Failed asserting that 2 is identical to 1. Two emails to one shopper, every run.
The fix is part 3's second tool, the invariant as a WHERE clause, with the mark taken before the work instead of after:
public function handle(): void
{
$claimed = Order::whereKey($this->order->id)->whereNull('confirmation_sent_at')->update(['confirmation_sent_at' => now()]);
if ($claimed === 0) {
return;
}
Mail::to($this->order->email)->send(new OrderConfirmation($this->order));
$this->order->increment('confirmation_sends');
}
One conditional update claims the order; the second worker's update changes zero rows and it leaves. The mark now means "someone is sending this" rather than "this was sent", which has a consequence: if the send fails after the claim, the retry finds the mark taken and does nothing, and the shopper gets no email. For a confirmation that is the better failure. For something that must eventually happen, the claim goes in a transaction with the work, as the webhook's does, so that a failure releases it.
Laravel has two middleware for the same job: WithoutOverlapping, an atomic lock in the cache keyed on the job, and ShouldBeUnique, which keeps a second copy off the queue while one is pending. Both are locks around the work rather than facts in the row, both depend on a cache store shared by every worker, and both expire. The row's own column cannot expire, cannot be on a different cache server, and is checked by the same database that holds the order. Use the middleware for jobs whose work has no row to mark; use the row when there is one.
A command that ran twice at once
shop:cancel-unpaid runs every minute, finds pending orders older than thirty minutes, cancels them and gives back what they took. Part 1 wrote it the way such commands are written:
foreach ($orders as $order) {
foreach ($order->items as $item) {
$item->product->stock = $item->product->stock + $item->quantity;
$item->product->save();
}
// …coupon, gift card
$order->update(['status' => 'cancelled']);
}
It runs twice at once in two ordinary situations: a run that takes longer than a minute, so the scheduler starts the next one beside it, and a second application server with its own scheduler. The race test runs two at once over twenty pending orders:
$runs = gun(2, function () {
Artisan::call('shop:cancel-unpaid');
return trim(Artisan::output());
});
$cancelledByRun = collect($runs)->map(fn ($out) => (int) filter_var($out, FILTER_SANITIZE_NUMBER_INT));
expect(Order::where('status', 'cancelled')->count())->toBe(20)
->and($cancelledByRun->sum())->toBe(20)
->and($product->fresh()->stock)->toBe(20);
runs: ["Cancelled 20 unpaid orders.","Cancelled 20 unpaid orders."]
Failed asserting that 40 is identical to 20.
Both runs cancelled all twenty and both gave the stock back, and an order with a coupon or a gift card would have had its redemption and its balance returned twice as well, which the audit lists as drift and a customer notices as a coupon that works again. The stock itself ended at 20 or 21 depending on the run, because the read-modify-write restores lost most of their own duplicates, which is the kind of luck that keeps this bug in production for years.
Two fixes, one in the schedule and one in the command, and the command's is the one that matters:
Schedule::command('shop:cancel-unpaid')->everyMinute()->withoutOverlapping()->onOneServer();
withoutOverlapping takes a cache lock for the duration of a run so the next minute's run skips if this one is still going; onOneServer takes a cache lock so that only one server runs it each minute. Both need a cache store every server shares, Redis here, and both are the right thing to have. Neither is a guarantee: a lock can expire under a long run, a cache can fail over, a deploy can run the command by hand while the scheduler runs it too. So the command itself claims each order the way the confirmation job claims the email:
$cancelled += (int) DB::transaction(function () use ($order) {
$claimed = Order::whereKey($order->id)->where('status', 'pending')->update(['status' => 'cancelled']);
if ($claimed === 0) {
return false;
}
foreach ($order->items->sortBy('product_id') as $item) {
Product::whereKey($item->product_id)->increment('stock', $item->quantity);
}
if ($order->coupon_id) {
Coupon::whereKey($order->coupon_id)->decrement('redemptions');
}
if ($order->gift_card_id) {
GiftCard::whereKey($order->gift_card_id)->increment('balance_cents', $order->gift_card_cents);
}
return true;
}, attempts: 3);
Pending to cancelled is a one-way door, and the conditional update lets exactly one run through it per order; the run that gets zero rows gives nothing back. The restores are atomic increments, in product order, for part 4's reason: a checkout taking the same products at the same time holds its locks in that order, and a cleanup returning them in cart order could deadlock it. The attempts: 3 covers whatever is left. The claim also catches a third party nobody planned for: a shopper who pays in the same second the cleanup runs, whose webhook turned the order to paid first, and whose order the cleanup now leaves alone.
On the development stack, twenty pending orders and two copies of the command started in the same instant:
$ bin/dev artisan shop:cancel-unpaid --minutes=0 & bin/dev artisan shop:cancel-unpaid --minutes=0
Cancelled 6 unpaid orders.
Cancelled 14 unpaid orders.
Before the fix both lines said twenty. Six and fourteen is what two runs sharing twenty orders should say, and shop:audit says no problems.
Workers hold the code they started with
Not a race, but the queue bug that cost the most during this series. A worker is a long-lived process that loaded the application once. Part 2 found 604 failed confirmation emails, every one with Call to undefined function money(): the helper had been added to Composer's autoload after the two worker containers started, and they were still running the autoloader from before it. The web requests had the function, because PHP-FPM loads the application per request. The workers did not, and would not until restarted.
php artisan queue:restart is the deploy step: it sets a timestamp in the cache that every worker checks after each job, and each one exits cleanly when it sees it, to be started again by whatever supervises it. A deploy that forgets it ships old code to the queue for as long as the workers live, which on a quiet queue is forever. --max-jobs and --max-time on queue:work bound that lifetime regardless.
The results
The race suite at the end of the series, three runs in a row:
✓ it runs every runner against the test database 3.45s
✓ it sells five units to ten buyers, and not one more 1.10s
✓ it lets a coupon with five uses be used five times 1.15s
✓ it never spends more than a gift card holds 1.79s
✓ it never issues the same order number twice 2.62s
✓ it turns one checkout into one order even when the button is pressed… 0.83s
✓ it serves ten carts that hold the same two products in alternating… 1.60s
✓ it sends one confirmation when the same job runs on two workers at… 1.04s
✓ it returns the stock of an unpaid order once when the cleanup runs… 1.87s
✓ it records one payment when the same event is delivered five times… 0.78s
Tests: 10 passed (24 assertions)
Ten invariants, every one of which was false in part 1 or in the first version of its fix, and a feature suite of twenty-two tests that stayed green through every part. The gun that fires them is sixty lines in tests/Pest.php.
What went wrong
The gun fired before everyone was at the line. Part 1's gun() chose a start time one and a half seconds ahead and had every process wait for it. With more containers running on the laptop by this part, a child process sometimes took longer than that to boot, arrived after the gun, and ran alone; the two-worker test passed every time because the two workers were never running together. The start is now a barrier: each process increments a key in Redis when it is ready and spins until the count reaches the number of runners. Each one also opens its database connection before reporting ready, because opening it afterwards put tens of milliseconds of jitter between runners, which is longer than the work they were meant to overlap. The whole race suite got faster too, since nobody waits for a fixed delay any more.
The confirmation had already been sent. With the barrier in place the two-worker test still passed, and a probe that returned each runner's timings showed why: both read confirmation_sent_at as already set, before either ran. The test placed its order through Checkout::place, which dispatches the job, and the test suite's sync queue ran it inside the dispatch. Queue::fake() around the order's creation keeps the confirmation unsent. A race test that passes is a test to be suspicious of, for the second time in this series.
The send was too quick to race. With the queue faked the test still passed under the array mailer, whose send takes microseconds; the gap between the check and the mark was shorter than the gap between the two runners. The test sets MAIL_MAILER=smtp in $_ENV for its children, which carries into them as part 1 found, and sends through Mailpit for real, about a hundred milliseconds, which is what a worker does. The race then failed on every run. A reproduction has to be as slow as production in the place that matters.
The cleanup test dropped the orders it had just created. The command's cutoff is created_at < now(), and the test's orders were created in the same second it ran, so a run that started in that second saw eighteen of twenty. The test backdates the orders by an hour and runs the command with its real thirty-minute default, which is also a more honest test of the command.
That is the series. The method from part 1 ran unchanged through five parts: name the invariant, fire the action from several processes at once, read the failure, fix at the lowest layer that holds, keep the test, audit. The layers, from the bottom: a unique index, an atomic update, an update with its condition in the WHERE, a locking read, a version column, a transaction with a retry, and only then a lock in the cache. The main post has the index and the numbers.
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
5 / 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