I have dozens of concurrent Celery workers creating, updating, and deleting data from various models in my Django application. I'm running into the following error:
deadlock detected
DETAIL: Process 3285070 waits for ShareLock on transaction 559341801; blocked by process 3285058.
Process 3285058 waits for ShareLock on transaction 559341803; blocked by process 3285070.
HINT: See server log for query details.
And these are the blocks of code where it's throwing the error:
with transaction.atomic():
for score in list_of_scores_to_update:
score.save()
time_delta = timezone.now() - timezone.timedelta(minutes=2)
with transaction.atomic():
Score.objects.select_for_update(of=('self'), skip_locked=True).filter(checked_date__lte=time_delta).delete()
How can I prevent these deadlocks by acquiring a write lock on all of the rows prior to updating them?