Menu

How I Prevented Overselling with MongoDB Inventory Reservations
📰

How I Prevented Overselling with MongoDB Inventory Reservations

DEV Community: mongodb·Subhankar Roy·4 days ago
#a3NsOXyF
#devtomongodb#devto#dev#stock#reservation
Long article (453 words) — no AI summary yet.
Reading 0:00
15s threshold

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

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.