Inventory Reservation and Concurrency Control

If one item remains, two concurrent requests must not both purchase it. A read-then-write sequence without atomic protection can oversell because both requests may read the same available quantity.

Use an atomic conditional update, row-level locking, optimistic concurrency, or a reservation record with uniqueness constraints. For example, decrement inventory only when available >= requestedQuantity; check the affected-row count to determine whether the reservation succeeded.

Reservations need expiry and cleanup, but expiration races with payment confirmation. Use explicit reservation states and version checks so an expired reservation cannot be consumed silently. For high-demand drops, queue admission or per-item serialization may be necessary to protect the inventory store.

Atomic inventory decrement
const result = await Inventory.updateOne(
  { sku, available: { $gte: quantity } },
  { $inc: { available: -quantity } }
);
if (result.modifiedCount !== 1) {
  throw new Error("Insufficient inventory");
}
💡 The predicate and decrement execute as one atomic document update. Validate that quantity is positive, enforce a suitable schema, and use a transaction or reservation model if other records must change atomically.
Key Takeaways
  • Avoid read-then-write inventory checks without concurrency control.
  • Atomic conditional updates can enforce simple stock invariants.
  • Reservation expiry and payment completion require explicit race handling.