[BUG]:Shop purchase endpoint has a race condition that allows overselling limited stock items
In server/controllers/shopController.js, the purchaseItem function fetches the item with findById, checks item.stock === 0 to decide if it is out of stock, then later in the same function decrements item.stock and calls item.save().
These are separate steps with no locking between them, so under concurrent requests for the same item, multiple purchases can read the same stock value before any of them save their update. Each request individually passes the out of stock check and proceeds to debit points and create a purchase record, meaning a limited stock item with only one unit left can be sold to multiple users at once.
This is the same category of problem that debitPoints in server/services/pointService.js already solves correctly for point balances, using an atomic findOneAndUpdate with a points greater than or equal to amount condition so a user can never spend points they do not have even under concurrent requests. The shop stock check does not use the same pattern, so it remains vulnerable to overselling.
Suggested fix: change the stock check and decrement in purchaseItem to a single atomic operation, for example a findOneAndUpdate on ShopItem with a condition like stock greater than 0 or stock equal to negative 1 for unlimited items, combined with the decrement in the same call, mirroring the approach already used in debitPoints.
Hi @DeadIndian, I'm a GSSoC 26 contributor and would like to work on this issue. I have a clear fix in mind that mirrors the atomic pattern already used in debitPoints. Could I get this assigned to me?
Thank you for raising this issue!
We'll review it as soon as possible. We truly appreciate your contributions! ✨
Meanwhile make sure you've visited the README.md, CONTRIBUTING.md, and CODE_OF_CONDUCT.md before creating a PR for this. Also, please do NOT create a PR until this issue has been assigned to you. 😊
Hi, I'd like to work on this issue. I'll fix the race condition in purchaseItem by replacing the read-then-write stock check with a single atomic findOneAndUpdate (stock > 0 or -1 for unlimited), mirroring the existing debitPoints pattern. Could you please assign it to me?
/assign /claim
Hi,could you assign this issue to me?