Race conditions in Rails first_or_create

activerecord, ruby-on-rails, ruby-on-rails-3

Solution

Yes, it's possible.

You can significantly reduce the chance of conflict with either optimistic or pessimistic locking. Of course optimistic locking requires adding a field to the table, and pessimistic locking doesn't scale as well--plus, it depends on your data store's capabilities.

I'm not sure whether you need the extra protection, but it's available.

Problem

I'm trying to enforce uniqueness of values in one of my table fields. Changing the table isn't an option. I need to use ActiveRecord to conditionally insert a row into the table but I'm concerned about synchronization. Does `first_or_create` in Rails ActiveRecord prevent race conditions? This is the source code for `first_or_create` from GitHub: ``` def first_or_create(attributes = nil, options = {}, &block) first || create(attributes, options, &block) end ``` Is it possible that a duplicate entry will result in the database due to synchronization issues with multiple processes?

Original source

Related problems