Q51 [Scenario]: High concurrent orders cause item stock counts to drop below zero. How do you prevent inventory race conditions?

Avoid checking inventory client-side (if (item.stock > 0) item.save()). Instead, use an atomic update with a query filter condition: Item.updateOne({ _id: itemId, stock: { $gte: quantity } }, { $inc: { stock: -quantity } }). If modifiedCount === 0, inventory was insufficient, preventing negative stock levels atomically.

Atomic Inventory Reduction
const result = await Item.updateOne(
  { _id: itemId, stock: { $gte: orderQty } }, // Condition filter
  {$inc: { stock: -orderQty } } // Atomic reduction
);

if (result.modifiedCount === 0) {
  throw new Error('Insufficient inventory or item out of stock');
}

Decrements stock atomically on the database server strictly if stock is greater than or equal to order quantity.

Key Takeaways
  • Combine range filters directly inside atomic update queries.

  • Eliminates client-side check-then-set race conditions.

Knowledge Check

Why does client-side stock checking (if stock > 0) fail under high concurrent write loads?