Internal IDs are not atomic

The code for generating internal IDs (iids) is as follows:

def set_iid
  if iid.blank?
    records = project.send(self.class.name.tableize)
    records = records.with_deleted if self.paranoid?
    max_iid = records.maximum(:iid)
                                                     
    self.iid = max_iid.to_i + 1
  end
end

This code is not atomic, meaning it's possible for 2 issues trying to use the same iid. This will lead to a unique constraint failure, resulting in errors showing up to a user. We're seeing this in our PostgreSQL logs in the form of:

ERROR: duplicate key value violations
  - unique constraint "index_issues_on_project_id_and_iid"

This method should be made atomic somehow, or the issue creation process should retry in case of unique constraints.