Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Refactor `select_for_update` utils (#17866)

Filip Owczarek20a2b1f48f34
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c1117c10c7..c2de671746 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -406,6 +406,26 @@ otherwise to the main module directory, usually to the `utils.py` file.
Try to find a name as descriptive as possible when writing such a method.
Also, do not forget about the docstring, especially in a complicated function.
+### Locking Objects
+
+To lock objects and prevent race conditions in concurrent operations, use Django's [`select_for_update()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#select-for-update) method on querysets.
+
+#### General Guidelines
+
+- When locking **multiple objects**, always lock them **in a consistent order** to avoid deadlocks.
+ - Use a clear and stable ordering—typically by `pk`.
+ - When locking **across multiple models**, always acquire locks in a defined order. For example, lock the `Order` model **before** `OrderLine`.
+
+#### Best Practices
+
+To reduce the chance of deadlocks and to keep the locking logic consistent:
+
+- Wrap all locking logic in **helper functions**.
+- Place these helper functions in a file named `lock_objects.py` located in the same app directory as the model you're locking.
+ - For single-model locks, use the model's app directory (e.g. `orders/lock_objects.py`).
+ - For multi-model locks, place the function in the directory of the **last model being locked**.
+ - Example: If locking `Order` and `TransactionItem`, and `TransactionItem` is locked last, use `payment/lock_objects.py`.
+
### Searching
So far, we have mainly used the `GinIndex` and `ilike` operators for searching, but currently, we are testing a new solution with the use of `SearchVector` and `SearchRank`.
diff --git a/saleor/checkout/lock_objects.py b/saleor/checkout/lock_objects.py
new file mode 100644
index 0000000000..4c12ae6dbc
--- /dev/null
+++ b/saleor/checkout/lock_objects.py
@@ -0,0 +1,11 @@
+from django.db.models import QuerySet
+
+from .models import Checkout, CheckoutLine
+
+
+def checkout_qs_select_for_update() -> QuerySet[Checkout]:
+ return Checkout.objects.order_by("pk").select_for_update(of=(["self"]))
+
+
+def checkout_lines_qs_select_for_update() -> QuerySet[CheckoutLine]:
+ return CheckoutLine.objects.order_by("pk").select_for_update(of=(["self"]))
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index dbf88ebfad..5f85135a8c 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -9,7 +9,7 @@ import graphene
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
-from django.db.models import QuerySet, prefetch_related_objects
+from django.db.models import prefetch_related_objects
from django.utils import timezone
from prices import Money
@@ -61,6 +61,7 @@ from ..warehouse.models import Warehouse
from ..warehouse.reservations import reserve_stocks_and_preorders
from . import AddressType, base_calculations, calculations
from .error_codes import CheckoutErrorCode
+from .lock_objects import checkout_lines_qs_select_for_update
from .models import Checkout, CheckoutLine, CheckoutMetadata
if TYPE_CHECKING:
@@ -123,10 +124,6 @@ def invalidate_checkout_prices(
return updated_fields
-def checkout_lines_qs_select_for_update() -> QuerySet[CheckoutLine]:
- return CheckoutLine.objects.order_by("id").select_for_update(of=(["self"]))
-
-
def checkout_lines_bulk_update(
lines_to_update: list["CheckoutLine"], fields_to_update: list[str]
):
diff --git a/saleor/discount/utils/order.py b/saleor/discount/utils/order.py
index fd7e3f7462..2fa10e936b 100644
--- a/saleor/discount/utils/order.py
+++ b/saleor/discount/utils/order.py
@@ -13,6 +13,7 @@ from ...core.db.connection import allow_writer
from ...core.prices import quantize_price
from ...core.taxes import zero_money
from ...order.base_calculations import base_order_subtotal
+from ...order.lock_objects import order_qs_select_for_update
from ...order.models import Order, OrderLine
from .. import DiscountType
from ..interface import VariantPromotionRuleInfo
@@ -43,8 +44,6 @@ def create_order_line_discount_objects(
list[str],
],
) -> None | list["EditableOrderLineInfo"]:
- from ...order.utils import order_qs_select_for_update
-
if not discount_data or not lines_info:
return None
@@ -282,8 +281,6 @@ def create_order_line_discount_objects_for_catalogue_promotions(
rules_info: Iterable[VariantPromotionRuleInfo],
channel: Channel,
) -> list["OrderLineDiscount"]:
- from ...order.utils import order_qs_select_for_update
-
line_discounts_to_create: list[OrderLineDiscount] = []
for rule_info in rules_info:
line_discount = _create_order_line_discount_for_catalogue_promotion(
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index 70fbe44e06..0d9e67ddb5 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -15,11 +15,13 @@ from prices import Money
from ...channel.models import Channel
from ...checkout.fetch import CheckoutLineInfo
+from ...checkout.lock_objects import checkout_lines_qs_select_for_update
from ...checkout.models import Checkout, CheckoutLine
from ...core.db.connection import allow_writer
from ...core.exceptions import InsufficientStock
from ...core.taxes import zero_money
from ...order.fetch import EditableOrderLineInfo
+from ...order.lock_objects import order_lines_qs_select_for_update
from ...order.models import Order
from ...product.models import (
Product,
@@ -404,9 +406,6 @@ def _get_available_for_purchase_variant_ids(
def delete_gift_lines_qs(
order_or_checkout: Checkout | Order,
):
- from ...checkout.utils import checkout_lines_qs_select_for_update
- from ...order.utils import order_lines_qs_select_for_update
-
with transaction.atomic():
if isinstance(order_or_checkout, Checkout):
locked_checkout_lines_qs = checkout_lines_qs_select_for_update()
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index cca890fc0f..e6c00ccaa0 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -9,7 +9,6 @@ from .....app.models import App
from .....checkout.actions import (
transaction_amounts_for_checkout_updated_without_price_recalculation,
)
-from .....checkout.models import Checkout
from .....core.exceptions import PermissionDenied
from .....core.prices import quantize_price
from .....core.tracing import traced_atomic_transaction
@@ -25,6 +24,11 @@ from .....order.utils import (
from .....payment import OPTIONAL_AMOUNT_EVENTS, TransactionEventType
from .....payment import models as payment_models
from .....payment.interface import PaymentMethodDetails
+from .....payment.lock_objects import (
+ get_checkout_and_transaction_item_locked_for_update,
+ get_order_and_transaction_item_locked_for_update,
+ transaction_item_qs_select_for_update,
+)
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
from .....payment.utils import (
authorization_success_already_exists,
@@ -312,16 +316,9 @@ class TransactionEventReport(DeprecatedModelMutation):
):
order = cast(order_models.Order, transaction.order)
with traced_atomic_transaction():
- order = (
- order_models.Order.objects.prefetch_related(
- "payments", "payment_transactions", "granted_refunds"
- )
- .select_for_update()
- .get(pk=order.pk)
+ order, transaction = get_order_and_transaction_item_locked_for_update(
+ order.pk, transaction.pk
)
- transaction = payment_models.TransactionItem.objects.select_for_update(
- of=("self",)
- ).get(pk=transaction.pk)
updates_amounts_for_order(order)
update_order_search_vector(order)
order_info = fetch_order_info(order)
@@ -353,14 +350,11 @@ class TransactionEventReport(DeprecatedModelMutation):
checkout_deleted = False
if transaction.checkout_id:
with traced_atomic_transaction():
- locked_checkout = (
- Checkout.objects.select_for_update()
- .filter(pk=transaction.checkout_id)
- .first()
+ locked_checkout, transaction = (
+ get_checkout_and_transaction_item_locked_for_update(
+ transaction.checkout_id, transaction.pk
+ )
)
- transaction = payment_models.TransactionItem.objects.select_for_update(
- of=("self",)
- ).get(pk=transaction.pk)
if transaction.checkout_id and locked_checkout:
transaction_amounts_for_checkout_updated_without_price_recalculation(
transaction, locked_checkout, manager, user, app
@@ -485,8 +479,8 @@ class TransactionEventReport(DeprecatedModelMutation):
# thread race. We need to be sure, that we will always create a single event
# on our side for specific action.
_transaction = (
- payment_models.TransactionItem.objects.filter(pk=transaction.pk)
- .select_for_update(of=("self",))
+ transaction_item_qs_select_for_update()
+ .filter(pk=transaction.pk)
.first()
)
diff --git a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
index c2eaad4769..17d2fcf4e4 100644
--- a/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
+++ b/saleor/graphql/product/bulk_mutations/product_variant_bulk_delete.py
@@ -13,8 +13,8 @@ from ....core.postgres import FlatConcatSearchVector
from ....core.tracing import traced_atomic_transaction
from ....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirty
from ....order import events as order_events
+from ....order.lock_objects import order_lines_qs_select_for_update
from ....order.tasks import recalculate_orders_task
-from ....order.utils import order_lines_qs_select_for_update
from ....permission.enums import ProductPermissions
from ....product import models
from ....product.search import prepare_product_search_vector_value
diff --git a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py
index 75c83aa394..b1e6760d62 100644
--- a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py
+++ b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py
@@ -8,7 +8,7 @@ from ....core.tracing import traced_atomic_transaction
from ....permission.enums import ProductPermissions
from ....warehouse import models
from ....warehouse.error_codes import StockBulkUpdateErrorCode
-from ....warehouse.management import stock_qs_select_for_update
+from ....warehouse.lock_objects import stock_qs_select_for_update
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.utils import get_webhooks_for_event
from ...core.doc_category import DOC_CATEGORY_PRODUCTS
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 3e49269a6f..b8935fde43 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -22,7 +22,7 @@ from ..core.utils.events import (
webhook_async_event_requires_sync_webhooks_to_trigger,
)
from ..giftcard import GiftCardLineData
-from ..order.utils import order_lines_qs_select_for_update
+from ..order.lock_objects import order_lines_qs_select_for_update
from ..payment import (
ChargeStatus,
CustomPaymentChoices,
diff --git a/saleor/order/lock_objects.py b/saleor/order/lock_objects.py
new file mode 100644
index 0000000000..d924eecdcc
--- /dev/null
+++ b/saleor/order/lock_objects.py
@@ -0,0 +1,11 @@
+from django.db.models import QuerySet
+
+from .models import Order, OrderLine
+
+
+def order_lines_qs_select_for_update() -> QuerySet[OrderLine]:
+ return OrderLine.objects.order_by("pk").select_for_update(of=["self"])
+
+
+def order_qs_select_for_update() -> QuerySet[Order]:
+ return Order.objects.order_by("pk").select_for_update(of=(["self"]))
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 714485c776..c4d930daa8 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -84,14 +84,6 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-def order_qs_select_for_update():
- return Order.objects.order_by("id").select_for_update(of=(["self"]))
-
-
-def order_lines_qs_select_for_update() -> QuerySet[OrderLine]:
- return OrderLine.objects.order_by("pk").select_for_update(of=["self"])
-
-
def get_order_country(order: Order) -> str:
"""Return country to which order will be shipped."""
return get_active_country(
diff --git a/saleor/payment/lock_objects.py b/saleor/payment/lock_objects.py
new file mode 100644
index 0000000000..2d28b8c2cc
--- /dev/null
+++ b/saleor/payment/lock_objects.py
@@ -0,0 +1,36 @@
+from typing import TYPE_CHECKING, Optional
+from uuid import UUID
+
+from django.db.models import QuerySet
+
+from ..checkout.lock_objects import checkout_qs_select_for_update
+from ..order.lock_objects import order_qs_select_for_update
+from .models import TransactionItem
+
+if TYPE_CHECKING:
+ from ..checkout.models import Checkout
+ from ..order.models import Order
+
+
+def transaction_item_qs_select_for_update() -> QuerySet[TransactionItem]:
+ return TransactionItem.objects.order_by("pk").select_for_update(of=["self"])
+
+
+def get_order_and_transaction_item_locked_for_update(
+ order_id: UUID, transaction_item_id: int
+) -> tuple["Order", TransactionItem]:
+ order = order_qs_select_for_update().get(pk=order_id)
+ transaction_item = transaction_item_qs_select_for_update().get(
+ pk=transaction_item_id
+ )
+ return order, transaction_item
+
+
+def get_checkout_and_transaction_item_locked_for_update(
+ checkout_id: UUID, transaction_item_id: int
+) -> tuple[Optional["Checkout"], TransactionItem]:
+ checkout = checkout_qs_select_for_update().filter(pk=checkout_id).first()
+ transaction_item = transaction_item_qs_select_for_update().get(
+ pk=transaction_item_id
+ )
+ return checkout, transaction_item
diff --git a/saleor/warehouse/lock_objects.py b/saleor/warehouse/lock_objects.py
new file mode 100644
index 0000000000..3b99c1d904
--- /dev/null
+++ b/saleor/warehouse/lock_objects.py
@@ -0,0 +1,22 @@
+from .models import Allocation, Stock
+
+
+def stock_select_for_update_for_existing_qs(qs):
+ return qs.order_by("pk").select_for_update(of=(["self"]))
+
+
+def stock_qs_select_for_update():
+ return stock_select_for_update_for_existing_qs(Stock.objects.all())
+
+
+def allocation_with_stock_qs_select_for_update():
+ return (
+ Allocation.objects.select_related("stock")
+ .select_for_update(
+ of=(
+ "self",
+ "stock",
+ )
+ )
+ .order_by("stock__pk")
+ )
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 34e87cd6b6..b5febccb79 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -23,6 +23,11 @@ from ..order.fetch import OrderLineInfo
from ..order.models import OrderLine
from ..plugins.manager import PluginsManager
from ..product.models import ProductVariant, ProductVariantChannelListing
+from .lock_objects import (
+ allocation_with_stock_qs_select_for_update,
+ stock_qs_select_for_update,
+ stock_select_for_update_for_existing_qs,
+)
from .models import (
Allocation,
ChannelWarehouse,
@@ -42,14 +47,6 @@ class StockData(NamedTuple):
quantity: int
-def stock_select_for_update_for_existing_qs(qs):
- return qs.order_by("pk").select_for_update(of=(["self"]))
-
-
-def stock_qs_select_for_update():
- return stock_select_for_update_for_existing_qs(Stock.objects.all())
-
-
def delete_stocks(stock_pks_to_delete: list[int]):
with transaction.atomic():
return Stock.objects.filter(
@@ -70,19 +67,6 @@ def stock_bulk_update(stocks: list[Stock], fields_to_update: list[str]):
Stock.objects.bulk_update(stocks, fields_to_update)
-def allocation_with_stock_qs_select_for_update():
- return (
- Allocation.objects.select_related("stock")
- .select_for_update(
- of=(
- "self",
- "stock",
- )
- )
- .order_by("stock__pk")
- )
-
-
def delete_allocations(allocation_pks_to_delete: list[int]):
with transaction.atomic():
return Allocation.objects.filter(
diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.py
index 60fb413ad2..a204d52898 100644
--- a/saleor/warehouse/reservations.py
+++ b/saleor/warehouse/reservations.py
@@ -11,7 +11,8 @@ from django.utils import timezone
from ..core.exceptions import InsufficientStock, InsufficientStockData
from ..core.tracing import traced_atomic_transaction
from ..product.models import ProductVariant, ProductVariantChannelListing
-from .management import sort_stocks, stock_qs_select_for_update
+from .lock_objects import stock_qs_select_for_update
+from .management import sort_stocks
from .models import Allocation, PreorderReservation, Reservation
if TYPE_CHECKING: