Sanjaay Gowda T S
All practice questions

ORIGINAL TECHNICAL PRACTICE

Avoid a read-modify-write race

Software engineeringMediumConcept

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

  1. Use a conditional update such as decrementing only where quantity>0, then inspect whether a row was actually updated.
  2. 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.
  3. 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.

KEEP PRACTISING

Related questions.

Keep learning beyond the interview.

Explore the Learning Hub