lundi 10 août 2015

handling parallel requests with updating inventory stock

I am using rails 3.0.20 and mysql in my inventory application. As a standard, I'm mainting stock value in purchase items table and every time stock value will be modified when item is sold/returned. Here are my models code:

purchase_item.rb

attr_accessible :id, :item_id, :batch, :stock, selling price..

def cal_stock(qty)
  self.stock = stock - qty
end

order.rb

attr_accessible :id, :date, :purchase_item_id, :sold_qty

after_save :reduce_purchase_stock

private
def reduce_purchase_stock
  qty = sold_qty - sold_qty_was.to_i
  purchase_item.cal_stock(qty)
  purchase_item.save(:validate => false) 
end

I need to generate the report for item's stock on selected date. I don't get any better idea than saving original stock value after sales in new column(stock_after_sold) of orders table. Edited code of order.rb model as

order.rb

attr_accessible :id, :purchase_item_id, :date, :sold_qty, :stock_after_sold

before_save :assign_stock_after_sales
after_save :reduce_purchase_stock

private
def assign_stock_after_sales
  qty = sold_qty - sold_qty_was.to_i
  purchase_item.cal_stock(qty)
  self.stock_after_sold = purchase_item.stock
end

def reduce_purchase_stock
  purchase_item.reload
  qty = sold_qty - sold_qty_was.to_i
  purchase_item.cal_stock(qty)
  purchase_item.save(:validate => false) 
end

Problem: I started testing with more number of parallel requests using script(thread) for same purchase item, Invalid stock value is saved in stock_after_sold column. Following example illustrate problem.

Started POST "/orders" for domain at 2015-08-10 15:35:02 +0530
Started POST "/orders" for domain at 2015-08-10 15:35:02 +0530
Started POST "/orders" for domain at 2015-08-10 15:35:02 +0530
Started POST "/orders" for domain at 2015-08-10 15:35:02 +0530
Started POST "/orders" for domain at 2015-08-10 15:35:02 +0530
Started POST "/orders" for domain at 2015-08-10 15:35:02 +0530
Started POST "/orders" for domain at 2015-08-10 15:35:02 +0530

Saved records in orders table.

enter image description here

Any idea/ help is very much appreciated.

Aucun commentaire:

Enregistrer un commentaire