Stock decrements on order placement without double-counting
Why it matters
Stock decrement outside a database transaction is a textbook race condition: two simultaneous order requests both read stock = 1, both pass the availability check, both write stock = 0, and one physical item ships twice. CWE-362 (Concurrent Execution Using Shared Resource with Improper Synchronization) names this exact failure. At low traffic the window is small but non-zero; at peak sale traffic (Black Friday, flash sales) it becomes near-certain. ISO 25010:2011 fault-tolerance requires the system to handle concurrent requests correctly — a separate findUnique + update pattern fails this at the architecture level, not the implementation level.
Severity rationale
Critical because a race condition in stock decrement causes confirmed orders for items that don't exist, resulting in fulfillment failures and customer refund obligations that grow proportionally with traffic.
Remediation
Wrap the stock check and decrement in a Prisma $transaction in src/app/api/orders/route.ts so both operations execute atomically.
const order = await prisma.$transaction(async (tx) => {
const product = await tx.product.findUnique({ where: { id: productId } })
if (!product || product.stock < quantityOrdered) {
throw new Error('Insufficient stock')
}
await tx.product.update({
where: { id: productId },
data: { stock: { decrement: quantityOrdered } },
})
return tx.order.create({ data: { productId, quantity: quantityOrdered } })
})
For high-concurrency scenarios, consider a Postgres row-level lock (SELECT FOR UPDATE) or an optimistic concurrency check (WHERE stock >= quantityOrdered in the update predicate) to further tighten the window.
DetectionPro
The detection method for this pattern is part of AuditBuffet Pro.
The full method (what to look for, pass and fail conditions, and how results get reported) ships inside the Catalog & Product Logic Audit. The pattern definition, severity rationale, and remediation remain openly licensed under CC-BY-4.0.
External references
- cwe · CWE-362 — Concurrent Execution using Shared Resource with Improper Synchronization (Race Condition)
- iso-25010:2011 · fault-tolerance — Fault Tolerance (Reliability)
Taxons
History
- 2026-04-18·v1.0.0·Initial import from ecommerce-catalog·automated