High-Concurrency Stock Reservation & Flash Sale Overselling: Atomic Inventory Locking in WooCommerce

Illustration of high-velocity flash sale checkout traffic hitting an atomic MySQL database vault that locks WooCommerce inventory rows in ascending order.

A single-SKU flash sale compresses hours of demand into a few seconds. The woocommerce flash sale overselling race condition stock problem looks like a counting bug, but it is really a mismatch between how WooCommerce admits orders and how it decrements inventory. This guide covers the two-phase inventory architecture, a diagnostic workflow that identifies which ingestion path leaked stock, and a must-use plugin that closes those gaps with row-level locks.

The commercial impact of flash sale overselling

Overselling is not a cosmetic inventory error. Every unit sold beyond physical stock creates a chain of costs:

  • Manual refunds and support load. Someone has to cancel, refund, and apologize to each surplus buyer, usually while the sale is still trending.
  • Non-refundable gateway fees. Many payment processors keep the processing fee on a refunded transaction, so each oversold order is a direct margin loss.
  • Chargebacks. Customers who wait days for a cancellation often dispute the charge instead, adding dispute fees and putting the merchant account’s chargeback ratio at risk.
  • Brand damage. A “sold out after payment” email is remembered longer than the discount.
  • PHP-FPM worker exhaustion. On a single hot SKU, every concurrent checkout queues on the same InnoDB row lock. Workers sit blocked on the database, the pool saturates, and unrelated pages start returning 502 and 504 errors—similar to the worker pool saturation seen before configuring isolated Redis session locks for high-traffic concurrency.

The last point matters for how you fix the problem: a design that serializes too aggressively trades overselling for an outage. The solution below keeps lock scope minimal for that reason.

The AI hallucination vs. architectural reality

Generic troubleshooting advice, including much AI-generated advice, offers two explanations for flash sale overselling. Both misread WooCommerce core.

Myth 1: migrating to HPOS fixes product stock race conditions

High-Performance Order Storage (HPOS) moves orders into wp_wc_orders and its companion tables. Products do not move. The _stock value still lives in wp_postmeta, mirrored into wp_wc_product_meta_lookup, and the product record stays in wp_posts. Every code path that reserves or decrements inventory is unchanged by HPOS. It is worth enabling for order-table performance, but it does nothing for product inventory race conditions.

Myth 2: wc_maybe_reduce_stock_levels() is broken because it has no floor check

The function is unconditional by design. Nothing in the payment-time decrement prevents _stock from dropping below zero. Its job is to record a sale that has already been paid for, and it assumes the earlier reservation step has already rejected excess demand. Adding a floor check there would leave inventory out of step with money that has already changed hands. The protection belongs in the order-placement phase, and the bugs appear when an order reaches payment without passing through it.

WooCommerce’s two-phase inventory architecture

WooCommerce separates conditional reservation at order placement from unconditional decrement at payment completion.

Phase 1: order placement

wc_reserve_stock_for_order() delegates to Automattic\WooCommerce\Checkout\Helpers\ReserveStock, which runs an atomic statement of this shape:

INSERT INTO wp_wc_reserved_stock (order_id, product_id, stock_quantity, timestamp, expires)
SELECT ... FOR UPDATE

The wp_wc_reserved_stock atomic reservation mechanism creates temporary inventory holds through a conditional database operation that checks available stock before inserting or updating reservation records. This approach coordinates concurrent checkout attempts without immediately decrementing the product's _stock value, allowing WooCommerce to distinguish reserved inventory from completed sales.

Three properties matter:

  • The FOR UPDATE read serializes concurrent checkouts for the same product, so only as many reservations are inserted as there is stock to cover. This mechanism relies on InnoDB row-level locking (SELECT ... FOR UPDATE), a pessimistic concurrency control technique that locks the relevant inventory records during stock availability checks. Concurrent checkout transactions attempting to reserve the same product must coordinate through these database locks, preventing conflicting reservations from independently consuming the same available stock.
  • Core sorts cart items in ascending product_id order. Every transaction acquires its locks in the same order, which prevents AB-BA deadlocks on multi-item carts. This deterministic lock ordering is an important AB-BA deadlock prevention strategy. Without consistent ordering, one transaction could lock Product A before Product B while another locks Product B before Product A, creating a circular wait. Acquiring inventory locks in ascending product ID order reduces this risk, although other database operations can still introduce deadlocks.
  • Reservations count as active only while the owning order is in checkout-draft or pending status and the hold has not expired. They are released on payment completion, on a status transition (processing, on-hold, completed, or cancelled), or when checkout throws an exception.

Phase 2: payment completion

wc_maybe_reduce_stock_levels() decrements _stock in wp_postmeta and updates wp_wc_product_meta_lookup. It is guarded only by the order-level stock_reduced flag and the item-level _reduced_stock meta, which stop it from running twice for the same order (assuming you have also serialized concurrent callbacks against Stripe and PayPal webhook race conditions). It never asks whether stock is available.

A negative _stock value in wp_postmeta is therefore the forensic fingerprint of one of two events: an order reached payment completion without ever holding a valid row in wp_wc_reserved_stock, or an external system overwrote the stock value after checkouts had already decremented it.

The five ingestion pathways

Ingestion pathway / configuration vector Phase 1 reservation (wp_wc_reserved_stock) Phase 2 decrement (wc_maybe_reduce_stock_levels) Resulting storage and concurrency outcome
Standard storefront checkout (Hold Stock > 0) Acquires a FOR UPDATE lock on wp_postmeta in ascending product_id order and inserts a hold into wp_wc_reserved_stock. Unconditional decrement, guarded by the order-level stock_reduced flag and item-level _reduced_stock meta. _stock >= 0. Excess checkouts are refused before the shopper is sent to the payment gateway.
Hold Stock disabled (blank or 0 minutes) Skipped entirely. wc_reserve_stock_for_order() returns early without locking or inserting. All concurrent shoppers reach the gateway at once and each payment completion runs the unconditional decrement. _stock < 0. Severe overselling across concurrent payment completions.
Non-checkout channels (REST API, POS, admin, CSV import) Bypassed by default, unless a custom flow creates the order as pending and calls wc_reserve_stock_for_order() itself. Decrements _stock even when remaining inventory is zero or already held by web shoppers. _stock < 0. Cross-channel inventory leakage.
External ERP / multichannel absolute stock sync Unaware of active holds and in-flight checkouts. Writes an absolute stock value over recent decrements. Later order completions decrement from an artificially inflated baseline. Silent overselling. Requires delta-based updates, or subtracting reserved and unsynced quantities.
Single-SKU high-velocity flash sale Every concurrent checkout queues on the single post_id row lock in wp_postmeta during the FOR UPDATE read. Contention shifts from overselling to lock-wait exhaustion when surrounding transactions are long. InnoDB error 1205 lock-wait timeouts and slow checkouts, unless lock scope is kept minimal and admission is queued.

A few notes on each vector:

  • Hold Stock disabled. If WooCommerce > Settings > Products > Inventory > Hold stock (minutes) is blank or 0, the reservation step is skipped, and unlimited shoppers can enter the payment gateway for the last unit. This setting is often cleared by someone who wanted to stop pending orders from being auto-cancelled.
  • Non-checkout channels. Orders created through the REST API, WP-Admin, CSV imports, POS terminals, or marketplace connectors never traverse the storefront checkout lifecycle. Nothing calls wc_reserve_stock_for_order(), so payment completion drives _stock negative.
  • Absolute ERP sync. A connector that writes a set value instead of a delta overwrites any checkout decrement that happened after the ERP read its snapshot. The stock goes up silently, and the next sales decrement from the wrong baseline. This is a lost-update anomaly in ERP inventory sync, where an external inventory management system overwrites a more recent WooCommerce stock change using an outdated absolute inventory snapshot. Delta-based stock synchronization reduces this risk by applying relative inventory movements against the current database value rather than replacing it with stale stock quantities.
  • Single-SKU flash sale. With Hold Stock enabled the overselling is prevented, but every checkout queues on one index entry in wp_postmeta. The bottleneck moves from correctness to throughput.

The mechanics above are discussed in WooCommerce issue #45245, and the lookup table schema in issue #68552.

Flowchart comparing unreserved WooCommerce stock decrements and ERP set overwrites against enforced wp_wc_reserved_stock holds and sorted FOR UPDATE locks.

Diagnostic workflow

Audit a historical oversell in three steps: find products with negative _stock, trace the channel that created each contributing order, and confirm the Hold Stock setting and storage engine. Replace the wp_ prefix in the SQL with your own table prefix.

Query 1: find every product and variation with negative stock

-- Identify all products and variations that have suffered overselling.
SELECT
    pm.post_id                    AS product_id,
    p.post_title,
    p.post_type,
    p.post_parent,
    CAST(pm.meta_value AS SIGNED) AS current_stock,
    pml.stock_quantity            AS lookup_table_stock,
    pml.stock_status              AS lookup_stock_status
FROM wp_postmeta pm
INNER JOIN wp_posts p
        ON p.ID = pm.post_id
LEFT JOIN wp_wc_product_meta_lookup pml
       ON pml.product_id = pm.post_id
WHERE pm.meta_key = '_stock'
  AND p.post_type IN ('product', 'product_variation')
  AND CAST(pm.meta_value AS SIGNED) < 0
ORDER BY current_stock ASC;

A mismatch between current_stock and lookup_table_stock is a separate finding. It means something wrote to one store without updating the other.

Query 2: trace the creation channel of orders for an oversold ID

This query assumes HPOS tables. It pivots the line-item meta so you can see each order’s created_via, status, quantity, and whether stock was reduced. Substitute the oversold product or variation ID for 12345.

-- Trace order creation channels for an oversold product or variation.
SELECT
    o.id                                  AS order_id,
    o.status,
    od.created_via,
    o.date_created_gmt,
    od.date_paid_gmt,
    od.order_stock_reduced,
    oi.order_item_id,
    CAST(qty.meta_value AS DECIMAL(12,2)) AS line_qty,
    red.meta_value                        AS item_reduced_stock,
    rs.stock_quantity                     AS reserved_qty,
    rs.expires                            AS reservation_expires
FROM wp_woocommerce_order_items oi
INNER JOIN wp_wc_orders o
        ON o.id = oi.order_id
LEFT JOIN wp_wc_order_operational_data od
       ON od.order_id = o.id
INNER JOIN wp_woocommerce_order_itemmeta pid
        ON pid.order_item_id = oi.order_item_id AND pid.meta_key = '_product_id'
LEFT JOIN wp_woocommerce_order_itemmeta vid
       ON vid.order_item_id = oi.order_item_id AND vid.meta_key = '_variation_id'
LEFT JOIN wp_woocommerce_order_itemmeta qty
       ON qty.order_item_id = oi.order_item_id AND qty.meta_key = '_qty'
LEFT JOIN wp_woocommerce_order_itemmeta red
       ON red.order_item_id = oi.order_item_id AND red.meta_key = '_reduced_stock'
LEFT JOIN wp_wc_reserved_stock rs
       ON rs.order_id = o.id AND rs.product_id = 12345
WHERE oi.order_item_type = 'line_item'
  AND o.type = 'shop_order'
  AND (CAST(pid.meta_value AS UNSIGNED) = 12345
       OR CAST(vid.meta_value AS UNSIGNED) = 12345)
ORDER BY o.date_created_gmt DESC
LIMIT 50;

How to read the output:

  • Reservation rows are released when an order is paid, so a NULL in reserved_qty is normal for completed orders. The useful signals are created_via and timing.
  • Orders paid in the minutes before stock crossed zero with created_via set to rest-api, admin, or a POS or import connector point to the non-checkout vector.
  • A burst of checkout orders with overlapping date_paid_gmt values and a Hold Stock value of 0 points to the disabled-hold vector.
  • Pending orders that still show a live reservation_expires value are the holds currently protecting stock.
  • If the product has parent-managed stock, run the query again with the parent ID, because reservations are keyed to the stock-managing ID.

Verify Hold Stock and the InnoDB engine with WP-CLI

Row-level locking only works on InnoDB. A MyISAM table silently turns FOR UPDATE into table-level behavior or no locking at all.

#!/usr/bin/env bash
set -euo pipefail

# Drop --allow-root if you are not running WP-CLI as root.
PREFIX="$(wp db prefix --allow-root)"

echo "Hold stock (minutes):"
wp option get woocommerce_hold_stock_minutes --allow-root \
  || echo "(option not set; WooCommerce default applies)"

echo "Storage engines:"
wp db query "SELECT TABLE_NAME, ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN ('${PREFIX}postmeta', '${PREFIX}wc_reserved_stock', '${PREFIX}wc_product_meta_lookup');" --allow-root

An empty or 0 hold value means the reservation step is skipped. Any table reporting an engine other than InnoDB should be converted before you rely on anything below, for example with ALTER TABLE wp_wc_reserved_stock ENGINE=InnoDB; in a maintenance window.

Production-ready code solution: the AtomicInventoryManager must-use plugin

The plugin does three things:

  1. Forces a minimum 10-minute reservation window so Hold Stock can never be disabled in production.
  2. Enforces reservations on REST API order creation, so integrations get a 409 instead of an oversold order.
  3. Adds an atomic, row-locked availability check ahead of the payment-time decrement, and provides a delta-based method for ERP syncs.

Save it as wp-content/mu-plugins/atomic-inventory-manager.php.

<?php
/**
 * Plugin Name: Enterprise Atomic Stock Reservation & Oversell Guard
 * Description: Enforces stock reservations on REST/custom orders and guards payment decrements with atomic SQL locks.
 * Version: 1.0.0
 */

declare(strict_types=1);

namespace EnterpriseWC\InventoryConcurrency;

use Automattic\WooCommerce\Checkout\Helpers\ReserveStockException;
use Automattic\WooCommerce\Utilities\OrderUtil;
use WC_Order;
use WC_Order_Item_Product;
use WC_REST_Exception;
use WP_Error;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

final class AtomicInventoryManager {

    private const MIN_HOLD_MINUTES = 10;

    /** @var array<int,bool> Orders already blocked in this request (prevents note/status recursion). */
    private static array $blocked_orders = [];

    /**
     * Register inventory protection hooks across checkout and REST API channels.
     */
    public static function init(): void {
        // 1. Never let Hold Stock be disabled in production.
        add_filter( 'pre_option_woocommerce_hold_stock_minutes', [ self::class, 'enforce_minimum_hold_stock' ] );

        // 2. Reserve stock for orders created through the REST API.
        add_action( 'woocommerce_rest_insert_shop_order_object', [ self::class, 'reserve_stock_on_rest_order' ], 10, 3 );

        // 3. Guard payment-time stock reduction against unreserved orders.
        add_filter( 'woocommerce_can_reduce_order_stock', [ self::class, 'atomic_verify_before_decrement' ], 10, 2 );
    }

    /**
     * Guarantee a minimum reservation window when the option is blank, zero, or too low.
     *
     * Short-circuits get_option(). The stored value is read with this filter
     * temporarily removed to avoid infinite recursion.
     *
     * @param mixed $pre_option False unless another filter already supplied a value.
     * @return mixed
     */
    public static function enforce_minimum_hold_stock( $pre_option ) {
        if ( false !== $pre_option ) {
            return $pre_option;
        }

        remove_filter( 'pre_option_woocommerce_hold_stock_minutes', [ self::class, 'enforce_minimum_hold_stock' ] );
        $stored = get_option( 'woocommerce_hold_stock_minutes', 60 );
        add_filter( 'pre_option_woocommerce_hold_stock_minutes', [ self::class, 'enforce_minimum_hold_stock' ] );

        $minutes = is_numeric( $stored ) ? (int) $stored : 0;

        return (string) max( self::MIN_HOLD_MINUTES, $minutes );
    }

    /**
     * Reserve stock immediately when an order is created via the REST API.
     *
     * @param WC_Order $order    Newly inserted order object.
     * @param mixed    $request  REST request (unused).
     * @param bool     $creating True when the order is being created, false on update.
     * @throws WC_REST_Exception When the reservation fails due to insufficient inventory.
     */
    public static function reserve_stock_on_rest_order( WC_Order $order, $request = null, bool $creating = true ): void {
        if ( ! $creating || ! $order->has_status( [ 'pending', 'checkout-draft' ] ) ) {
            return;
        }

        try {
            wc_reserve_stock_for_order( $order );
        } catch ( ReserveStockException $e ) {
            $order->update_status( 'cancelled', 'Order cancelled: insufficient stock during REST reservation.' );

            throw new WC_REST_Exception(
                'woocommerce_rest_stock_reservation_failed',
                sanitize_text_field( $e->getMessage() ),
                409
            );
        }
    }

