3

As our Rails application deals with increasing user activity and load, we're starting to see some issues with simultaneous transactions. We've used JavaScript to disable / remove the buttons after clicks, and this works for the most part, but isn't an ideal solution. In short, users are performing an action multiple times in rapid succession. Because the action results in a row insert into the DB, we can't just lock one row in the table. Given the high level of activity on the affected models, I can't use the usual locking mechanims ( http://guides.rubyonrails.org/active_record_querying.html#locking-records-for-update ) that you would use for an update.

This question ( Prevent simultaneous transactions in a web application ) addresses a similar issue, but it uses file locking (flock) to provide a solution, so this won't work with multiple application servers, as we have. We could do something similar I suppose with Redis or another data store that is available to all of our application servers, but I don't know if this really solves the problem fully either.

What is the best way to prevent duplicate database inserts from simultaneously executed transactions?

Community
  • 1
  • 1
shedd
  • 4,198
  • 4
  • 33
  • 42

1 Answers1

4

Try adding a unique index to the table where you are having the issue. It won't prevent the system from attempting to insert duplicate data, but it will prevent it from getting stored in the database. You will just need to handle the insert when it fails.

Peter Brown
  • 50,956
  • 18
  • 113
  • 146
  • Thanks - I'm testing a multi-key unique constraint on the table, which is a good suggestion and certainly should prevent the inserts. Was just curious if there were any other recommendations on how to prevent this. I appreciate the response. – shedd Jan 05 '12 at 22:02