Race condition in Django save()

I have an API that can take a list of files and save it in the DB for a specific user. I want to limit the number of files per user to be some number. The way I enforce this is through overriding the save method: A pseudocode: In the view: For item in list_to_save: item.save()

And save method:

curr_count= Files.objects.filter(id=user_id).count If curr_count > max_count: Get curr_count-max_count item For del in delete: del.delete()

The question is, will this lead to a race condition if the same user tries to send 2 different list of files? Since there might be 2 save operations running at the same time?

I am expecting that there is some race condition since the two server will see that DB has entries, and will try to delete them both, leading to some inconsistencies

Yes, this does create a race condition. Since you’re performing an aggregate function (count) on the model, the only way that I can think of to prevent inconsistencies is to acquire a full table lock during your upload processing.