Use transactions. Each transaction is ensuring the consistency of the data (quantity >= 0) at the end of the transaction.
Consistency should be checked exclusively, so no two transactions are allowed to modify quantity at the same time.
OR
Do what amazon does – accept the order (no commitment), no modifying of the quantity. Next step is – the services try to process the order (transactions run here), and if something goes wrong (exclusive consistency check), send the order denial message to the customer.
This last approach more fits high availability requirements, when the order processing cannot be afforded within each UI request.
About Transactions
Database transactions would be one way to implement. e.g. in T-SQL:
begin transaction
set @quantity = select Quantity from Products where ProductName="AAA"
if @quantity >= @orderedQuantity
begin
update Products set Quantity = Quantity - @orderedQuantity
where ProductName="AAA"
commit transaction
end
else begin
rallback transaction
end
In general, your transaction needs to make sure that it acquires exclusive write lock over the record it’s going to update, and commit data after the consistency check. If the consistency check does not pass, roll back.
2
solved 100000 users concurrent to buy the same product in ASP.NET