PostgreSQLQuestion 07 of 11
Two requests buy the last item — how do you avoid a race?
Answer out loud or in your head first, then compare.
Answer
I don't do a separate SELECT, a check in JS and an unconditional UPDATE. I check availability and decrement the stock in one atomic statement.
SQL
-- inventory(product_id PRIMARY KEY, stock integer NOT NULL)
UPDATE inventory
SET stock = stock - 1
WHERE product_id = 42 AND stock > 0
RETURNING stock;Result: no row returned means no such product or no stock left. Under the default Read Committed, a concurrent UPDATE waits and re-evaluates the condition after the competing change.
To be precise: if the order and the stock must be saved together, you need a transaction. An alternative for complex logic: SELECT FOR UPDATE and the update in the same transaction. Higher isolation may require retries.
How did it go? Be honest — “Not yet” puts the question on your review list.
Related questions
- D03 · Why might a transaction alone not be enough to protect a limit? — Backend, data and system design