Interview question
Reserve inventory with one atomic conditional update
Uses a conditional update and transaction to prevent overselling while recording the reservation consistently.
TL;DR
Uses a conditional update and transaction to prevent overselling while recording the reservation consistently.
Atomic predicates, affected-row checks, transactions, rollback behavior, and concurrent correctness.
Practice the problem like a real interview: restate, reason, implement, and test.
Tables: Inventory(ProductId, AvailableQuantity) and InventoryReservations(ReservationId, ProductId, Quantity, CreatedAtUtc). Decrease available quantity and insert a reservation only when AvailableQuantity >= @Quantity. Otherwise return an error and change nothing.
Two requests concurrently try to reserve 4 units when 5 remain. Only one conditional update can affect the inventory row; the other sees insufficient remaining quantity and fails.
@Quantity > 0 before executing the transaction.I put the availability rule in the UPDATE predicate so checking and decrementing are one atomic statement. @@ROWCOUNT tells me whether the reservation won the race. A transaction then couples that inventory change to the reservation record, and XACT_ABORT plus TRY/CATCH ensures an insert failure does not leave stock decremented.
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
UPDATE dbo.Inventory
SET AvailableQuantity = AvailableQuantity - @Quantity
WHERE ProductId = @ProductId
AND AvailableQuantity >= @Quantity;
IF @@ROWCOUNT = 0
THROW 50001, 'Insufficient inventory or unknown product.', 1;
INSERT dbo.InventoryReservations
(ReservationId, ProductId, Quantity, CreatedAtUtc)
VALUES
(@ReservationId, @ProductId, @Quantity, SYSUTCDATETIME());
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
ROLLBACK TRANSACTION;
THROW;
END CATCH;
The update targets one primary-key row, so lock scope is small and contention is localized to the product being reserved. Hot products may still serialize heavily. A unique key on ReservationId is important when callers can retry the operation.
@@ROWCOUNT after the conditional update.Move to the linked follow-up, next path step, prerequisite, or deeper variant.
Practice the next layer of the same subject.