Skip to content

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

Improve performance of Celery task deleting inactive checkouts (#12466)

Mikacb276a94ae83
diff --git a/saleor/checkout/migrations/0055_add_last_change_idx.py b/saleor/checkout/migrations/0055_add_last_change_idx.py
new file mode 100644
index 0000000000..8189209e21
--- /dev/null
+++ b/saleor/checkout/migrations/0055_add_last_change_idx.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.18 on 2023-03-24 09:51
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0054_alter_checkout_options"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="checkout",
+ name="last_change",
+ field=models.DateTimeField(auto_now=True, db_index=True),
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0058_merge_0055_add_last_change_idx.py b/saleor/checkout/migrations/0058_merge_0055_add_last_change_idx.py
new file mode 100644
index 0000000000..4502857c11
--- /dev/null
+++ b/saleor/checkout/migrations/0058_merge_0055_add_last_change_idx.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.18 on 2023-04-03 08:27
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0055_add_last_change_idx"),
+ ("checkout", "0057_remove_metadata_from_checkout_model_state"),
+ ]
+
+ operations = []
diff --git a/saleor/checkout/migrations/0059_merge_0058.py b/saleor/checkout/migrations/0059_merge_0058.py
new file mode 100644
index 0000000000..ed5968cf1a
--- /dev/null
+++ b/saleor/checkout/migrations/0059_merge_0058.py
@@ -0,0 +1,12 @@
+# Generated by Django 3.2.18 on 2023-04-03 08:36
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0058_auto_20230313_1602"),
+ ("checkout", "0058_merge_0055_add_last_change_idx"),
+ ]
+
+ operations = []
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 2959044679..3efe82c558 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -40,7 +40,7 @@ class Checkout(models.Model):
"""A shopping checkout."""
created_at = models.DateTimeField(auto_now_add=True)
- last_change = models.DateTimeField(auto_now=True)
+ last_change = models.DateTimeField(auto_now=True, db_index=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=True,
diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.py
index 12ea3ef3c0..f15c44e049 100644
--- a/saleor/checkout/tasks.py
+++ b/saleor/checkout/tasks.py
@@ -1,51 +1,97 @@
+import logging
+from typing import Tuple
+
from celery.utils.log import get_task_logger
from django.conf import settings
-from django.db.models import Q
+from django.db.models import Exists, OuterRef, Q, QuerySet, Subquery
from django.utils import timezone
from ..celeryconf import app
-from .models import Checkout
-
-task_logger = get_task_logger(__name__)
+from .models import Checkout, CheckoutLine
-# Batch size of 2000 is about ~27MB of memory usage in task.
-CHECKOUT_BATCH_SIZE = 2000
+task_logger: logging.Logger = get_task_logger(__name__)
-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 delete_expired_checkouts(
+ batch_size: int = 2000,
+ batch_count: int = 5,
+ invocation_count: int = 1,
+ invocation_limit: int = 500,
+) -> Tuple[int, bool]:
+ """Delete inactive checkouts from the database.
+ Inactivity is based on the "Checkout.last_change" datetime column.
-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
+ Deletes:
+ - Anonymous checkouts after 30 days of inactivity no matter if it has lines or not,
+ configurable through ``settings.ANONYMOUS_CHECKOUTS_TIMEDELTA``.
+ - Users checkouts after 90 days of inactivity no matter if it has lines or not,
+ configurable via``settings.USER_CHECKOUTS_TIMEDELTA``.
+ - All anonymous and users checkouts after 6h of inactivity
+ if there are no lines associated, refer to ``settings.EMPTY_CHECKOUTS_TIMEDELTA``.
+ :param batch_size: The maximum row count that can be deleted per ``DELETE FROM``
+ SQL statement. Around 13.5 KB of memory will be utilized by the Celery
+ worker per row, thus 2000 will be using around 27 MB.
+ :param batch_count: How many batches can be executed in a single task.
+ This limits how long can the task run as there may be lots of checkouts
+ to delete.
+ :param invocation_count: How many times the task re-triggered itself up.
+ :param invocation_limit: The maximum times the task can re-trigger itself up
+ in order to limit how long it may run.
-def delete_expired_checkouts():
+ :return: A tuple containing row count deleted (int)
+ and whether there is more to delete (bool).
+ """
now = timezone.now()
+
expired_anonymous_checkouts = (
- Q(email__isnull=True)
+ Q(last_change__lt=now - settings.ANONYMOUS_CHECKOUTS_TIMEDELTA)
+ & Q(email__isnull=True)
& Q(user__isnull=True)
- & Q(last_change__lt=now - settings.ANONYMOUS_CHECKOUTS_TIMEDELTA)
)
- expired_user_checkout = (Q(email__isnull=False) | Q(user__isnull=False)) & Q(
+ expired_user_checkout = Q(
last_change__lt=now - settings.USER_CHECKOUTS_TIMEDELTA
+ ) & (Q(email__isnull=False) | Q(user__isnull=False))
+ empty_checkouts = Q(last_change__lt=now - settings.EMPTY_CHECKOUTS_TIMEDELTA) & ~Q(
+ Exists(
+ # Type ignore reason: Subquery can be used inside Exists()
+ # https://github.com/typeddjango/django-stubs/issues/985
+ Subquery( # type: ignore[arg-type]
+ CheckoutLine.objects.filter(checkout_id=OuterRef("pk"))
+ )
+ )
)
- empty_checkouts = Q(lines__isnull=True) & Q(
- last_change__lt=now - settings.EMPTY_CHECKOUTS_TIMEDELTA
- )
- qs = Checkout.objects.filter(
+
+ qs: QuerySet[Checkout] = Checkout.objects.filter(
empty_checkouts | expired_anonymous_checkouts | expired_user_checkout
)
+ qs = qs.only("pk").order_by()[:batch_size]
+
+ total_deleted: int = 0
+ has_more: bool = True
+ for batch_number in range(batch_count):
+ deleted_count, _ = Checkout.objects.filter(pk__in=qs.values_list("pk")).delete()
+ total_deleted += deleted_count
+
+ # Stop deleting inactive checkouts if there was no match.
+ if deleted_count < batch_size:
+ has_more = False
+ break
- 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 total_deleted:
+ task_logger.debug("Deleted %d checkouts.", total_deleted)
- if deleted_count:
- task_logger.debug("Removed %s checkouts.", deleted_count)
+ if has_more:
+ if invocation_count < invocation_limit:
+ # Continue deleting checkouts as there may be still more to delete.
+ delete_expired_checkouts.delay(
+ batch_size=batch_size,
+ batch_count=batch_count,
+ invocation_count=invocation_count + 1,
+ invocation_limit=invocation_limit,
+ )
+ else:
+ task_logger.warning("Invocation limit reached, aborting task")
+ return total_deleted, has_more
diff --git a/saleor/checkout/tests/test_tasks.py b/saleor/checkout/tests/test_tasks.py
index a6d96972b1..3a17beeaf7 100644
--- a/saleor/checkout/tests/test_tasks.py
+++ b/saleor/checkout/tests/test_tasks.py
@@ -1,4 +1,6 @@
from datetime import timedelta
+from unittest import mock
+from uuid import UUID
import pytest
from django.utils import timezone
@@ -168,12 +170,7 @@ def test_delete_empty_checkouts(checkouts_list, customer_user, variant):
)
Checkout.objects.bulk_update(
- [
- empty_checkout_1,
- empty_checkout_2,
- empty_checkout_3,
- not_empty_checkout,
- ],
+ [empty_checkout_1, empty_checkout_2, empty_checkout_3, not_empty_checkout],
["last_change", "email", "user"],
)
@@ -213,11 +210,7 @@ def test_delete_expired_checkouts(checkouts_list, customer_user, variant):
assert empty_checkout.lines.count() == 0
Checkout.objects.bulk_update(
- [
- expired_anonymous_checkout,
- expired_user_checkout,
- empty_checkout,
- ],
+ [expired_anonymous_checkout, expired_user_checkout, empty_checkout],
["created_at", "last_change", "email", "user"],
)
@@ -240,3 +233,122 @@ def test_delete_expired_checkouts_no_checkouts_to_delete(checkout):
# then
assert Checkout.objects.count() == checkout_count
+
+
[email protected]("saleor.checkout.tasks.delete_expired_checkouts.delay")
+def test_delete_checkouts_until_done(mocked_task: mock.MagicMock, channel_USD):
+ """
+ Ensure the Celery task ``delete_expired_checkouts`` deletes all inactive
+ checkouts from the database until there are none left to delete.
+
+ Given the settings:
+ - Max 2 inactive checkouts to delete per single ``DELETE FROM`` SQL statement
+ - A maximum of 3 ``DELETE FROM`` SQL statements may be run per task (totalling
+ to a max 6 inactivate checkout/task).
+
+ Database data:
+ - 7 inactive checkouts
+
+ The expected flow is:
+ 1. Deletes 2 checkouts three times (three SQL statement expected)
+ 2. Triggers a new task due to having still inactive checkouts left to be
+ deleted (1 checkout left).
+ """
+
+ # Create 7 empty checkouts in DB
+ Checkout.objects.bulk_create(
+ [
+ Checkout(
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ token=UUID(int=checkout_id),
+ )
+ for checkout_id in range(7)
+ ]
+ )
+ Checkout.objects.update(last_change=timezone.now() - timedelta(hours=7))
+
+ task_params = {
+ "batch_size": 2,
+ "batch_count": 3,
+ "invocation_limit": 10,
+ }
+ mocked_task.assert_not_called()
+
+ # Delete inactive checkouts.
+ deleted_count, has_more = delete_expired_checkouts(
+ **task_params, invocation_count=1
+ )
+ assert deleted_count == 6
+ assert has_more is True
+ assert (
+ Checkout.objects.count() == 1
+ ), "Should have deleted 6 checkouts thus only 1 should be left"
+
+ # Should have triggered a new task to delete more checkouts
+ mocked_task.assert_called_once_with(**task_params, invocation_count=2)
+ mocked_task.reset_mock()
+
+ # Ensure we delete the remaining, and we do not trigger anymore task.
+ deleted_count, has_more = delete_expired_checkouts(
+ **task_params, invocation_count=2
+ )
+ assert deleted_count == 1
+ assert has_more is False
+ assert (
+ Checkout.objects.count() == 0
+ ), "Should have deleted the last remaining checkout (one)"
+
+ # Shouldn't have triggered a new task as nothing is left to be deleted.
+ mocked_task.assert_not_called()
+
+
[email protected]("saleor.checkout.tasks.delete_expired_checkouts.delay")
+def test_aborts_deleting_checkouts_when_invocation_count_exhausted(
+ mocked_task: mock.MagicMock, channel_USD
+):
+ """
+ Ensure the Celery task stops triggering tasks when the invocation limit is reached.
+ """
+
+ # Create 3 empty checkouts in DB
+ Checkout.objects.bulk_create(
+ [
+ Checkout(
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ token=UUID(int=checkout_id),
+ )
+ for checkout_id in range(3)
+ ]
+ )
+ Checkout.objects.update(last_change=timezone.now() - timedelta(hours=7))
+
+ mocked_task.assert_not_called()
+ task_params = {
+ "batch_size": 1,
+ "batch_count": 1,
+ "invocation_limit": 2,
+ }
+
+ # Invocation #1, should delete 1 checkout
+ deleted_count, has_more = delete_expired_checkouts(
+ **task_params, invocation_count=1
+ )
+ assert deleted_count == 1
+ assert has_more is True
+
+ # Should have triggered a new task to delete more checkouts
+ mocked_task.assert_called_once_with(**task_params, invocation_count=2)
+ mocked_task.reset_mock()
+
+ # Invocation #2, should delete 1 checkout and should stop there (has_more=True
+ # & no more task.delay()).
+ deleted_count, has_more = delete_expired_checkouts(
+ **task_params, invocation_count=2
+ )
+ assert deleted_count == 1
+ assert has_more is True
+
+ # Should have stopped there
+ mocked_task.assert_not_called()