Skip to content

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

Fix deadlocks on attributeValueUpdate (#10696)

Tomasz Szymański6eb11d58ad42
diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.py
index c0995372f4..ba16b0faec 100644
--- a/saleor/graphql/attribute/mutations.py
+++ b/saleor/graphql/attribute/mutations.py
@@ -2,7 +2,8 @@ from typing import TYPE_CHECKING
import graphene
from django.core.exceptions import ObjectDoesNotExist, ValidationError
-from django.db.models import Exists, OuterRef, Q
+from django.db import transaction
+from django.db.models import Exists, OuterRef, Q, Subquery
from django.utils.text import slugify
from ...attribute import ATTRIBUTE_PROPERTIES_CONFIGURATION, AttributeInputType
@@ -752,14 +753,32 @@ class AttributeValueUpdate(AttributeValueCreate):
@classmethod
def post_save_action(cls, info, instance, cleaned_input):
- variants = product_models.ProductVariant.objects.filter(
- Exists(instance.variantassignments.filter(variant_id=OuterRef("id")))
- )
+ with transaction.atomic():
+ variants = product_models.ProductVariant.objects.filter(
+ Exists(instance.variantassignments.filter(variant_id=OuterRef("id")))
+ )
+ # SELECT … FOR UPDATE needs to lock rows in a consistent order
+ # to avoid deadlocks between updates touching the same rows.
+ qs = (
+ product_models.Product.objects.select_for_update(of=("self",))
+ .filter(
+ Q(
+ Exists(
+ instance.productassignments.filter(
+ product_id=OuterRef("id")
+ )
+ )
+ )
+ | Q(Exists(variants.filter(product_id=OuterRef("id"))))
+ )
+ .order_by("pk")
+ )
+ # qs is executed in a subquery to make sure the SELECT statement gets
+ # properly evaluated and locks the rows in the same order every time.
+ product_models.Product.objects.filter(
+ pk__in=Subquery(qs.values("pk"))
+ ).update(search_index_dirty=True)
- product_models.Product.objects.filter(
- Q(Exists(instance.productassignments.filter(product_id=OuterRef("id"))))
- | Q(Exists(variants.filter(product_id=OuterRef("id"))))
- ).update(search_index_dirty=True)
manager = load_plugin_manager(info.context)
manager.attribute_value_updated(instance)
manager.attribute_updated(instance.attribute)