Your e-commerce application has a critical bug: occasionally, when two users purchase the last item in stock simultaneously, both purchases succeed, resulting in negative inventory. This is a classic "lost update" race condition.
The purchase flow works as follows:
async function purchaseItem(userId: string, itemId: string, quantity: number) {
// Step 1: Read current inventory
const item = await prisma.item.findUnique({ where: { id: itemId } });
// Step 2: Check availability
if (item.stockQuantity < quantity) {
throw new Error('Insufficient stock');
}
// Step 3: Decrement inventory
await prisma.item.update({
where: { id: itemId },
data: { stockQuantity: item.stockQuantity - quantity }
});
// Step 4: Create order
await prisma.order.create({
data: { userId, itemId, quantity, status: 'CONFIRMED' }
});
}
The Race: Between Step 1 (read) and Step 3 (write), another request can read the same stock quantity, pass the check in Step 2, and also proceed to decrement. Both requests see stockQuantity = 1, both pass the >= 1 check, and both set the stock to 0. But two items were sold when only one existed.