hard20 pts · first answer countsdatabasesconcurrency
Two buyers, one item left
Two users buy the last item at the same moment and both orders succeed, making stock -1. What is the best fix?
const item = await db.query("SELECT stock FROM items WHERE id = $1", [id])
if (item.stock > 0) {
await db.query("UPDATE items SET stock = stock - 1 WHERE id = $1", [id])
await createOrder(id)
}Discussion 0
Join free to post in the discussion.
Related questions
- The N+1 query problemFull Stack Developer
- Offset vs cursor paginationFull Stack Developer
- Renaming a column safelyFull Stack Developer
- Too many database connectionsFull Stack Developer
- Write skew under snapshot isolationFull Stack Developer
- Two agents edit one ticketFull Stack Developer
- Duplicate emails despite a checkBackend Developer
- Optimistic lock update hits 0 rowsBackend Developer