mysql - Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction: INSERT INTO -


recently, found lots of deadlock errors in application.

mysql2::error: deadlock found when trying lock; try restarting transaction: insert `products`.... 

the code below:

after user has been created, add products user. don't understand why deadlock happened.

class user < activerecord::base     after_create :add_products     has_many :products, :dependent => :destroy      def self.create_user       user.create!(.......)     end      def add_products       product.add(self, "product_name", 10)     end     ..... end  class product < activerecord::base     belongs_to :user      def self.add(user, product_name, amount)        transaction          product = user.products.find_by_product_name(product_name)          if product             product.increment :amount, amount             product.save!          else             product = self.create! user_id: user.id,                                    product_name: product_name,                                    amount: amount          end        end        product     end end 

i didn't find root cause, can give me advice? in advance!!!

my guess using innodb , doing concurrent insertions.

to trace , understand cause checkout these articles

one way fix issue retry below code

def add_products     retries = 0      begin         product.add(self, "product_name", 10)     rescue  activerecord::statementinvalid => ex         if ex.message =~ /deadlock found when trying lock/ #ex not e!!             retries += 1                raise ex if retries > 3  ## max 3 retries              sleep 10             retry         else             raise ex         end     end end 

or there gems transaction_query handle mysql deadlocks.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -