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

Concurrency9 min read

Isolation levels, gap locks and deadlocks, from the server's own records

What REPEATABLE READ promises and does not, read from a second connection: two kinds of read, the levels, the gap locks in performance_schema.data_locks, a deadlock in SHOW ENGINE INNODB STATUS, and two carts fixed first by retrying the transaction and then by taking the rows in one order.

By Abhishek Fouzdar

Part 3 made the race suite green with a transaction, two locking reads and a few conditional updates, and on the way met two deadlocks and a read that could not see a row that existed. Each of those is InnoDB doing exactly what it promises, and the promises are worth knowing before the next one. This part reads them off the server's own records: a second database connection that lets a test hold a transaction open and watch what another connection sees, performance_schema.data_locks for the locks a statement actually takes, SHOW ENGINE INNODB STATUS for the last deadlock, and the deadlock counter in innodb_metrics to measure a fix.

A second connection

Every race so far was reproduced with processes. For isolation questions a second connection in the same process is better, because the interleaving is then exact: this statement, then that one, then this one again. The config is a copy of the mysql connection under another name:

// config/database.php
'b' => [
    'driver' => 'mysql',
    // …the same host, database and credentials as 'mysql'
],

A test opens a transaction on the default connection, commits something on b, and asks the default connection what it sees:

it('keeps showing a transaction the stock it first read, whatever another connection commits', function () {
    $product = Product::factory()->stock(5)->create();

    DB::beginTransaction();
    $first = DB::table('products')->where('id', $product->id)->value('stock');

    DB::connection('b')->table('products')->where('id', $product->id)->decrement('stock', 3);

    $again = DB::table('products')->where('id', $product->id)->value('stock');
    $locking = DB::table('products')->where('id', $product->id)->lockForUpdate()->value('stock');
    DB::commit();

    expect([$first, $again, $locking])->toBe([5, 5, 2]);
});

Five, five, two. The plain read returns 5 before and after the other connection's committed change, and the locking read returns 2. That is the whole of REPEATABLE READ in one line, and it explains both of part 3's surprises.

Two kinds of read

InnoDB keeps old versions of rows in its undo log, and under REPEATABLE READ, its default, a transaction's plain SELECTs all read from a snapshot taken at the transaction's first read. Nothing committed after that moment is visible to them, however many times they run. This is a consistent read, and it is implemented without a single lock: readers never block writers and writers never block readers.

A locking read, SELECT … FOR UPDATE or … FOR SHARE, is different in kind. It reads the latest committed version of the row, takes a lock on it, and holds the lock until the transaction ends. So does every UPDATE and DELETE, which have to act on the row as it is rather than as it was:

it('evaluates an update against the current row, not the snapshot', function () {
    $product = Product::factory()->stock(1)->create();

    DB::beginTransaction();
    expect(DB::table('products')->where('id', $product->id)->value('stock'))->toBe(1);

    DB::connection('b')->table('products')->where('id', $product->id)->where('stock', '>=', 1)->decrement('stock');

    $taken = DB::table('products')->where('id', $product->id)->where('stock', '>=', 1)->decrement('stock');
    DB::commit();

    expect($taken)->toBe(0)->and($product->fresh()->stock)->toBe(0);
});

The transaction's snapshot says the stock is 1. The UPDATE … WHERE stock >= 1 changes nothing, because the row it evaluates is the current one, where the stock is 0. This is why part 3's conditional updates are correct under the default isolation level without any extra care: the WHERE of a write is always evaluated against the present.

And it is why createOrFirst failed in part 3. Its recovery is a plain read, so inside a transaction that had already read something, it read a snapshot from before the winner committed and found nothing. A locking read sees the present, which is what the recovery now uses. The rule from part 3 holds: claim first, or recover with a locking read.

The levels

Level Plain reads see Locking reads and writes
READ UNCOMMITTED Other transactions' uncommitted changes Current row
READ COMMITTED A fresh snapshot per statement: everything committed so far Current row, record locks only
REPEATABLE READ (InnoDB default) One snapshot per transaction, taken at its first read Current row, record locks and gap locks
SERIALIZABLE As REPEATABLE READ, and every plain read becomes a shared locking read Current row, record and gap locks

READ COMMITTED is what PostgreSQL defaults to and what many Laravel applications run MySQL at without knowing it, since the choice is a one-line setting on the connection: 'isolation_level' => 'READ COMMITTED' in config/database.php, which the MySQL connector turns into SET SESSION TRANSACTION ISOLATION LEVEL when the connection opens. Under it the first test reads five, then two:

