Suppose you have an e-commerce web app where the user makes a payment. The user will then receive a virtual item that will be added to their inventory in the database. Suppose I wrote a code to do the following steps in order:
- Check if the order was marked as “complete” previously. If the order is already “complete”, do not continue.
- Then add an item to the user’s inventory.
- Then mark the order as “complete”
The problem in this strategy is that if the code was terminated due to an error after step 2, the order will not be marked as “complete” even though the user already received the item they paid for. How do developers in the e-commerce industry typically handle this issue?
For your information, this is an example code illustrating the steps above while using MongoDB:
order_id = "some id for the payment"
if user_order_is_complete(order_id ) == False: # Step 1: Check first if the order was completed previously
# Step 2: add the item to the user's inventory
filter = {"_id":user_id}
update = {
"$inc": {"item":1}
}
users_collection.update_one(filter=filter, update=update)
# Step 3: Mark the order as complete
filter = {"_id":order_id}
update = {
"$set": {"state":"complete"}
}
orders_collection.update_one(filter=filter, update=update)