    /**
     * Row-locked availability check that runs before wc_reduce_stock_levels() decrements stock.
     *
     * @param bool     $can_reduce Whether stock can be reduced.
     * @param WC_Order $order      Order undergoing stock reduction.
     * @return bool
     */
    public static function atomic_verify_before_decrement( $can_reduce, $order ) {
        global $wpdb;

        if ( ! $can_reduce || ! $order instanceof WC_Order ) {
            return (bool) $can_reduce;
        }

        $items = $order->get_items( 'line_item' );
        if ( empty( $items ) ) {
            return true;
        }

        // Collect stock-managed IDs, skipping items already reduced or allowing backorders.
        $managed_requests = [];
        foreach ( $items as $item ) {
            if ( ! $item instanceof WC_Order_Item_Product || $item->get_meta( '_reduced_stock', true ) ) {
                continue;
            }

            $product = $item->get_product();
            if ( ! $product || ! $product->managing_stock() || $product->backorders_allowed() ) {
                continue;
            }

            $stock_id = (int) $product->get_stock_managed_by_id();
            $qty      = (int) apply_filters( 'woocommerce_order_item_quantity', $item->get_quantity(), $order, $item );

            $managed_requests[ $stock_id ] = ( $managed_requests[ $stock_id ] ?? 0 ) + $qty;
        }

        if ( empty( $managed_requests ) ) {
            return true;
        }

        // Ascending ID order: every transaction locks rows in the same sequence, so no deadlocks.
        ksort( $managed_requests, SORT_NUMERIC );

        $wpdb->query( 'START TRANSACTION' );

        foreach ( $managed_requests as $stock_id => $qty_needed ) {
            // Lock the exact _stock row via its indexed post_id + meta_key.
            $current_stock = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT CAST(meta_value AS SIGNED)
                     FROM {$wpdb->postmeta}
                     WHERE post_id = %d AND meta_key = '_stock'
                     FOR UPDATE",
                    $stock_id
                )
            );

            if ( null === $current_stock ) {
                continue; // No _stock row for this ID; nothing to guard.
            }

            $other_reserved = self::get_other_reserved_quantity( (int) $stock_id, $order->get_id() );
            $available      = (int) $current_stock - $other_reserved;

