Commit 109f105e8a0 for woocommerce

commit 109f105e8a0edc36aaf9a052941c2b89ea00884d
Author: Luigi Teschio <gigitux@gmail.com>
Date:   Fri Nov 20 17:21:44 2026 +0100

    Prevent concurrent Store API order update races (#71269)

    Forwardport of 560-gh-Automattic/woocommerce.

    Source PR head: ede47982a55e1077157e8c94436818f08474c750

    Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>

diff --git a/plugins/woocommerce/client/blocks/docs/third-party-developers/extensibility/hooks/actions.md b/plugins/woocommerce/client/blocks/docs/third-party-developers/extensibility/hooks/actions.md
index c22d42738dd..a9be95ed99a 100644
--- a/plugins/woocommerce/client/blocks/docs/third-party-developers/extensibility/hooks/actions.md
+++ b/plugins/woocommerce/client/blocks/docs/third-party-developers/extensibility/hooks/actions.md
@@ -44,7 +44,6 @@
 - [woocommerce_store_api_cart_errors](#woocommerce_store_api_cart_errors)
 - [woocommerce_store_api_cart_select_shipping_rate](#woocommerce_store_api_cart_select_shipping_rate)
 - [woocommerce_store_api_cart_update_customer_from_request](#woocommerce_store_api_cart_update_customer_from_request)
-- [woocommerce_store_api_cart_update_order_from_request](#woocommerce_store_api_cart_update_order_from_request)
 - [woocommerce_store_api_checkout_order_created](#woocommerce_store_api_checkout_order_created)
 - [woocommerce_store_api_checkout_order_processed](#woocommerce_store_api_checkout_order_processed)
 - [woocommerce_store_api_checkout_update_customer_from_request](#woocommerce_store_api_checkout_update_customer_from_request)
@@ -808,29 +807,6 @@ do_action( 'woocommerce_store_api_cart_update_customer_from_request', \WC_Custom

 ---

-## woocommerce_store_api_cart_update_order_from_request
-
-
-Fires when the order is synced with cart data from a cart route.
-
-```php
-do_action( 'woocommerce_store_api_cart_update_order_from_request', \WC_Order $draft_order, \WC_Customer $customer, \WP_REST_Request $request )
-```
-
-### Parameters
-
-| Argument | Type | Description |
-| -------- | ---- | ----------- |
-| $draft_order | \WC_Order | Order object. |
-| $customer | \WC_Customer | Customer object. |
-| $request | \WP_REST_Request | Full details about the request. |
-
-### Source
-
-- [StoreApi/Routes/V1/AbstractCartRoute.php](../../../../../../src/StoreApi/Routes/V1/AbstractCartRoute.php)
-
----
-
 ## woocommerce_store_api_checkout_order_created


diff --git a/plugins/woocommerce/includes/class-wc-checkout.php b/plugins/woocommerce/includes/class-wc-checkout.php
index 5598384e36b..0fb343f6f87 100644
--- a/plugins/woocommerce/includes/class-wc-checkout.php
+++ b/plugins/woocommerce/includes/class-wc-checkout.php
@@ -16,6 +16,7 @@ use Automattic\WooCommerce\Internal\Checkout\PaymentRecovery;
 use Automattic\WooCommerce\Internal\CostOfGoodsSold\CogsAwareTrait;
 use Automattic\WooCommerce\Internal\ProductVariations\SelectedVariationName;
 use Automattic\WooCommerce\Internal\Tax\TaxRateDataStore;
+use Automattic\WooCommerce\StoreApi\Utilities\OrderController;
 use Automattic\WooCommerce\Utilities\ShippingUtil;
 use Automattic\WooCommerce\StoreApi\Utilities\CartController;

@@ -465,8 +466,14 @@ class WC_Checkout {
 			return $order_id;
 		}

+		$order = null;
+
 		try {
-			$order_id           = absint( WC()->session->get( 'order_awaiting_payment' ) );
+			$order_id = absint( WC()->session->get( 'order_awaiting_payment' ) );
+			if ( $order_id && ! OrderController::lock_order( $order_id ) ) {
+				throw new Exception( esc_html( OrderController::get_order_lock_error_message() ) );
+			}
+
 			$cart_hash          = WC()->cart->get_cart_hash();
 			$cart_hashes        = $this->get_cart_section_hashes();
 			$available_gateways = WC()->payment_gateways->get_available_payment_gateways();
@@ -579,6 +586,11 @@ class WC_Checkout {
 			// Save the order.
 			$order_id = $order->save();

+			// This acquires the lock for a new order, or confirms ownership of a resumed order.
+			if ( ! OrderController::lock_order( $order_id ) ) {
+				throw new Exception( esc_html( OrderController::get_order_lock_error_message() ) );
+			}
+
 			// Defense-in-depth: if the cart still has items but the persisted order has none,
 			// the save silently dropped every line item (e.g. a $wpdb->insert() returning false
 			// in save_items()). Re-read the order from the data store so we check DB state, not
@@ -615,7 +627,7 @@ class WC_Checkout {

 			return $order_id;
 		} catch ( Exception $e ) {
-			if ( $order && $order instanceof WC_Order ) {
+			if ( $order instanceof WC_Order ) {
 				wc_release_coupons_for_order( $order );
 				/**
 				 * Action hook fired when an order is discarded due to Exception.
@@ -1533,10 +1545,15 @@ class WC_Checkout {
 	 * Process an order that does require payment.
 	 *
 	 * @since 3.0.0
+	 * @throws Exception When another request owns the order lock.
 	 * @param int    $order_id       Order ID.
 	 * @param string $payment_method Payment method.
 	 */
 	protected function process_order_payment( $order_id, $payment_method ) {
+		if ( ! OrderController::lock_order( absint( $order_id ), 0 ) ) {
+			throw new Exception( esc_html( OrderController::get_order_lock_error_message() ) );
+		}
+
 		$available_gateways = WC()->payment_gateways->get_available_payment_gateways();

 		if ( ! isset( $available_gateways[ $payment_method ] ) ) {
@@ -1586,10 +1603,14 @@ class WC_Checkout {
 	 * Process an order that doesn't require payment.
 	 *
 	 * @since 3.0.0
-	 * @throws Exception If the order is missing or a cancelled unpaid order would be marked paid.
+	 * @throws Exception If another request owns the order lock, the order is missing, or a cancelled unpaid order would be marked paid.
 	 * @param int $order_id Order ID.
 	 */
 	protected function process_order_without_payment( $order_id ) {
+		if ( ! OrderController::lock_order( absint( $order_id ), 0 ) ) {
+			throw new Exception( esc_html( OrderController::get_order_lock_error_message() ) );
+		}
+
 		$order = wc_get_order( $order_id );

 		if ( ! $order instanceof WC_Order ) {
diff --git a/plugins/woocommerce/includes/class-wc-session-handler.php b/plugins/woocommerce/includes/class-wc-session-handler.php
index 60a22e51e5a..b4572390f27 100644
--- a/plugins/woocommerce/includes/class-wc-session-handler.php
+++ b/plugins/woocommerce/includes/class-wc-session-handler.php
@@ -16,6 +16,7 @@ use Automattic\WooCommerce\Internal\Features\FeaturesController;
 use Automattic\WooCommerce\Internal\Session\SessionDataWriter;
 use Automattic\WooCommerce\Utilities\StringUtil;
 use Automattic\WooCommerce\StoreApi\Utilities\CartTokenUtils;
+use Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard;

 defined( 'ABSPATH' ) || exit;

@@ -59,6 +60,16 @@ class WC_Session_Handler extends WC_Session {
 	 */
 	protected $_table = ''; // phpcs:ignore PSR2.Classes.PropertyDeclaration.Underscore

+	/**
+	 * Whether the current core session read should bypass and refresh the object cache.
+	 *
+	 * This is enabled temporarily by get_session_data_from_storage() for checkout concurrency validation. Normal
+	 * session initialization and other reads continue using the cache.
+	 *
+	 * @var bool
+	 */
+	private bool $bypass_session_cache = false;
+
 	/**
 	 * Constructor for the session class.
 	 */
@@ -177,6 +188,7 @@ class WC_Session_Handler extends WC_Session {
 			$this->_customer_id = $this->generate_customer_id();
 			$this->_data        = $this->get_session_data();
 			$this->set_loaded_session_snapshot( $this->_data );
+			SessionConcurrencyGuard::capture( $this, $this->_data );
 			return;
 		}

@@ -262,6 +274,7 @@ class WC_Session_Handler extends WC_Session {
 	 */
 	private function restore_session_data() {
 		$session_data = $this->get_session_data();
+		SessionConcurrencyGuard::capture( $this, $session_data );

 		/**
 		 * Filters the session data when restoring from storage during initialization.
@@ -535,10 +548,10 @@ class WC_Session_Handler extends WC_Session {
 	}

 	/**
-	 * Get session data fresh from storage.
+	 * Get persisted session data through the normal cache-aware read path.
 	 *
-	 * This re-reads session data from the database rather than returning
-	 * in-memory data, ensuring the latest persisted state is returned.
+	 * The core handler may satisfy this read from the object cache. This is the normal path used when initializing
+	 * cookie sessions and by callers that do not require a fresh database value.
 	 *
 	 * @return array
 	 */
@@ -546,6 +559,26 @@ class WC_Session_Handler extends WC_Session {
 		return $this->has_session() ? (array) $this->get_session( $this->get_customer_id(), array() ) : array();
 	}

+	/**
+	 * Get the latest persisted session data for checkout concurrency validation.
+	 *
+	 * Core reads temporarily bypass and refresh the object cache for this call. Normal method dispatch is preserved,
+	 * so custom handlers continue using their own storage implementation.
+	 *
+	 * @since 11.3.0
+	 * @return array
+	 */
+	public function get_session_data_from_storage(): array {
+		$previous_bypass_state      = $this->bypass_session_cache;
+		$this->bypass_session_cache = true;
+
+		try {
+			return $this->get_session_data();
+		} finally {
+			$this->bypass_session_cache = $previous_bypass_state;
+		}
+	}
+
 	/**
 	 * Gets a cache prefix. This is used in session names so the entire cache can be invalidated with 1 function call.
 	 *
@@ -578,6 +611,7 @@ class WC_Session_Handler extends WC_Session {

 			// Later saves in this request compare against this request's own data, so they merge again.
 			$this->set_loaded_session_snapshot( $this->_data );
+			SessionConcurrencyGuard::capture( $this, $this->_data );
 			$this->_dirty = false;

 			/**
@@ -616,6 +650,7 @@ class WC_Session_Handler extends WC_Session {
 		$this->_customer_id = $this->generate_customer_id();
 		$this->_has_cookie  = false;
 		$this->replace_session_on_save();
+		SessionConcurrencyGuard::capture( $this, array() );
 	}

 	/**
@@ -675,8 +710,8 @@ class WC_Session_Handler extends WC_Session {
 			return $default_value;
 		}

-		// Try to get it from the cache, it will return false if not present or if object cache not in use.
-		$value = wp_cache_get( $this->get_cache_prefix() . $customer_id, WC_SESSION_CACHE_GROUP );
+		// Normal reads use the cache. Checkout concurrency validation temporarily bypasses it to compare fresh persisted data.
+		$value = $this->bypass_session_cache ? false : wp_cache_get( $this->get_cache_prefix() . $customer_id, WC_SESSION_CACHE_GROUP );

 		if ( false === $value ) {
 			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted table name.
@@ -688,7 +723,12 @@ class WC_Session_Handler extends WC_Session {

 			$cache_duration = $this->_session_expiration - time();
 			if ( 0 < $cache_duration ) {
-				wp_cache_add( $this->get_cache_prefix() . $customer_id, $value, WC_SESSION_CACHE_GROUP, $cache_duration );
+				$cache_key = $this->get_cache_prefix() . $customer_id;
+				if ( $this->bypass_session_cache ) {
+					wp_cache_set( $cache_key, $value, WC_SESSION_CACHE_GROUP, $cache_duration );
+				} else {
+					wp_cache_add( $cache_key, $value, WC_SESSION_CACHE_GROUP, $cache_duration );
+				}
 			}
 		}

diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index a1c11b2ab27..4945ba5a204 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -65275,7 +65275,7 @@ parameters:
 		-
 			message: '#^Access to protected property Automattic\\WooCommerce\\StoreApi\\Payments\\PaymentResult\:\:\$status\.$#'
 			identifier: property.protected
-			count: 2
+			count: 1
 			path: src/StoreApi/Routes/V1/Checkout.php

 		-
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/AbstractCartRoute.php b/plugins/woocommerce/src/StoreApi/Routes/V1/AbstractCartRoute.php
index 93cda02af2b..c431cb1c015 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/AbstractCartRoute.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/AbstractCartRoute.php
@@ -155,7 +155,6 @@ abstract class AbstractCartRoute extends AbstractRoute {
 			}
 		}

-		// For successful update requests, recalculate cart totals and sync draft orders with the current cart.
 		if ( $this->is_update_request( $request ) && ! is_wp_error( $response ) ) {
 			$this->cart_updated( $request );
 		}
@@ -271,44 +270,14 @@ abstract class AbstractCartRoute extends AbstractRoute {
 	}

 	/**
-	 * Triggered after an update to cart data. Re-calculates totals and updates draft orders (if they already exist) to
-	 * keep all data in sync.
+	 * Triggered after a successful update to cart data.
+	 *
+	 * Cart routes no longer synchronize draft orders. The method remains so route subclasses can react to updates.
+	 * Checkout synchronizes the authoritative cart state immediately before placing an order.
 	 *
 	 * @param \WP_REST_Request $request Request object.
 	 */
-	protected function cart_updated( \WP_REST_Request $request ) {
-		$draft_order = $this->get_draft_order();
-
-		if ( $draft_order ) {
-			// This does not trigger a recalculation of the cart--endpoints should have already done so before returning
-			// the cart response.
-			$this->order_controller->update_order_from_cart( $draft_order, false );
-
-			wc_do_deprecated_action(
-				'woocommerce_blocks_cart_update_order_from_request',
-				array(
-					$draft_order,
-					$request,
-				),
-				'7.2.0',
-				'woocommerce_store_api_cart_update_order_from_request',
-				'This action was deprecated in WooCommerce Blocks version 7.2.0. Please use woocommerce_store_api_cart_update_order_from_request instead.'
-			);
-
-			/**
-			 * Fires when the order is synced with cart data from a cart route.
-			 *
-			 * @since 7.2.0
-			 *
-			 * @param \WC_Order $draft_order Order object.
-			 * @param \WC_Customer $customer Customer object.
-			 * @param \WP_REST_Request $request Full details about the request.
-			 */
-			do_action( 'woocommerce_store_api_cart_update_order_from_request', $draft_order, $request );
-
-			$this->forget_draft_order_if_not_saved( $draft_order );
-		}
-	}
+	protected function cart_updated( \WP_REST_Request $request ) {}

 	/**
 	 * For non-GET endpoints, require and validate a nonce to prevent CSRF attacks.
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/CartRemoveItem.php b/plugins/woocommerce/src/StoreApi/Routes/V1/CartRemoveItem.php
index 292cddd0fbd..5a108efa7ed 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/CartRemoveItem.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/CartRemoveItem.php
@@ -2,6 +2,7 @@
 namespace Automattic\WooCommerce\StoreApi\Routes\V1;

 use Automattic\WooCommerce\StoreApi\Utilities\DraftOrderTrait;
+use Automattic\WooCommerce\StoreApi\Utilities\OrderController;
 use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;

 /**
@@ -100,7 +101,7 @@ class CartRemoveItem extends AbstractCartRoute {
 	protected function maybe_release_stock() {
 		$draft_order_id = $this->get_draft_order_id();

-		if ( ! $draft_order_id ) {
+		if ( ! $draft_order_id || ! OrderController::lock_order( $draft_order_id, 0 ) ) {
 			return;
 		}

diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
index 41b9d021737..2b7b62b3969 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
@@ -7,6 +7,8 @@ use Automattic\WooCommerce\StoreApi\Payments\PaymentResult;
 use Automattic\WooCommerce\StoreApi\Exceptions\InvalidCartException;
 use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
 use Automattic\WooCommerce\StoreApi\Utilities\DraftOrderTrait;
+use Automattic\WooCommerce\StoreApi\Utilities\OrderController;
+use Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard;
 use Automattic\WooCommerce\Checkout\Helpers\ReserveStockException;
 use Automattic\WooCommerce\StoreApi\Utilities\CheckoutTrait;
 use Automattic\WooCommerce\Internal\Checkout\PaymentRecovery;
@@ -160,6 +162,7 @@ class Checkout extends AbstractCartRoute {
 	 *
 	 * @param \WP_REST_Request $request Request object.
 	 *
+	 * @throws RouteException If the persisted session changed after this request loaded it.
 	 * @return \WP_REST_Response
 	 */
 	public function get_response( \WP_REST_Request $request ) {
@@ -180,6 +183,10 @@ class Checkout extends AbstractCartRoute {

 		if ( ! $response ) {
 			try {
+				// Every method of this route reads and writes the draft order, so take it before anything reads it.
+				$this->lock_order_or_throw( absint( $this->get_draft_order_id() ) );
+				// The session was loaded before the lock. Refuse externally persisted changes rather than overwrite a newer draft and potentially complete the wrong total.
+				$this->throw_if_persisted_session_changed();
 				$response = $this->get_response_by_request_method( $request );
 			} catch ( InvalidCartException $error ) {
 				$response = $this->get_route_error_response_from_object( $error->getError(), $error->getCode(), $error->getAdditionalData() );
@@ -702,6 +709,16 @@ class Checkout extends AbstractCartRoute {
 			'This action was deprecated in WooCommerce Blocks version 7.2.0. Please use woocommerce_store_api_checkout_order_processed instead.'
 		);

+		// The order is placed from here on as it was validated above, so make sure no other request could have written
+		// to it in the meantime. This also takes the lock for an order that was only created by this request.
+		if ( ! OrderController::lock_order( $this->order->get_id() ) ) {
+			throw new RouteException(
+				'woocommerce_rest_checkout_order_locked',
+				esc_html( OrderController::get_order_lock_error_message() ),
+				409
+			);
+		}
+
 		// Set initial status to 'pending'; woocommerce_store_api_checkout_order_processed (fired below) can override it.
 		// Custom statuses are preserved when no payment is needed; payment gateway statuses take precedence otherwise.
 		$this->order->update_status( 'pending' );
@@ -1190,6 +1207,44 @@ class Checkout extends AbstractCartRoute {
 		);
 	}

+	/**
+	 * Refuse to use a session that another request changed after this request loaded it.
+	 *
+	 * Mutations made by this request are allowed because the session handler compares the latest persisted data with
+	 * the persisted data that initialized this request, not with its current in-memory data.
+	 *
+	 * @throws RouteException If another request changed the persisted session.
+	 */
+	private function throw_if_persisted_session_changed(): void {
+		if ( WC()->session && SessionConcurrencyGuard::has_changed( WC()->session ) ) {
+			throw new RouteException(
+				'woocommerce_rest_checkout_session_changed',
+				esc_html__( 'Your cart changed during checkout. Please review it and try again.', 'woocommerce' ),
+				409
+			);
+		}
+	}
+
+	/**
+	 * Give this request exclusive use of an order, or confirm that it still has it, and refuse the request otherwise.
+	 *
+	 * Checkout and other order writers must hold the same lock so an order cannot change between validation and placement.
+	 *
+	 * @see OrderController::lock_order()
+	 *
+	 * @throws RouteException If another request is using the order. Returns HTTP 409 with the cart so the client can refresh.
+	 * @param int $order_id Order ID.
+	 */
+	private function lock_order_or_throw( int $order_id ): void {
+		if ( ! OrderController::lock_order( $order_id ) ) {
+			throw new RouteException(
+				'woocommerce_rest_checkout_order_locked',
+				esc_html( OrderController::get_order_lock_error_message() ),
+				409
+			);
+		}
+	}
+
 	/**
 	 * This validates if the order can be placed regarding settings in WooCommerce > Settings > Accounts & Privacy
 	 * If registration during checkout is disabled, guest checkout is disabled and the user is not logged in, prevent checkout.
diff --git a/plugins/woocommerce/src/StoreApi/SessionHandler.php b/plugins/woocommerce/src/StoreApi/SessionHandler.php
index a376fbf67d6..62daebd9a68 100644
--- a/plugins/woocommerce/src/StoreApi/SessionHandler.php
+++ b/plugins/woocommerce/src/StoreApi/SessionHandler.php
@@ -6,6 +6,7 @@ namespace Automattic\WooCommerce\StoreApi;
 use Automattic\Jetpack\Constants;
 use Automattic\WooCommerce\Internal\Session\SessionDataWriter;
 use Automattic\WooCommerce\StoreApi\Utilities\CartTokenUtils;
+use Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard;
 use WC_Session;
 defined( 'ABSPATH' ) || exit;

@@ -54,6 +55,7 @@ final class SessionHandler extends WC_Session {
 	 */
 	public function init() {
 		$this->init_session_from_token();
+		SessionConcurrencyGuard::capture( $this, $this->_data );
 		add_action( 'shutdown', array( $this, 'save_data' ), 20 );
 	}

@@ -172,6 +174,7 @@ final class SessionHandler extends WC_Session {
 		$this->_dirty       = false;
 		$this->_customer_id = null;
 		$this->replace_session_on_save();
+		SessionConcurrencyGuard::capture( $this, array() );
 	}

 	/**
@@ -205,6 +208,7 @@ final class SessionHandler extends WC_Session {
 			}

 			$this->set_loaded_session_snapshot( $this->_data );
+			SessionConcurrencyGuard::capture( $this, $this->_data );
 			$this->_dirty = false;
 		}
 	}
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/OrderController.php b/plugins/woocommerce/src/StoreApi/Utilities/OrderController.php
index b72f307cdb7..2d5238f4363 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/OrderController.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/OrderController.php
@@ -28,6 +28,48 @@ class OrderController {
 	 */
 	private const LOCATION_FIELDS = [ 'country', 'state', 'postcode', 'city' ];

+	/**
+	 * Prefix of the option name used as a self-expiring mutex around an order. The order ID is appended.
+	 *
+	 * The row holds the lock's release time (a microtime float); its mere existence is the lock. It lives in the
+	 * options table for the reasons given on BatchProcessingController::ENQUEUED_PROCESSORS_LOCK_OPTION.
+	 *
+	 * @since 11.3.0
+	 */
+	const ORDER_LOCK_OPTION_PREFIX = 'wc_store_api_order_lock_';
+
+	/**
+	 * How long (in seconds) a held order lock stays valid before it is considered stale and can be taken over.
+	 *
+	 * Locks are released when the request ends, so this only bounds how long a lock left behind by a request that
+	 * died without running its shutdown hooks keeps the order out of reach. A request that may have outlived its
+	 * lock confirms it with lock_order() before relying on it.
+	 *
+	 * @since 11.3.0
+	 */
+	const ORDER_LOCK_TTL = 60;
+
+	/**
+	 * How long (in seconds) lock_order() waits by default for a lock held by another request.
+	 *
+	 * @since 11.3.0
+	 */
+	const ORDER_LOCK_TIMEOUT = 10;
+
+	/**
+	 * Orders locked by the current request, as order ID => stored release time.
+	 *
+	 * @var array<int, string>
+	 */
+	private static array $order_locks = array();
+
+	/**
+	 * Shutdown callback that releases locks held by this request.
+	 *
+	 * @var \Closure|null
+	 */
+	private static ?\Closure $unlock_orders_on_shutdown = null;
+
 	/**
 	 * Checkout fields controller.
 	 *
@@ -144,6 +186,154 @@ class OrderController {
 		}
 	}

+	/**
+	 * Get the shopper-facing message used when another request holds an order lock.
+	 *
+	 * @since 11.3.0
+	 *
+	 * @return string
+	 */
+	public static function get_order_lock_error_message(): string {
+		return __( 'Your order is still being processed by another request. Please try again.', 'woocommerce' );
+	}
+
+	/**
+	 * Give the current request exclusive use of an order until the request ends, or confirm that it still has it.
+	 *
+	 * Checkout flows use this lock to serialize reads and mutations of a shared order. Cart routes may also use it
+	 * for order-specific side effects, such as releasing reserved stock. Callers acquire the lock before relying on
+	 * order state so that another request cannot change the order after validation and before placement or payment.
+	 *
+	 * The claim is an atomic INSERT of an options row (which fails if the row already exists, making it a mutex);
+	 * if the row exists but its stored release time has already passed, a conditional UPDATE takes the stale lock
+	 * over. Modeled on BatchProcessingController::acquire_enqueued_processors_lock(). A request that already holds
+	 * the lock atomically renews the row only while its ownership value still matches, so the call is safe to repeat,
+	 * for instance from every part of a batch request.
+	 *
+	 * @since 11.3.0
+	 *
+	 * @param int $order_id Order ID. There is nothing to lock when this is 0.
+	 * @param int $timeout  How long (in seconds) to wait for a lock held by another request.
+	 * @return bool True if the lock is held by this request. False if another request holds it, or took it over
+	 *              from this request after the lock went stale.
+	 */
+	public static function lock_order( int $order_id, int $timeout = self::ORDER_LOCK_TIMEOUT ): bool {
+		global $wpdb;
+
+		if ( $order_id <= 0 ) {
+			return true;
+		}
+
+		$option_name = self::ORDER_LOCK_OPTION_PREFIX . $order_id;
+
+		if ( isset( self::$order_locks[ $order_id ] ) ) {
+			$owned_expiry = self::$order_locks[ $order_id ];
+			$time         = microtime( true );
+			$expiry       = number_format( max( $time + self::ORDER_LOCK_TTL, (float) $owned_expiry + 0.000001 ), 6, '.', '' );
+
+			// Renew only if the row still contains this request's ownership value. If an expired lease and its owner
+			// race to update the row, exactly one conditional UPDATE wins.
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$renewed = $wpdb->query(
+				$wpdb->prepare(
+					"UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value = %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+					$expiry,
+					$option_name,
+					$owned_expiry
+				)
+			);
+
+			if ( $renewed ) {
+				self::$order_locks[ $order_id ] = $expiry;
+				return true;
+			}
+
+			// The lock went stale and another request took it over, or the row is gone.
+			unset( self::$order_locks[ $order_id ] );
+			return false;
+		}
+
+		$give_up_at = microtime( true ) + max( 0, $timeout );
+
+		// A contended INSERT fails on the duplicate key by design, so silence wpdb error reporting to keep the
+		// expected-failure path from spamming the log in debug mode; restore the prior setting when done.
+		$suppress = $wpdb->suppress_errors( true );
+		try {
+			while ( true ) {
+				$time   = microtime( true );
+				$now    = number_format( $time, 6, '.', '' );
+				$expiry = number_format( $time + self::ORDER_LOCK_TTL, 6, '.', '' );
+
+				// The unique option_name key makes this INSERT a mutex: it fails when the lock row already exists.
+				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+				$acquired = $wpdb->insert(
+					$wpdb->options,
+					array(
+						'option_name'  => $option_name,
+						'option_value' => $expiry,
+						'autoload'     => 'no',
+					),
+					array( '%s', '%s', '%s' )
+				);
+
+				if ( ! $acquired ) {
+					// The lock row exists; take it over only if its stored release time is already in the past.
+					// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+					$acquired = $wpdb->query(
+						$wpdb->prepare(
+							"UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value < %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+							$expiry,
+							$option_name,
+							$now
+						)
+					);
+				}
+
+				if ( $acquired ) {
+					self::$order_locks[ $order_id ] = $expiry;
+
+					if ( null === self::$unlock_orders_on_shutdown ) {
+						self::$unlock_orders_on_shutdown = static function (): void {
+							global $wpdb;
+
+							$callback = self::$unlock_orders_on_shutdown;
+							foreach ( self::$order_locks as $locked_order_id => $locked_expiry ) {
+								// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+								$wpdb->delete(
+									$wpdb->options,
+									array(
+										'option_name'  => self::ORDER_LOCK_OPTION_PREFIX . $locked_order_id,
+										'option_value' => $locked_expiry,
+									),
+									array( '%s', '%s' )
+								);
+							}
+
+							self::$order_locks               = array();
+							self::$unlock_orders_on_shutdown = null;
+
+							if ( $callback ) {
+								remove_action( 'shutdown', $callback, PHP_INT_MAX );
+							}
+						};
+
+						// Release after the session handlers persist their data at shutdown priority 20.
+						add_action( 'shutdown', self::$unlock_orders_on_shutdown, PHP_INT_MAX );
+					}
+					return true;
+				}
+
+				if ( $time >= $give_up_at ) {
+					return false;
+				}
+
+				usleep( 50000 );
+			}
+		} finally {
+			$wpdb->suppress_errors( $suppress );
+		}
+	}
+
 	/**
 	 * Final validation ran before payment is taken.
 	 *
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/SessionConcurrencyGuard.php b/plugins/woocommerce/src/StoreApi/Utilities/SessionConcurrencyGuard.php
new file mode 100644
index 00000000000..fbbc7d73486
--- /dev/null
+++ b/plugins/woocommerce/src/StoreApi/Utilities/SessionConcurrencyGuard.php
@@ -0,0 +1,88 @@
+<?php
+/**
+ * Detects persisted session changes during checkout.
+ */
+
+declare(strict_types=1);
+
+namespace Automattic\WooCommerce\StoreApi\Utilities;
+
+use WC_Session;
+
+/**
+ * Retains persisted session state most recently loaded or saved by each handler.
+ *
+ * @internal
+ */
+final class SessionConcurrencyGuard {
+
+	/**
+	 * Persisted session hashes keyed by session-handler object.
+	 *
+	 * @var \SplObjectStorage<WC_Session, string>|null
+	 */
+	private static $baseline_hashes;
+
+	/**
+	 * Capture persisted session data loaded or saved by a handler.
+	 *
+	 * @param WC_Session $session Session handler.
+	 * @param array      $data Persisted session data that was loaded or saved.
+	 */
+	public static function capture( WC_Session $session, array $data ): void {
+		self::get_baseline_hashes()[ $session ] = self::hash( $data );
+	}
+
+	/**
+	 * Check whether persisted data changed after it was last loaded or saved by this handler.
+	 *
+	 * @param WC_Session $session Session handler.
+	 * @return bool
+	 */
+	public static function has_changed( WC_Session $session ): bool {
+		$baseline_hashes = self::get_baseline_hashes();
+
+		if ( ! $baseline_hashes->contains( $session ) ) {
+			return false;
+		}
+
+		if ( method_exists( $session, 'get_session_data_from_storage' ) ) {
+			$persisted_data = $session->get_session_data_from_storage();
+		} elseif ( method_exists( $session, 'get_session_data' ) ) {
+			$persisted_data = $session->get_session_data();
+		} else {
+			return false;
+		}
+
+		return ! hash_equals( $baseline_hashes[ $session ], self::hash( (array) $persisted_data ) );
+	}
+
+	/**
+	 * Get the persisted session hash registry.
+	 *
+	 * @return \SplObjectStorage<WC_Session, string>
+	 */
+	private static function get_baseline_hashes(): \SplObjectStorage {
+		if ( ! self::$baseline_hashes ) {
+			/**
+			 * Persisted session hash registry.
+			 *
+			 * @var \SplObjectStorage<WC_Session, string> $baseline_hashes
+			 */
+			$baseline_hashes       = new \SplObjectStorage();
+			self::$baseline_hashes = $baseline_hashes;
+		}
+
+		return self::$baseline_hashes;
+	}
+
+	/**
+	 * Get a stable hash for persisted session data.
+	 *
+	 * @param array $data Session data to hash.
+	 * @return string
+	 */
+	private static function hash( array $data ): string {
+		return hash( 'sha256', maybe_serialize( $data ) );
+	}
+}
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php b/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
index ed0bdf0e68a..0f9e6ae8262 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
@@ -5,9 +5,12 @@
  * @package WooCommerce\Tests\Checkout.
  */

+declare( strict_types = 1 );
+
 use Automattic\WooCommerce\Enums\OrderStatus;
 use Automattic\WooCommerce\Internal\Checkout\PaymentRecovery;
 use Automattic\WooCommerce\RestApi\UnitTests\LoggerSpyTrait;
+use Automattic\WooCommerce\StoreApi\Utilities\OrderController;
 use Automattic\WooCommerce\Testing\Tools\CodeHacking\Hacks\FunctionsMockerHack;

 /**
@@ -79,6 +82,14 @@ class WC_Checkout_Test extends \WC_Unit_Test_Case {
 			public function update_session( $data ) {
 				return parent::update_session( $data );
 			}
+
+			public function process_order_for_test( $order_id, $with_payment ) {
+				if ( $with_payment ) {
+					return parent::process_order_payment( $order_id, WC_Gateway_BACS::ID );
+				}
+
+				return parent::process_order_without_payment( $order_id );
+			}
 		};
 		// phpcs:enable Generic.CodeAnalysis, Squiz.Commenting

@@ -98,20 +109,108 @@ class WC_Checkout_Test extends \WC_Unit_Test_Case {
 	 * Runs after each test.
 	 */
 	public function tearDown(): void {
-		delete_option( 'woocommerce_calc_taxes' );
-		delete_option( 'woocommerce_allowed_countries' );
-		delete_option( 'woocommerce_specific_allowed_countries' );
+		global $wpdb;
+
+		try {
+			$shutdown_callback_property = new ReflectionProperty( OrderController::class, 'unlock_orders_on_shutdown' );
+			$shutdown_callback_property->setAccessible( true );
+			$shutdown_callback = $shutdown_callback_property->getValue();
+			if ( $shutdown_callback ) {
+				$shutdown_callback();
+			}
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( OrderController::ORDER_LOCK_OPTION_PREFIX ) . '%' ) );
+
+			delete_option( 'woocommerce_calc_taxes' );
+			delete_option( 'woocommerce_allowed_countries' );
+			delete_option( 'woocommerce_specific_allowed_countries' );
+
+			if ( $this->original_session ) {
+				WC()->session           = $this->original_session;
+				$this->original_session = null;
+			}

-		if ( $this->original_session ) {
-			WC()->session           = $this->original_session;
-			$this->original_session = null;
+			wp_set_current_user( 0 );
+			WC()->session->set( 'customer', null );
+			WC_Helper_Shipping::delete_simple_flat_rate();
+		} finally {
+			parent::tearDown();
 		}
+	}
+
+	/**
+	 * @testdox Legacy checkout refuses an order currently locked by another request.
+	 */
+	public function test_create_order_refuses_locked_awaiting_payment_order(): void {
+		global $wpdb;
+
+		$order = WC_Helper_Order::create_order();
+		WC()->session->set( 'order_awaiting_payment', $order->get_id() );
+		$inserted = $wpdb->insert(
+			$wpdb->options,
+			array(
+				'option_name'  => OrderController::ORDER_LOCK_OPTION_PREFIX . $order->get_id(),
+				'option_value' => number_format( microtime( true ) + 60, 6, '.', '' ),
+				'autoload'     => 'no',
+			),
+			array( '%s', '%s', '%s' )
+		);
+		$this->assertSame( 1, $inserted, 'The competing request lock should be inserted.' );
+
+		$result = $this->sut->create_order( array( 'payment_method' => WC_Gateway_BACS::ID ) );
+
+		$this->assertWPError( $result );
+		$this->assertSame( 'Your order is still being processed by another request. Please try again.', $result->get_error_message() );
+	}
+
+	/**
+	 * @testdox Legacy checkout locks an order after creating it.
+	 */
+	public function test_create_order_locks_new_order(): void {
+		global $wpdb;
+
+		$product = WC_Helper_Product::create_simple_product();
+		WC()->cart->add_to_cart( $product->get_id() );
+
+		$order_id = $this->sut->create_order( array( 'payment_method' => WC_Gateway_BACS::ID ) );
+
+		$this->assertIsInt( $order_id, 'Checkout should create an order.' );
+		$this->assertNotNull(
+			$wpdb->get_var(
+				$wpdb->prepare(
+					"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s",
+					OrderController::ORDER_LOCK_OPTION_PREFIX . $order_id
+				)
+			),
+			'The newly created order should remain locked for the request.'
+		);
+	}
+
+	/**
+	 * @testdox Legacy checkout verifies lock ownership immediately before payment processing.
+	 * @testWith [false]
+	 *           [true]
+	 *
+	 * @param bool $with_payment Whether to exercise the payment-gateway path.
+	 */
+	public function test_payment_processing_refuses_lost_order_lock( bool $with_payment ): void {
+		global $wpdb;
+
+		$order = WC_Helper_Order::create_order();
+		$this->assertTrue( OrderController::lock_order( $order->get_id(), 0 ), 'The test request should initially own the lock.' );
+
+		$wpdb->update(
+			$wpdb->options,
+			array( 'option_value' => number_format( microtime( true ) + 120, 6, '.', '' ) ),
+			array( 'option_name' => OrderController::ORDER_LOCK_OPTION_PREFIX . $order->get_id() ),
+			array( '%s' ),
+			array( '%s' )
+		);

-		wp_set_current_user( 0 );
-		WC()->session->set( 'customer', null );
-		WC_Helper_Shipping::delete_simple_flat_rate();
+		$this->expectException( Exception::class );
+		$this->expectExceptionMessage( 'Your order is still being processed by another request. Please try again.' );

-		parent::tearDown();
+		$this->sut->process_order_for_test( $order->get_id(), $with_payment );
 	}

 	/**
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-session-handler-test.php b/plugins/woocommerce/tests/php/includes/class-wc-session-handler-test.php
new file mode 100644
index 00000000000..479f8d1ffa7
--- /dev/null
+++ b/plugins/woocommerce/tests/php/includes/class-wc-session-handler-test.php
@@ -0,0 +1,246 @@
+<?php
+/**
+ * Tests for WC_Session_Handler.
+ */
+
+declare(strict_types=1);
+
+/**
+ * WC_Session_Handler tests.
+ */
+class WC_Session_Handler_Test extends WC_Unit_Test_Case {
+
+	/**
+	 * @testdox Direct persisted session reads replace a stale object-cache entry with the latest data.
+	 */
+	public function test_get_session_data_from_storage_reads_latest_persisted_data(): void {
+		global $wpdb;
+
+		$customer_id = wc_rand_hash( 't_', 30 );
+		$handler     = new WC_Session_Handler();
+		$this->set_test_session( $handler, $customer_id );
+
+		$cache_key = WC_Cache_Helper::get_cache_prefix( WC_SESSION_CACHE_GROUP ) . $customer_id;
+		$table     = $wpdb->prefix . 'woocommerce_sessions';
+
+		try {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->replace(
+				$table,
+				array(
+					'session_key'    => $customer_id,
+					'session_value'  => maybe_serialize( array( 'cart_version' => 'latest' ) ),
+					'session_expiry' => time() + DAY_IN_SECONDS,
+				),
+				array( '%s', '%s', '%d' )
+			);
+			wp_cache_set( $cache_key, array( 'cart_version' => 'stale' ), WC_SESSION_CACHE_GROUP );
+
+			$this->assertSame( array( 'cart_version' => 'stale' ), $handler->get_session_data() );
+			$this->assertSame( array( 'cart_version' => 'latest' ), $handler->get_session_data_from_storage() );
+			$this->assertSame( array( 'cart_version' => 'latest' ), $handler->get_session_data() );
+		} finally {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->delete( $table, array( 'session_key' => $customer_id ), array( '%s' ) );
+			wp_cache_delete( $cache_key, WC_SESSION_CACHE_GROUP );
+		}
+	}
+
+	/**
+	 * @testdox A stale cache can reject one checkout but is refreshed for the next request.
+	 */
+	public function test_stale_cache_is_refreshed_after_concurrency_check(): void {
+		global $wpdb;
+
+		$customer_id = wc_rand_hash( 't_', 30 );
+		$stale_data  = array( 'cart_version' => 'stale' );
+		$latest_data = array( 'cart_version' => 'latest' );
+		$handler     = new WC_Session_Handler();
+		$table       = $wpdb->prefix . 'woocommerce_sessions';
+		$cache_key   = WC_Cache_Helper::get_cache_prefix( WC_SESSION_CACHE_GROUP ) . $customer_id;
+		$this->set_test_session( $handler, $customer_id );
+
+		try {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->replace(
+				$table,
+				array(
+					'session_key'    => $customer_id,
+					'session_value'  => maybe_serialize( $latest_data ),
+					'session_expiry' => time() + DAY_IN_SECONDS,
+				),
+				array( '%s', '%s', '%d' )
+			);
+			wp_cache_set( $cache_key, $stale_data, WC_SESSION_CACHE_GROUP );
+
+			$cached_data = $handler->get_session_data();
+			\Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard::capture( $handler, $cached_data );
+			$this->assertTrue( \Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard::has_changed( $handler ) );
+
+			$next_handler = new WC_Session_Handler();
+			$this->set_test_session( $next_handler, $customer_id );
+			$next_request_data = $next_handler->get_session_data();
+			\Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard::capture( $next_handler, $next_request_data );
+
+			$this->assertSame( $latest_data, $next_request_data );
+			$this->assertFalse( \Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard::has_changed( $next_handler ) );
+		} finally {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->delete( $table, array( 'session_key' => $customer_id ), array( '%s' ) );
+			wp_cache_delete( $cache_key, WC_SESSION_CACHE_GROUP );
+		}
+	}
+
+	/**
+	 * @testdox A subclass inheriting core storage still reads fresh persisted data.
+	 */
+	public function test_get_session_data_from_storage_reads_fresh_data_for_noop_subclass(): void {
+		global $wpdb;
+
+		$customer_id = wc_rand_hash( 't_', 30 );
+		$handler     = new class() extends WC_Session_Handler {};
+		$this->set_test_session( $handler, $customer_id );
+
+		$cache_key = WC_Cache_Helper::get_cache_prefix( WC_SESSION_CACHE_GROUP ) . $customer_id;
+		$table     = $wpdb->prefix . 'woocommerce_sessions';
+
+		try {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->replace(
+				$table,
+				array(
+					'session_key'    => $customer_id,
+					'session_value'  => maybe_serialize( array( 'cart_version' => 'latest' ) ),
+					'session_expiry' => time() + DAY_IN_SECONDS,
+				),
+				array( '%s', '%s', '%d' )
+			);
+			wp_cache_set( $cache_key, array( 'cart_version' => 'stale' ), WC_SESSION_CACHE_GROUP );
+
+			$this->assertSame( array( 'cart_version' => 'stale' ), $handler->get_session_data() );
+			$this->assertSame( array( 'cart_version' => 'latest' ), $handler->get_session_data_from_storage() );
+			$this->assertSame( array( 'cart_version' => 'latest' ), $handler->get_session_data() );
+		} finally {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->delete( $table, array( 'session_key' => $customer_id ), array( '%s' ) );
+			wp_cache_delete( $cache_key, WC_SESSION_CACHE_GROUP );
+		}
+	}
+
+	/**
+	 * @testdox Direct persisted reads respect storage overridden by a custom session handler.
+	 */
+	public function test_get_session_data_from_storage_respects_custom_session_handlers(): void {
+		$customer_id = wc_rand_hash( 't_', 30 );
+		$handler     = new class() extends WC_Session_Handler {
+			/**
+			 * Custom backend data.
+			 *
+			 * @var array
+			 */
+			public $custom_data = array( 'cart_version' => 'custom-backend' );
+
+			/**
+			 * Set the active session for the test.
+			 *
+			 * @param string $customer_id Customer ID.
+			 */
+			public function set_test_session( string $customer_id ): void {
+				$this->_customer_id        = $customer_id;
+				$this->_has_cookie         = true;
+				$this->_session_expiration = time() + DAY_IN_SECONDS;
+			}
+
+			/**
+			 * Read from the simulated custom backend.
+			 *
+			 * @param string $customer_id Customer ID.
+			 * @param mixed  $default_value Default value.
+			 * @return mixed
+			 */
+			public function get_session( $customer_id, $default_value = false ) {
+				return $this->custom_data;
+			}
+		};
+		$handler->set_test_session( $customer_id );
+
+		$this->assertSame( array( 'cart_version' => 'custom-backend' ), $handler->get_session_data_from_storage() );
+	}
+
+	/**
+	 * @testdox Persisted session changes exclude unsaved changes made by the current request.
+	 */
+	public function test_detects_only_external_persisted_session_changes(): void {
+		global $wpdb;
+
+		$customer_id   = wc_rand_hash( 't_', 30 );
+		$initial_data  = array( 'cart_version' => 'initial' );
+		$external_data = array( 'cart_version' => 'external' );
+		$handler       = new WC_Session_Handler();
+		$table         = $wpdb->prefix . 'woocommerce_sessions';
+		$cache_key     = WC_Cache_Helper::get_cache_prefix( WC_SESSION_CACHE_GROUP ) . $customer_id;
+
+		try {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->replace(
+				$table,
+				array(
+					'session_key'    => $customer_id,
+					'session_value'  => maybe_serialize( $initial_data ),
+					'session_expiry' => time() + DAY_IN_SECONDS,
+				),
+				array( '%s', '%s', '%d' )
+			);
+			$this->set_test_session( $handler, $customer_id, $initial_data );
+
+			$handler->set( 'current_request', 'changed' );
+			$this->assertFalse( \Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard::has_changed( $handler ), 'Unsaved changes from this request should not look external.' );
+
+			$handler->save_data();
+			$this->assertFalse( \Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard::has_changed( $handler ), 'Saving this request should update its persisted baseline.' );
+
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->update(
+				$table,
+				array( 'session_value' => maybe_serialize( $external_data ) ),
+				array( 'session_key' => $customer_id ),
+				array( '%s' ),
+				array( '%s' )
+			);
+			$this->assertTrue( \Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard::has_changed( $handler ), 'A later persisted change should be detected.' );
+		} finally {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->delete( $table, array( 'session_key' => $customer_id ), array( '%s' ) );
+			wp_cache_delete( $cache_key, WC_SESSION_CACHE_GROUP );
+		}
+	}
+
+	/**
+	 * Set active state on an exact core session handler.
+	 *
+	 * @param WC_Session_Handler $handler Session handler.
+	 * @param string             $customer_id Customer ID.
+	 * @param array|null         $session_data Optional in-memory and persisted baseline data.
+	 */
+	private function set_test_session( WC_Session_Handler $handler, string $customer_id, ?array $session_data = null ): void {
+		$properties = array(
+			'_customer_id'        => $customer_id,
+			'_has_cookie'         => true,
+			'_session_expiration' => time() + DAY_IN_SECONDS,
+		);
+
+		if ( null !== $session_data ) {
+			$properties['_data'] = $session_data;
+		}
+
+		foreach ( $properties as $name => $value ) {
+			$property = new ReflectionProperty( $handler, $name );
+			$property->setAccessible( true );
+			$property->setValue( $handler, $value );
+		}
+
+		if ( null !== $session_data ) {
+			\Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard::capture( $handler, $session_data );
+		}
+	}
+}
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Cart.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Cart.php
index 198e88b939b..f2929cfeb28 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Cart.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/Cart.php
@@ -310,6 +310,30 @@ class Cart extends ControllerTestCase {
 		);
 	}

+	/**
+	 * @testdox Cart updates do not synchronize an existing draft order.
+	 */
+	public function test_update_item_does_not_synchronize_draft_order(): void {
+		$draft_order_id = wc()->session->get( 'store_api_draft_order' );
+
+		$request = new \WP_REST_Request( 'POST', '/wc/store/v1/cart/update-item' );
+		$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
+		$request->set_body_params(
+			array(
+				'key'      => $this->keys[0],
+				'quantity' => 10,
+			)
+		);
+
+		$response    = rest_get_server()->dispatch( $request );
+		$draft_order = wc_get_order( $draft_order_id );
+
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertSame( 11, $response->get_data()['items_count'] );
+		$this->assertInstanceOf( \WC_Order::class, $draft_order );
+		$this->assertCount( 0, $draft_order->get_items(), 'Cart routes should leave draft orders unchanged.' );
+	}
+
 	/**
 	 * Test getting updated shipping.
 	 */
@@ -1699,15 +1723,17 @@ class Cart extends ControllerTestCase {
 	}

 	/**
-	 * @testdox A cart change removes the draft order from the session when syncing the change to it fails to save.
+	 * @testdox A cart change does not save or forget the draft order.
 	 */
-	public function test_cart_change_forgets_draft_order_that_fails_to_save(): void {
+	public function test_cart_change_does_not_save_or_forget_draft_order(): void {
 		$draft_order_id = (int) wc()->session->get( 'store_api_draft_order' );
 		$this->assertGreaterThan( 0, $draft_order_id );

-		$fail = function ( $order ) use ( $draft_order_id ) {
+		$save_attempted = false;
+		$fail           = function ( $order ) use ( $draft_order_id, &$save_attempted ) {
 			if ( $order->get_id() === $draft_order_id ) {
-				throw new \Exception( 'Forced save failure' );
+				$save_attempted = true;
+				throw new \Exception( 'Cart routes must not save draft orders.' );
 			}
 		};
 		add_action( 'woocommerce_before_order_object_save', $fail );
@@ -1715,9 +1741,15 @@ class Cart extends ControllerTestCase {
 		$request = new \WP_REST_Request( 'POST', '/wc/store/v1/cart/remove-item' );
 		$request->set_header( 'Nonce', wp_create_nonce( 'wc_store_api' ) );
 		$request->set_body_params( array( 'key' => $this->keys[0] ) );
-		$response = rest_get_server()->dispatch( $request );

-		$this->assertSame( 200, $response->get_status(), 'The cart change itself should still succeed.' );
-		$this->assertEmpty( wc()->session->get( 'store_api_draft_order' ), 'A draft order that failed to save must not stay in the session to be resumed.' );
+		try {
+			$response = rest_get_server()->dispatch( $request );
+		} finally {
+			remove_action( 'woocommerce_before_order_object_save', $fail );
+		}
+
+		$this->assertSame( 200, $response->get_status(), 'The cart change itself should succeed.' );
+		$this->assertFalse( $save_attempted, 'Cart routes should not save draft orders.' );
+		$this->assertSame( $draft_order_id, (int) wc()->session->get( 'store_api_draft_order' ), 'Checkout should validate the draft order when it is next used.' );
 	}
 }
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/CheckoutSessionLockTests.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/CheckoutSessionLockTests.php
new file mode 100644
index 00000000000..78c04480e9c
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Routes/CheckoutSessionLockTests.php
@@ -0,0 +1,91 @@
+<?php
+/**
+ * Checkout session lock tests.
+ */
+
+declare(strict_types=1);
+
+namespace Automattic\WooCommerce\Tests\Blocks\StoreApi\Routes;
+
+use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
+use Automattic\WooCommerce\StoreApi\Routes\V1\Checkout as CheckoutRoute;
+use Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard;
+
+/**
+ * Tests for checkout state after order-lock contention.
+ */
+class CheckoutSessionLockTests extends \WC_Unit_Test_Case {
+
+	/**
+	 * @testdox Checkout retains the active session baseline when another handler captures state.
+	 */
+	public function test_checkout_rejects_changed_persisted_session(): void {
+		$sut              = ( new \ReflectionClass( CheckoutRoute::class ) )->newInstanceWithoutConstructor();
+		$assert_unchanged = new \ReflectionMethod( CheckoutRoute::class, 'throw_if_persisted_session_changed' );
+		$assert_unchanged->setAccessible( true );
+
+		$original_session = WC()->session;
+		$session          = new class() extends \WC_Session_Handler {
+			/**
+			 * Simulated persisted session data.
+			 *
+			 * @var array
+			 */
+			public $persisted_data = array( 'version' => 'external' );
+
+			/**
+			 * Get the simulated persisted session data.
+			 *
+			 * @return array
+			 */
+			public function get_session_data_from_storage(): array {
+				return $this->persisted_data;
+			}
+		};
+		WC()->session     = $session;
+		SessionConcurrencyGuard::capture( $session, array( 'version' => 'loaded' ) );
+		SessionConcurrencyGuard::capture( new \WC_Session_Handler(), array( 'version' => 'temporary-handler' ) );
+
+		try {
+			try {
+				$assert_unchanged->invoke( $sut );
+				$this->fail( 'Checkout should reject a session changed by another request.' );
+			} catch ( RouteException $error ) {
+				$this->assertSame( 'woocommerce_rest_checkout_session_changed', $error->getErrorCode() );
+				$this->assertSame( 409, $error->getCode() );
+			}
+		} finally {
+			WC()->session = $original_session;
+		}
+	}
+
+	/**
+	 * @testdox Checkout allows current-request changes when persisted session data is unchanged.
+	 */
+	public function test_checkout_allows_unchanged_persisted_session(): void {
+		$sut              = ( new \ReflectionClass( CheckoutRoute::class ) )->newInstanceWithoutConstructor();
+		$assert_unchanged = new \ReflectionMethod( CheckoutRoute::class, 'throw_if_persisted_session_changed' );
+		$assert_unchanged->setAccessible( true );
+
+		$original_session = WC()->session;
+		$session          = new class() extends \WC_Session_Handler {
+			/**
+			 * Get the unchanged simulated persisted session data.
+			 *
+			 * @return array
+			 */
+			public function get_session_data_from_storage(): array {
+				return array( 'version' => 'loaded' );
+			}
+		};
+		WC()->session     = $session;
+		SessionConcurrencyGuard::capture( $session, array( 'version' => 'loaded' ) );
+
+		try {
+			$assert_unchanged->invoke( $sut );
+			$this->assertTrue( true );
+		} finally {
+			WC()->session = $original_session;
+		}
+	}
+}
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/SessionHandlerTest.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/SessionHandlerTest.php
index 3e5bcda09f5..edfb4ed84f6 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/SessionHandlerTest.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/SessionHandlerTest.php
@@ -5,6 +5,7 @@ namespace Automattic\WooCommerce\Tests\Blocks\StoreApi;

 use Automattic\WooCommerce\StoreApi\SessionHandler;
 use Automattic\WooCommerce\StoreApi\Utilities\CartTokenUtils;
+use Automattic\WooCommerce\StoreApi\Utilities\SessionConcurrencyGuard;
 use WC_Session;
 use WC_Unit_Test_Case;

@@ -139,4 +140,52 @@ class SessionHandlerTest extends WC_Unit_Test_Case {

 		$this->assertSame( $customer_id, $handler->get_customer_id(), 'A customer token should address its own session' );
 	}
+
+	/**
+	 * @testdox Persisted session changes exclude unsaved changes made by the current request.
+	 */
+	public function test_detects_only_external_persisted_session_changes(): void {
+		global $wpdb;
+
+		$customer_id   = 't_session_revision';
+		$initial_data  = array( 'cart_version' => 'initial' );
+		$external_data = array( 'cart_version' => 'external' );
+		$table         = $wpdb->prefix . 'woocommerce_sessions';
+
+		try {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->replace(
+				$table,
+				array(
+					'session_key'    => $customer_id,
+					'session_value'  => maybe_serialize( $initial_data ),
+					'session_expiry' => time() + DAY_IN_SECONDS,
+				),
+				array( '%s', '%s', '%d' )
+			);
+			$_SERVER['HTTP_CART_TOKEN'] = CartTokenUtils::get_cart_token( $customer_id );
+
+			$handler = new SessionHandler();
+			$handler->init();
+			$handler->set( 'current_request', 'changed' );
+
+			$this->assertFalse( SessionConcurrencyGuard::has_changed( $handler ), 'Unsaved changes from this request should not look external.' );
+
+			$handler->save_data();
+			$this->assertFalse( SessionConcurrencyGuard::has_changed( $handler ), 'Saving this request should update its persisted baseline.' );
+
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->update(
+				$table,
+				array( 'session_value' => maybe_serialize( $external_data ) ),
+				array( 'session_key' => $customer_id ),
+				array( '%s' ),
+				array( '%s' )
+			);
+			$this->assertTrue( SessionConcurrencyGuard::has_changed( $handler ), 'A later persisted change should be detected.' );
+		} finally {
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->delete( $table, array( 'session_key' => $customer_id ), array( '%s' ) );
+		}
+	}
 }
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/OrderControllerTests.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/OrderControllerTests.php
index 63bce0c9ae6..dc5e1b927e5 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/OrderControllerTests.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/OrderControllerTests.php
@@ -63,6 +63,21 @@ class OrderControllerTests extends \WC_Unit_Test_Case {
 		};
 	}

+	/**
+	 * Tear down test fixtures.
+	 */
+	public function tearDown(): void {
+		global $wpdb;
+
+		try {
+			$this->unlock_orders();
+			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+			$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( OrderController::ORDER_LOCK_OPTION_PREFIX ) . '%' ) );
+		} finally {
+			parent::tearDown();
+		}
+	}
+
 	/**
 	 * test_validate_existing_order_before_payment_valid_data.
 	 */
@@ -679,6 +694,141 @@ class OrderControllerTests extends \WC_Unit_Test_Case {
 		return $order;
 	}

+	/**
+	 * @testdox Order locks are re-entrant within a request and released by their owner.
+	 */
+	public function test_order_lock_is_reentrant_and_released(): void {
+		global $wpdb;
+
+		$order_id    = 123;
+		$option_name = OrderController::ORDER_LOCK_OPTION_PREFIX . $order_id;
+
+		$this->assertTrue( OrderController::lock_order( $order_id, 0 ), 'The first acquisition should lock the order.' );
+		$shutdown_callback = $this->get_order_lock_shutdown_callback();
+		$this->assertInstanceOf( \Closure::class, $shutdown_callback );
+		$this->assertSame( PHP_INT_MAX, has_action( 'shutdown', $shutdown_callback ), 'The lock should be released after session data is persisted.' );
+		$first_expiry = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $option_name ) );
+
+		$this->assertTrue( OrderController::lock_order( $order_id, 0 ), 'The same request should retain ownership.' );
+		$renewed_expiry = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $option_name ) );
+		$this->assertGreaterThan( (float) $first_expiry, (float) $renewed_expiry, 'Re-entering the lock should renew its lease.' );
+
+		$this->unlock_orders();
+
+		$this->assertNull(
+			$wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $option_name ) ),
+			'Releasing the lock should remove its options-table row.'
+		);
+		$this->assertFalse( has_action( 'shutdown', $shutdown_callback ), 'Manual cleanup should remove the shutdown callback.' );
+	}
+
+	/**
+	 * @testdox A live order lock owned by another request blocks acquisition.
+	 */
+	public function test_order_lock_rejects_another_owner(): void {
+		global $wpdb;
+
+		$order_id = 456;
+		$inserted = $wpdb->insert(
+			$wpdb->options,
+			array(
+				'option_name'  => OrderController::ORDER_LOCK_OPTION_PREFIX . $order_id,
+				'option_value' => number_format( microtime( true ) + 60, 6, '.', '' ),
+				'autoload'     => 'no',
+			),
+			array( '%s', '%s', '%s' )
+		);
+
+		$this->assertSame( 1, $inserted, 'The competing request lock should be inserted.' );
+		$this->assertFalse( OrderController::lock_order( $order_id, 0 ), 'The active lock should prevent acquisition.' );
+	}
+
+	/**
+	 * @testdox An expired order lock can be taken over and released by the new owner.
+	 */
+	public function test_order_lock_takes_over_expired_lock(): void {
+		global $wpdb;
+
+		$order_id    = 789;
+		$option_name = OrderController::ORDER_LOCK_OPTION_PREFIX . $order_id;
+		$inserted    = $wpdb->insert(
+			$wpdb->options,
+			array(
+				'option_name'  => $option_name,
+				'option_value' => number_format( microtime( true ) - 1, 6, '.', '' ),
+				'autoload'     => 'no',
+			),
+			array( '%s', '%s', '%s' )
+		);
+
+		$this->assertSame( 1, $inserted, 'The stale lock should be inserted.' );
+		$this->assertTrue( OrderController::lock_order( $order_id, 0 ), 'The expired lock should be available for takeover.' );
+		$this->assertGreaterThan(
+			microtime( true ),
+			(float) $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $option_name ) ),
+			'The takeover should store a new future expiry.'
+		);
+
+		$this->unlock_orders();
+
+		$this->assertNull( $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $option_name ) ) );
+	}
+
+	/**
+	 * @testdox Releasing a stale lock does not delete a replacement owner's lock.
+	 */
+	public function test_unlock_does_not_delete_replacement_lock(): void {
+		global $wpdb;
+
+		$order_id          = 987;
+		$option_name       = OrderController::ORDER_LOCK_OPTION_PREFIX . $order_id;
+		$replacement_value = number_format( microtime( true ) + 120, 6, '.', '' );
+
+		$this->assertTrue( OrderController::lock_order( $order_id, 0 ) );
+		$this->assertSame(
+			1,
+			$wpdb->update(
+				$wpdb->options,
+				array( 'option_value' => $replacement_value ),
+				array( 'option_name' => $option_name ),
+				array( '%s' ),
+				array( '%s' )
+			),
+			'The replacement request should take ownership of the row.'
+		);
+		$this->assertFalse( OrderController::lock_order( $order_id, 0 ), 'The stale owner should not renew a replacement owner\'s lock.' );
+
+		$this->unlock_orders();
+
+		$this->assertSame(
+			$replacement_value,
+			$wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $option_name ) ),
+			'Releasing the stale owner should preserve the replacement lock.'
+		);
+	}
+
+	/**
+	 * Get the registered order-lock shutdown callback.
+	 *
+	 * @return \Closure|null
+	 */
+	private function get_order_lock_shutdown_callback(): ?\Closure {
+		$property = new \ReflectionProperty( OrderController::class, 'unlock_orders_on_shutdown' );
+		$property->setAccessible( true );
+
+		return $property->getValue();
+	}
+
+	/**
+	 * Release order locks registered by the current test.
+	 */
+	private function unlock_orders(): void {
+		$callback = $this->get_order_lock_shutdown_callback();
+		if ( $callback ) {
+			$callback();
+		}
+	}
+
 	/**
 	 * Helper method to set shipping address on an order.
 	 *