'Rails, custom Postgres sequence and possible concurrency issue

I have a Postgres photos table, with ids as UUIDs, not INT (primary keys). As I store the photos in directories, I created a custom field "file_id", with it's own sequence to get a uniq id for each record.

enter image description here

In my rails app (Rails 6.1), the photo model uses this code to get the next folder file_id to create:

  # need a file_id to store the file in a directory (can't use the uuid)
  before_create :build_file_id
  def build_file_id
    self.file_id = ActiveRecord::Base.connection.execute("select nextval('usr_photos_file_id_seq')").first["nextval"]
  end

Then my photo uploader creates the folders to store the photo using the file_id:

# id path
id_path = ("%012d".freeze % record.file_id).scan(/\d{3}/).join("/".freeze)   

This works very well for my simple tests:

this gives for example directories like : 000/001/002/003/original/image.jpg

However, I have some doubts about possible concurrency issues when many requests will add photos to the app.

How to be sure that each photo will be added correctly to the right directory created by the sequence ? Does select nextval('usr_photos_file_id_seq') is sure concurrently and 'reserved' by Postgres when the photo is copied ?

Thanks,



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source