0

I'm building an auction-like system in Rails 3 (using PostgreSQL as the database).

Imagine you have a Product. A product has many Bids.

I'm worried with what happens when 2 different users click "Bid" at the same time (providing I have at least 2 application servers, and they hit the servers at the same time). I have two possible acceptable behaviors for this:

  • one of them "wins", and the other receives an error message
  • one of them "wins", and the other bid is created next (each bid adds 0.01€ to the price). So all the concurrent bids are repeated until created

So my question is: how to handle this problem on Rails 3? I think using regular transactions isn't enough, or is it?

rubenfonseca
  • 699
  • 10
  • 26

1 Answers1

3

Rails pessimistic locking should allow you to achieve what you want. As far as I am aware this would let you handle the issue of ordering your updates to the database without throwing errors.

Here is a thread that explains the two different types of locking better that I can: Optimistic vs. Pessimistic locking

Community
  • 1
  • 1
Devin M
  • 9,636
  • 2
  • 33
  • 46
  • Thanks! I've read your links, and agree that pessimistic locking is the way to go. I used Product.find(id, :lock => true) and it seems to generate the correct SQL on PostgreSQL. As a bonus, any other transaction that runs the same line waits inline for the lock to be removed, so I can easily implement the option 2 from my question. – rubenfonseca Aug 23 '11 at 22:46
  • Awesome, thats great that it worked for you. Good luck with your application! – Devin M Aug 23 '11 at 23:05