ORIGINAL TECHNICAL PRACTICE
Avoid a read-modify-write race
Two requests both read an inventory count of1 and both decrement it. How would you enforce the rule that inventory never becomes negative?
Written for independent practice. The model answer presents one approach; clarify constraints and explain alternatives.
A REASONED APPROACH
Model answer.
The invariant belongs in an atomic storage operation or transaction. A separate application read followed by a write allows both requests to act on the same stale value.
Work through it
- Use a conditional update such as decrementing only where quantity>0, then inspect whether a row was actually updated.
- Keep related reservation and inventory changes in the same transaction when the business rule spans multiple records. Handle serialization failures or deadlocks according to the database’s contract.
- Test concurrent attempts against the last available item and retries of the same logical reservation. Separate atomicity from idempotency: both may be required.
Tradeoffs to discuss
- Pessimistic locking can serialize contention; optimistic conditional writes require conflict handling. The right choice depends on throughput, data layout and the required invariant.
Common pitfalls
- An in-process lock does not coordinate multiple server instances. A successful HTTP retry must not accidentally reserve inventory a second time.