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 .…