            if ( $available < $qty_needed ) {
                $wpdb->query( 'ROLLBACK' );
                self::block_order( $order, (int) $stock_id, (int) $qty_needed, $available );
                return false;
            }
        }

        $wpdb->query( 'COMMIT' );

        return true;
    }

    /**
     * Sum active, unexpired reservations held by orders other than the current one.
     *
     * Uses wp_wc_orders when HPOS is the authoritative order store, and falls back
     * to wp_posts when HPOS is disabled.
     */
    private static function get_other_reserved_quantity( int $stock_id, int $order_id ): int {
        global $wpdb;

        $reserved_table = $wpdb->prefix . 'wc_reserved_stock';
        $use_hpos       = class_exists( OrderUtil::class ) && OrderUtil::custom_orders_table_usage_is_enabled();

        if ( $use_hpos ) {
            $sql = "SELECT COALESCE(SUM(rs.stock_quantity), 0)
                FROM {$reserved_table} rs
                INNER JOIN {$wpdb->prefix}wc_orders o ON o.id = rs.order_id
                WHERE rs.product_id = %d
                  AND rs.order_id <> %d
                  AND rs.expires > NOW()
                  AND o.status IN ('wc-checkout-draft', 'wc-pending')";
        } else {
            $sql = "SELECT COALESCE(SUM(rs.stock_quantity), 0)
                FROM {$reserved_table} rs
                INNER JOIN {$wpdb->posts} p ON p.ID = rs.order_id
                WHERE rs.product_id = %d
                  AND rs.order_id <> %d
                  AND rs.expires > NOW()
                  AND p.post_status IN ('wc-checkout-draft', 'wc-pending')";
        }

        return (int) $wpdb->get_var( $wpdb->prepare( $sql, $stock_id, $order_id ) );
    }

    /**
     * Record the block on the order and move it to on-hold exactly once per request.
     *
     * Moving an order to on-hold fires wc_maybe_reduce_stock_levels() again, which
     * re-enters the guard. The static flag stops the duplicate note and status call.
     */
    private static function block_order( WC_Order $order, int $stock_id, int $qty_needed, int $available ): void {
        $order_id = $order->get_id();

        if ( ! empty( self::$blocked_orders[ $order_id ] ) ) {
            return;
        }
        self::$blocked_orders[ $order_id ] = true;

        $order->add_order_note(
            sprintf(
                'Atomic inventory guard blocked oversell on product ID #%d (requested: %d, available after holds: %d).',
                $stock_id,
                $qty_needed,
                $available
            )
        );
        $order->update_status( 'on-hold', 'Insufficient atomic stock during payment reconciliation.' );
    }

    /**
     * Apply a relative stock change from an ERP or 3PL instead of an absolute set_stock() call.
     *
     * The row lock on wp_postmeta serializes this write against checkout decrements,
     * so a concurrent sale is never overwritten.
     *
     * @param int $product_id Product or variation ID that manages stock.
     * @param int $delta      Positive or negative stock change.
     * @return int|WP_Error   Updated stock level, or an error.
     */
    public static function apply_erp_stock_delta( int $product_id, int $delta ) {
        global $wpdb;

        $wpdb->query( 'START TRANSACTION' );

        $current = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT CAST(meta_value AS SIGNED) FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_stock' FOR UPDATE",
                $product_id
            )
        );

        if ( null === $current ) {
            $wpdb->query( 'ROLLBACK' );
            return new WP_Error( 'invalid_stock_target', 'Product does not have initialized _stock meta.' );
        }

        $new_stock = (int) $current + $delta;
        $threshold = (int) get_option( 'woocommerce_notify_no_stock_amount', 0 );

        if ( $new_stock > $threshold ) {
            $new_status = 'instock';
        } else {
            $backorders = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_backorders'",
                    $product_id
                )
            );
            $new_status = in_array( $backorders, [ 'yes', 'notify' ], true ) ? 'onbackorder' : 'outofstock';
        }

        $stock_written = $wpdb->update(
            $wpdb->postmeta,
            [ 'meta_value' => (string) $new_stock ],
            [ 'post_id' => $product_id, 'meta_key' => '_stock' ],
            [ '%s' ],
            [ '%d', '%s' ]
        );

        $status_written = $wpdb->update(
            $wpdb->postmeta,
            [ 'meta_value' => $new_status ],
            [ 'post_id' => $product_id, 'meta_key' => '_stock_status' ],
            [ '%s' ],
            [ '%d', '%s' ]
        );

        $lookup_written = $wpdb->update(
            $wpdb->prefix . 'wc_product_meta_lookup',
            [
                'stock_quantity' => $new_stock,
                'stock_status'   => $new_status,
            ],
            [ 'product_id' => $product_id ],
            [ '%d', '%s' ],
            [ '%d' ]
        );

        if ( false === $stock_written || false === $status_written || false === $lookup_written ) {
            $wpdb->query( 'ROLLBACK' );
            return new WP_Error( 'stock_write_failed', 'Stock delta could not be written.' );
        }

        $wpdb->query( 'COMMIT' );

        // Direct SQL bypasses WordPress and WooCommerce caches; invalidate them explicitly.
        wp_cache_delete( $product_id, 'post_meta' );
        clean_post_cache( $product_id );
        wc_delete_product_transients( $product_id );
        wp_cache_delete( 'product-' . $product_id, 'products' );

        $parent_id = (int) wp_get_post_parent_id( $product_id );
        if ( $parent_id > 0 ) {
            wc_delete_product_transients( $parent_id );
        }

        return $new_stock;
    }
}

AtomicInventoryManager::init();

An ERP connector then sends movements, not snapshots:

<?php
// The ERP shipped 3 units out of the warehouse: apply -3, never "set stock to 42".
$result = \EnterpriseWC\InventoryConcurrency\AtomicInventoryManager::apply_erp_stock_delta( 4812, -3 );

if ( is_wp_error( $result ) ) {
    error_log( 'ERP stock delta failed: ' . $result->get_error_message() );
}

How each piece closes a vector

Minimum hold window. The pre_option_woocommerce_hold_stock_minutes filter short-circuits get_option(). The handler reads the stored value with itself unhooked, then returns the larger of the stored value and 10. A blank or 0 setting can no longer disable Phase 1, which closes the Hold Stock Disabled vector. Two side effects to know about: the settings screen will display the effective value, and because WooCommerce uses the same option to auto-cancel unpaid pending orders, manually created pending orders will now be cancelled after at least 10 minutes.

