How I Prevented Overselling with MongoDB Inventory Reservations
Two customers can try to buy the last unit at the same time. On Elexify, one might be on the Next.js storefront while the other is on the Android app. Both use the same Node.js API, so checkout needs a single place to de
Two customers can try to buy the last unit at the same time. On Elexify, one might be on the Next.js storefront while the other is on the Android app. Both use the same Node.js API, so checkout needs a single place to decide who gets the unit.
I used MongoDB inventory reservations and atomic stock updates to make that decision at the database level.
Check stock and reserve it in the same write
A checkout flow that reads stock and then updates it in a separate operation has a race condition. Two requests can both read 1 before either writes, so both pass the availability check.
Put the availability check in the update filter. Hereβs a simplified Mongoose example. It assumes the API has already validated quantity as a positive integer.
const result = await Inventory.updateOne(
{ _id: inventoryId, available: { $gte: quantity } },
{ $inc: { available: -quantity, reserved: quantity } },
{ session }
);
if (result.matchedCount === 0) {
throw new Error("Insufficient stock");
}
MongoDB applies this update atomically to the inventory document. With one unit left and two requests for one unit each, the first successful update changes available to 0. The other request can no longer match the stock condition.
Keep the reservation and stock update together
When the reservation is stored in a separate document, run both writes in the same transaction and pass the same session to each operation. If creating the reservation fails, the stock update rolls back. For a cart with multiple products, the transaction can also roll back the entire reservation if one item is unavailable.
Make payment finalization safe to retry
A payment gateway can send the same callback more than once or deliver events out of order. On Elexify, payment finalization is idempotent. One way to implement this is to condition each state change on the orderβs current state and commit the order update and reservation consumption together. Once the order is paid, a repeated success callback should leave it paid without consuming its reservation again.
Test the last unit
Start with one unit in stock and send two checkout requests concurrently. Assert that exactly one reservation succeeds and that available stock is 0. Then replay the successful payment callback and verify that the reservation is consumed only once. Elexify runs checkout concurrency and payment reconciliation tests in CI.
For more on how the storefront and Android app share checkout and inventory, see my Elexify engineering case study.
Further reading: MongoDBβs guide to atomicity and transactions.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.