PostgreSQL and ActiveRecord subselect for race condition
问题 I'm experiencing a race condition in ActiveRecord with PostgreSQL where I'm reading a value then incrementing it and inserting a new record: num = Foo.where(bar_id: 42).maximum(:number) Foo.create!({ bar_id: 42, number: num + 1 }) At scale, multiple threads will simultaneously read then write the same value of number . Wrapping this in a transaction doesn't fix the race condition because the SELECT doesn't lock the table. I can't use an auto increment, because number is not unique, it's only