it('sees the new value on every read under READ COMMITTED', function () {
    $product = Product::factory()->stock(5)->create();

    DB::statement('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
    DB::beginTransaction();
    $first = DB::table('products')->where('id', $product->id)->value('stock');

    DB::connection('b')->table('products')->where('id', $product->id)->decrement('stock', 3);

    $again = DB::table('products')->where('id', $product->id)->value('stock');
    DB::commit();

    expect([$first, $again])->toBe([5, 2]);
});

Neither level makes part 1's code correct. A read-modify-write loses updates under both, because the problem was never what the read saw; it was that the write did not depend on the row. The levels decide what a transaction's plain reads see, and the right-hand column of the table, the locks, is where they differ in ways that produce surprises.

The gap

Part 3 locked single rows by primary key. Lock a range instead and REPEATABLE READ locks more than the rows:

it('locks the gap when a locking read covers a range, so a new matching row has to wait', function () {
    $product = Product::factory()->create();
    app(Checkout::class)->place([$product->id => 1], '[email protected]', (string) Str::uuid());

    DB::beginTransaction();
    $pending = DB::table('orders')->where('status', 'pending')->lockForUpdate()->count();

    DB::connection('b')->statement('SET SESSION innodb_lock_wait_timeout = 1');
    $attempt = fn () => DB::connection('b')->table('orders')->insert([/* a new pending order */]);

    expect($pending)->toBe(1)
        ->and($attempt)->toThrow(QueryException::class, 'Lock wait timeout exceeded');

    DB::commit();
    expect($attempt())->toBeTrue();
});

Connection A locks "every pending order", of which there is one. Connection B tries to insert a second pending order, a row A has never seen, and waits until A commits. Under READ COMMITTED the same test, with the level changed, inserts straight away.

The reason is in performance_schema.data_locks, read from a third session while a transaction holds SELECT … WHERE status = 'pending' FOR UPDATE over ten pending orders:

object_name  index_name           lock_type  lock_mode      lock_data
orders       orders_status_index  RECORD     X              'pending', 1
orders       orders_status_index  RECORD     X              'pending', 2
…
orders       orders_status_index  RECORD     X              'pending', 10
orders       orders_status_index  RECORD     X              supremum pseudo-record
orders       PRIMARY              RECORD     X,REC_NOT_GAP  1
…
orders       PRIMARY              RECORD     X,REC_NOT_GAP  10
orders       NULL                 TABLE      IX             NULL

Two kinds of lock. On the primary key, X,REC_NOT_GAP: the row itself, nothing around it. On the status index, plain X, which in this table means a next-key lock: the index record and the gap before it. And the last one, supremum pseudo-record, is the gap after the last 'pending' entry, where a new pending order would be inserted. REPEATABLE READ takes these so that the locking read, repeated within the transaction, returns the same rows: nobody can slip a new pending order into the range while it is held. That is a guarantee against phantoms, and its price is that an insert into the range waits.

Three things follow. A locking read on a range holds everyone out of that range, not just the rows it found, for as long as the transaction lasts. A locking read on a column with no index has no index records to lock and locks every row and every gap in the table, which is the whole table. And READ COMMITTED takes none of these gap locks, except the ones that foreign keys and unique checks need, which is why a system that does a lot of range locking is often run at that level. ShopMini stays at the default: its locks are by primary key, and the one range read it has, the scheduler's cancellation of unpaid orders in part 5, is a plain read followed by updates by key.

Lock waits and deadlocks

A lock wait is a queue. B wanted a lock A held, so B waited, and A's commit released it. The wait has a limit, innodb_lock_wait_timeout, which is 50 seconds by default and five in this stack's my.cnf, after which B gets error 1205, Lock wait timeout exceeded; try restarting transaction, and its statement is rolled back. Fifty seconds is a long time for a PHP-FPM worker to hold a request open, and a transaction that holds a lock while it does something slow, an HTTP call to a payment provider say, can hold every worker in the pool behind it. The rule is older than Laravel: no I/O inside a transaction that holds locks.

A deadlock is a queue with a cycle in it, and InnoDB detects it the moment the cycle closes rather than waiting for a timeout. The race test that found one in this part is two carts with the same two products in opposite order:

it('serves ten carts that hold the same two products in alternating order', function () {
    $pen = Product::factory()->stock(10)->create()->id;
    $ruler = Product::factory()->stock(10)->create()->id;

    $results = gun(10, function () use ($pen, $ruler) {
        $items = getmypid() % 2 === 0 ? [$pen => 1, $ruler => 1] : [$ruler => 1, $pen => 1];

        return Shopper::buyMany($items);
    });

    expect(collect($results)->filter(fn ($r) => str_starts_with($r, 'failed'))->all())->toBe([])
        ->and(Order::count())->toBe(10)
        ->and(Product::find($pen)->stock)->toBe(0);
});

Half the runners failed with SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction, and the status page shows why:

*** (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` trx id 39943 lock_mode X locks rec but not gap
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS index PRIMARY of table `testing`.`products` trx id 39943 lock_mode X locks rec but not gap waiting
*** (2) TRANSACTION:
update `products` set `stock` = `stock` - 1 … where `products`.`id` = 2 and `stock` >= 1
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS index PRIMARY of table `testing`.`products` trx id 39944 lock_mode X locks rec but not gap
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS index PRIMARY of table `testing`.`products` trx id 39944 lock_mode X locks rec but not gap waiting
*** WE ROLL BACK TRANSACTION (2)

Transaction 39943 took the pen and wants the ruler; 39944 took the ruler and wants the pen. Neither can finish until the other does. InnoDB picks the one with less undo to discard, rolls it back, and hands its connection the error. The other proceeds as if nothing happened. SHOW ENGINE INNODB STATUS keeps only the latest; innodb_print_all_deadlocks = 1, set in this stack's my.cnf, writes every one to the error log, which is the setting to turn on in production before the first one happens.

Retry, then avoid

There are two responses, and ShopMini uses both. The first is to do what the error says and run the transaction again:

return DB::transaction(function () use (…) {
    // …
}, attempts: 3);

Laravel's transaction catches the exception, asks its concurrency error detector whether this was a deadlock or a lock wait timeout, and if so runs the closure again, up to the number of attempts. The closure has to be safe to run twice. Everything inside the transaction was rolled back, so the database side is; the order number is taken outside the transaction so a retry reuses the one the rolled-back attempt had; and the job dispatch at the end is the one thing that is not safe, which part 5 is about. With the retry alone the race test passes, and the deadlock counter in innodb_metrics says eight deadlocks were detected and retried during the run, which took five seconds instead of two.

The second response is to make the cycle impossible. A deadlock needs two transactions to take the same locks in different orders; take them in the same order and one simply waits for the other:

// Every checkout takes its product rows in the same order, so two carts with the
// same products cannot each hold one and wait for the other.
ksort($items);

With the items sorted by product id, three runs of the test detected zero deadlocks. Both lines stay: the ordering removes the deadlocks a checkout can cause on its own, and the retry covers the ones it cannot see coming, which in part 5 is a scheduled command returning stock in a different order from the checkouts taking it.

Over HTTP, ten shoppers buying the same two products in alternating order:

Orders placed Failed Deadlocks detected Audit
Before 6 4 4 no problems
After 10 0 0 no problems

The "before" audit is worth a look: four deadlocks, and the books balanced. A deadlock is a clean failure. The victim's transaction is rolled back whole, the shopper sees an error page, and nothing was taken. Of all the ways the shop has failed in this series it is the only one that never cost anything but a sale.

What went wrong

The first version of the lock-order test could not fail. It fired two carts in one order and then one cart in the other, a second later, and passed, and the deadlock counter did not move, because the carts were never in flight together. A race test that cannot fail proves nothing, and the first thing to check when one passes is whether it raced. The replacement fires ten at once with the order chosen by process id parity, and failed on the first run.

The deadlock counter counts since the server started. innodb_metrics reported 63 deadlocks before the first k6 run, all of them from part 3's test runs. Every number in this part is a difference between two readings.

FOR UPDATE on a range locked more than the test expected to explain. The lock table for ten pending orders had twenty-one record locks and the supremum, and the first attempt to describe it said "it locks the rows". It locks the rows, the gaps between the index entries and the gap after the last one, which is why the insert waited, and the test description was rewritten to say so. The records are the explanation; the prose has to follow them.

Part 5 leaves the request and goes to the queue, where the same bugs come back with different names: a job that runs twice, a scheduled command that overlaps itself, and a dispatch that beat its own commit: Jobs, workers and the scheduler racing each other.

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.