Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database lock not working as expected with Rails & Postgres

I have the following code in a rails model:

foo = Food.find(...)
foo.with_lock do
  if bar = foo.bars.find_by_stuff(stuff)
    # do something with bar
  else
    bar = foo.bars.create!
    # do something with bar
  end
end

The goal is to make sure that a Bar of the type being created is not being created twice.

Testing with_lock works at the console confirms my expectations. However, in production, it seems that in either some or all cases the lock is not working as expected, and the redundant Bar is being attempted -- so, the with_lock doesn't (always?) result in the code waiting for its turn.

What could be happening here?

update so sorry to everyone who was saying "locking foo won't help you"!! my example initially didin't have the bar lookup. this is fixed now.

like image 906
John Bachir Avatar asked Jul 03 '12 14:07

John Bachir


2 Answers

You're confused about what with_lock does. From the fine manual:

with_lock(lock = true)

Wraps the passed block in a transaction, locking the object before yielding. You pass can the SQL locking clause as argument (see lock!).

If you check what with_lock does internally, you'll see that it is little more than a thin wrapper around lock!:

lock!(lock = true)

Obtain a row lock on this record. Reloads the record to obtain the requested lock.

So with_lock is simply doing a row lock and locking foo's row.

Don't bother with all this locking nonsense. The only sane way to handle this sort of situation is to use a unique constraint in the database, no one but the database can ensure uniqueness unless you want to do absurd things like locking whole tables; then just go ahead and blindly try your INSERT or UPDATE and trap and ignore the exception that will be raised when the unique constraint is violated.

like image 108
mu is too short Avatar answered Oct 28 '22 06:10

mu is too short


The correct way to handle this situation is actually right in the Rails docs:

http://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by

begin
  CreditAccount.find_or_create_by(user_id: user.id)
rescue ActiveRecord::RecordNotUnique
  retry
end

("find_or_create_by" is not atomic, its actually a find and then a create. So replace that with your find and then create. The docs on this page describe this case exactly.)

like image 24
Gal Avatar answered Oct 28 '22 07:10

Gal