MySQL InnoDB Locking: Deadlocks, Gap Locks, and How to Avoid Them

InnoDB locks and deadlocks in WordPress: read the error, fix the order

“Deadlock found when trying to get lock; try restarting transaction” appears in a WordPress log mostly on busy WooCommerce shops and in plugins that update counters or custom tables in transactions. InnoDB detects the deadlock and rolls back one of the transactions, so the database is fine, but the request that lost fails. Understanding which locks InnoDB takes, and in which order the code takes them, is enough to fix most of them.

Problem: A shop’s stock sync plugin updates stock in a custom table and in wp_postmeta inside transactions. During sales, the log shows several deadlocks per hour, and some stock updates are lost.

Solution: Read the last deadlock with SHOW ENGINE INNODB STATUS, make all code paths lock rows in the same order (for example by ascending product ID), keep transactions short and free of HTTP calls, make sure the WHERE clauses use indexes so that InnoDB does not lock ranges, and retry a transaction that was chosen as the deadlock victim.

Read the last deadlock

SHOW ENGINE INNODB STATUS\G
-- ------------------------
-- LATEST DETECTED DEADLOCK
-- ------------------------
-- *** (1) TRANSACTION: ... UPDATE wp_ha_stock SET qty = qty - 1 WHERE product_id = 812
-- *** (1) HOLDS THE LOCK(S): ... index PRIMARY of table wp_ha_stock ... product_id 501
-- *** (2) TRANSACTION: ... UPDATE wp_ha_stock SET qty = qty - 2 WHERE product_id = 501
-- *** (2) HOLDS THE LOCK(S): ... product_id 812
-- *** WE ROLL BACK TRANSACTION (2)

The classic pattern: transaction 1 locked product 501 and waits for 812, transaction 2 locked 812 and waits for 501. Each holds what the other needs. With innodb_print_all_deadlocks = ON, MySQL writes every deadlock to the error log, not only the latest.

Fix 1: lock in a consistent order

function ha_reserve_stock( array $quantities ): void {
    global $wpdb;
    ksort( $quantities ); // always ascending product IDs

    $wpdb->query( 'START TRANSACTION' );
    foreach ( $quantities as $product_id => $qty ) {
        $wpdb->query( $wpdb->prepare(
            "UPDATE {$wpdb->prefix}ha_stock SET qty = qty - %d WHERE product_id = %d AND qty >= %d",
            $qty, $product_id, $qty
        ) );
        if ( 1 !== (int) $wpdb->rows_affected ) {
            $wpdb->query( 'ROLLBACK' );
            throw new RuntimeException( "Not enough stock for product {$product_id}" );
        }
    }
    $wpdb->query( 'COMMIT' );
}

When every transaction takes its locks in ascending ID order, two transactions can wait for each other, but never in a circle, so a deadlock cannot form between them. The condition qty >= %d inside the UPDATE makes the check and the change one atomic step instead of a SELECT followed by an UPDATE.

Fix 2: indexes, so InnoDB locks rows and not ranges

In the default isolation level (REPEATABLE READ), InnoDB locks the index records it scans, plus the gaps between them (gap locks) to prevent phantom rows. An UPDATE ... WHERE sku = 'X' without an index on sku scans and locks the whole table. With an index, it locks one record:

ALTER TABLE wp_ha_stock ADD UNIQUE KEY sku (sku);
EXPLAIN UPDATE wp_ha_stock SET qty = qty - 1 WHERE sku = 'MUG-BLUE';   -- key: sku, rows: 1

Unique index lookups for a single existing row take no gap locks at all. More on indexes: MySQL indexes for WordPress queries.

Fix 3: short transactions and a retry

Never call an external API, send email or do heavy PHP work between START TRANSACTION and COMMIT: the locks are held the whole time. And because a deadlock is a normal, recoverable event, retry the victim once or twice:

function ha_reserve_stock_with_retry( array $quantities, int $tries = 3 ): void {
    global $wpdb;
    for ( $attempt = 1; $attempt <= $tries; $attempt++ ) {
        try {
            ha_reserve_stock( $quantities );
            return;
        } catch ( RuntimeException $e ) {
            $deadlock = str_contains( (string) $wpdb->last_error, 'Deadlock found' );
            if ( ! $deadlock || $attempt === $tries ) {
                throw $e; // not enough stock, another error, or out of retries
            }
            usleep( random_int( 20000, 80000 ) ); // short random pause before the next try
        }
    }
}

$wpdb does not throw on SQL errors: a deadlocked UPDATE affects no rows, ha_reserve_stock() rolls back and throws, and $wpdb->last_error tells whether a deadlock was the reason. Only then is the whole transaction repeated; a real “not enough stock” is passed on at once. The random pause keeps two retrying requests from colliding again.

NOTE: Lock waits that end in “Lock wait timeout exceeded” (after innodb_lock_wait_timeout, 50 seconds by default) are a different problem: one transaction holds locks for too long. SELECT * FROM performance_schema.data_lock_waits (MySQL 8) shows who waits for whom while it happens. Slow queries that hold locks longer than needed: the MySQL slow query log.