Topic: Race condition unbreakable generating next order number
I have simple order model and i need to generate order numbers (10000, 10001, ...) and i have all orders from many stores in one table so i cannot rely on sequence auto increments in database.
Proof of concept is something like:
last = Order.find(:first, :conditions => ["store_id = ?", self.store.id], :order => 'created_on DESC')
if last.nil? then
self.no = 10_000
self.no = last.no.to_i + 1 # increment No
But of course it is easily brekable by two concurent requests, any ideas how to make it race condition free?