Skip to content
Senior0 views

An online store has one item left, and two users try to buy it at the same time. How can you prevent the inventory quantity from going negative?

Practice

Asked at

AI answer

The stock check and deduction should be performed atomically in the database, not as separate steps in the application. For example, with a conditional update:

UPDATE Products
SET Quantity = Quantity - 1
WHERE Id = @id AND Quantity > 0;

If one row is updated, the product has been reserved; if zero rows are updated, the product is no longer available. The update is performed in a transaction, and the operation’s result is checked. Alternatives include locking the row or using optimistic concurrency with rowversion and retrying. For a lengthy checkout process, a reservation with an expiration time is typically used so that a lock is not held during payment.