Nested transaction.atomic loops with locks

With a Django 5.0.2 and PostgreSQL 14 (Azure Database Flexible Server) setup, I have this piece of code which, basically, translates to:

with transaction.atomic():
    objects = ObjectModel.objects.all():
    for object in objects:
        with transaction.atomic():
            another_object = AnotherObjectModel.objects.select_for_update().get(id=1000)
        # ...

I've been having quite a few crashes in my database and this has proven to be the point where the bottleneck happens. As it's legacy code (and forgive me the blame game) and I cannot trace any documentation or testimony as to why it was implemented like this, would anyone have a point of view of how this could or could not be a cause for the crash?

Please forgive me if this is not too explicit or not compliant to the forum's rules, I'll be more than happy to try to elaborate.

I have not tried anything so far, I'm afraid.

Back to Top