Tuesday, February 17, 2015

how to handle race conditions?

Hello,

I'm trying to make an app where folks can order X quantity of an item. The condition is that the order should only be made if inventory exists. Assume that we have stock of Y items. This means that only if Y >= X should we allow the sale to go through. And once we accept an order, the inventory should be updated so that Y = Y - X. 

The way I've currently implemented this is with a pair of getter/setter methods. I have a model 'ShopItem' which has two fields called 'quantity' and 'name' (this is unique). I've made a utility class (outside model source file) where I've made the following 2 functions;

def get_quantity(name):
  stuff_left = 0
  try:
    item = ShopItem.objects.get(name=name)
    stuff_left = item.quantity
  except ShopItem.DoesNotExist:
    pass # return zero
  return stuff_left

def set_quantity(name, stuff_left):
  item = ShopItem.objects.get(name=name)
  item.quantity = stuff_left
  item.save()


Elsewhere in my project, if I need to display the remaining quantity of an item in a view, I'll pass the result from get_quantity(). At sale time here is how I update things;

def customer_buy(name, number):
  temp = get_quantity(name)
  if (temp >= number):
    temp = temp - number
    set_quantity(name, temp)
    // do other things
  else:
    // sale failed, do something else

I tested this on my system and things appear to work. But I'm concerned about race conditions. What if two different customers came in to buy the same item? As in; if I only have 7 items in stock, but one customer came to buy 6nos and another 5nos. There is a chance (as per my understanding) that both orders will be accepted - even worse, my inventory will not accurately reflect the updated situation. 

Any ideas on how this issue can be resolved? I've come across this - https://docs.djangoproject.com/en/1.6/ref/models/instances/#updating-attributes-based-on-existing-fields , but not sure how to apply it to the current scenario. 

Learning django,
Abraham V.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7552759e-81d6-4cfb-a0ce-4fed95eef5bc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment