0 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?
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.
Also asked at МСДис
- Tell about RabbitMQ and Kafka — what is the difference?
- What concurrent collections do you know and what are they used for?
- How does ValueTask differ from Task?
- Where should you start when looking for the cause of a database query becoming slow?
- Which synchronization primitives in C#/.NET are you familiar with, and what are the characteristics of lock, Mutex, SemaphoreSlim, Interlocked, and volatile?
Similar questions
- What other type of locking is there in a database besides optimistic locking?
- What is transaction isolation in databases, and why is it needed?
- How can you synchronize operations or prevent race conditions between pods at the database level?
- How can you ensure that, when multiple instances of an application are running, the same background job runs on only one instance at a time?
- How can you make an HTTP POST method idempotent?