REST reservation. woocommerce_rest_insert_shop_order_object fires after the order is saved. For a new order in pending or checkout-draft status, the handler calls wc_reserve_stock_for_order(). When core throws ReserveStockException, the order is cancelled, which releases any partial hold, and a WC_REST_Exception with HTTP 409 is thrown. The REST controller converts that into a normal error response, so the integration sees a conflict instead of a created order. Orders created with set_paid already completed payment before this hook runs, so they are covered by the payment-time guard instead.

Payment-time guard. woocommerce_can_reduce_order_stock is checked inside wc_reduce_stock_levels(), so it runs for payment completion and for admin status changes that trigger a reduction. The guard works in this sequence:

  • Collect stock-managing IDs from line items, skipping items that already carry _reduced_stock and products that allow backorders.
  • Sort the IDs with ksort() so concurrent transactions always acquire locks in the same order.
  • Open a transaction and take SELECT ... FOR UPDATE on each _stock row.
  • Subtract unexpired reservations held by other pending or draft orders. The order’s own reservation is excluded because it is the demand being checked.
  • If current_stock - other_reserved < qty_needed, roll back, write an order note, move the order to on-hold, and return false so WooCommerce skips the decrement.

The reservation join uses wp_wc_orders when HPOS is the authoritative store and wp_posts otherwise, detected through OrderUtil.

ERP delta method. apply_erp_stock_delta() takes the same FOR UPDATE lock the guard uses, applies the change to the value currently in the database, and writes _stock, _stock_status, and wp_wc_product_meta_lookup inside one transaction. A checkout that decremented a second earlier is included in the baseline, which removes the lost-update problem of absolute syncs. The ERP must send true movements. Computing a delta as erp_snapshot - woocommerce_value reintroduces the same race.

Surviving the single-SKU lock queue

The guard and the reservation step both take a FOR UPDATE lock on one wp_postmeta row. That is correct, and on a hot SKU it is also a queue. To keep that queue from becoming an outage:

  • Keep transactions short. Nothing slow, such as HTTP calls, emails, or logging to remote services, should run between START TRANSACTION and COMMIT. The guard above does only indexed reads inside its transaction.
  • Gate excess demand before it reaches checkout. A waiting room or edge rate limit scoped to the sale URL, or a cap on concurrent checkouts for the SKU, keeps the number of workers waiting on the lock below the size of your PHP-FPM pool.
  • Size the pool for the sale. If the lock wait is a few hundred milliseconds, the workers needed to hold that traffic are several times what normal traffic requires.
  • Watch for error 1205 in the database log. It means requests are waiting longer than innodb_lock_wait_timeout allows, and the fix is admission control rather than a longer timeout. InnoDB Error 1205 (Lock wait timeout exceeded; try restarting transaction) occurs when a database operation waits longer than the configured innodb_lock_wait_timeout threshold to acquire a required lock. Unlike MySQL Error 1213 deadlocks in Action Scheduler queues, Error 1205 signals a lock wait timeout and should prompt investigation of long-running transactions, lock contention, and checkout request concurrency.

Rollout checklist and known limits

  • Test on staging with concurrency. Set a product to _stock = 5 and fire 50 concurrent REST order creations with a load tool. The expected result is five successes, 45 responses with HTTP 409, and _stock >= 0 afterward. Repeat with Hold Stock set to 0 to confirm the minimum is enforced.
  • Verify InnoDB first. The locking model assumes it.
  • Avoid nesting transactions. MySQL commits an open transaction when START TRANSACTION is issued. Do not call apply_erp_stock_delta() from code that is already inside its own transaction.
  • Understand what the guard covers. The lock protects the availability check. WooCommerce’s own decrement runs as a separate statement after the guard commits. Reservations make that window harmless for normal orders, because a competing unreserved completion still sees the first order’s hold. If you need strict serialization for unreserved channels, keep the transaction open until the woocommerce_reduce_order_stock action and commit there, with a shutdown fallback.
  • Plan for the on-hold queue. The guard prevents negative stock, but a blocked order may already have a captured payment. Give operations a view of guard-blocked orders and a refund or restock procedure.
  • Use relative sync everywhere. Every connector that can write _stock should use deltas, or go through apply_erp_stock_delta().

0 Comments