dj-paddle icon indicating copy to clipboard operation
dj-paddle copied to clipboard

Race condition when listening on both `subscription_payment_succeeded` and `subscription_created` for new subscriptions

Open tkainrad opened this issue 2 years ago • 0 comments

  • dj-paddle version:
  • 0.1.2

Description

After upgrading to 0.1.2 I started to see errors with every new subscription:

IntegrityError at /paddle/webhook/
(1062, "Duplicate entry 'xxxxxxx' for key 'PRIMARY'")

It turns out the problem is that now both subscription_payment_succeeded and subscription_created try to create a new subscription entry in the database in parallel. subscription_payment_succeeded was added to the subscription_event with 0.1.2.

The code documentation for Subscription does not mention subscription_payment_succeeded as possible trigger.

Fortunately, the problem is not severe, as the first webhook invocation (subscription_created) will succeed at creating the subscription. The second call will fail with no consequence, the retry from Paddle will then succeed when the Subscription instance can already be found in the database.

A get_or_create should solve the problem here:

        try:
            subscription = cls.objects.get(pk=pk)
        except cls.DoesNotExist:
            return cls.objects.create(pk=pk, **data)

tkainrad avatar Sep 18 '21 06:09 tkainrad