Skip to content

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

Optimize memory usage of delete_expired_checkouts task (#11175)

Tomasz Szymańskif6edcd7b4f7e
diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.py
index 2fb0282e70..12ea3ef3c0 100644
--- a/saleor/checkout/tasks.py
+++ b/saleor/checkout/tasks.py
@@ -8,6 +8,21 @@ from .models import Checkout
task_logger = get_task_logger(__name__)
+# Batch size of 2000 is about ~27MB of memory usage in task.
+CHECKOUT_BATCH_SIZE = 2000
+
+
+def _batch_tokens(iterable, batch_size=1):
+ length = len(iterable)
+ for index in range(0, length, batch_size):
+ yield iterable[index : min(index + batch_size, length)]
+
+
+def queryset_in_batches(queryset):
+ tokens = queryset.values_list("token", flat=True)
+ for tokens_batch in _batch_tokens(tokens, CHECKOUT_BATCH_SIZE):
+ yield tokens_batch
+
@app.task
def delete_expired_checkouts():
@@ -23,8 +38,14 @@ def delete_expired_checkouts():
empty_checkouts = Q(lines__isnull=True) & Q(
last_change__lt=now - settings.EMPTY_CHECKOUTS_TIMEDELTA
)
- count, _ = Checkout.objects.filter(
+ qs = Checkout.objects.filter(
empty_checkouts | expired_anonymous_checkouts | expired_user_checkout
- ).delete()
- if count:
- task_logger.debug("Removed %s checkouts.", count)
+ )
+
+ deleted_count = 0
+ for tokens_batch in queryset_in_batches(qs):
+ batch_count, _ = Checkout.objects.filter(token__in=tokens_batch).delete()
+ deleted_count += batch_count
+
+ if deleted_count:
+ task_logger.debug("Removed %s checkouts.", deleted_count)