Skip to content
RED SAGSkills
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)
}
Choose one answer

Discussion 0

Join free to post in the discussion.

Related questions