
The classic example
Two people buy the last ticket at the same time. Each request does the same three steps: read the stock, check it, write the new value.
Request A read stock 1
Request B read stock 1
Request A stock is 1: sell write stock = 0
Request B stock is 1: sell write stock = 0
Two tickets sold. One existed.Neither request did anything wrong on its own. The bug is in the gap between reading and writing, where the other request slipped in.
Why tests miss it
A test runs one request at a time. The bug needs two, with timing that comes up very rarely. On a developer's laptop it never happens. In production, with enough traffic, rare things happen every week.
Four ways to prevent it
- Do it in one step. Let the database check and subtract together: reduce the stock only where it is above zero, and look at whether a row changed.
- Lock. Take a lock on the row before reading it, so the second request waits its turn.
- Check a version. Save only if the row is still the version you read. If it is not, start again.
- Let a rule refuse it. A unique index makes the database reject the second insert, whatever the timing.
UPDATE tickets SET stock = stock - 1
WHERE id = 7 AND stock > 0;
-- one row changed: sold. no row changed: sold out.Where to look for them
- Anywhere the code reads a value, decides, then writes.
- Check, then create. Is this email taken? No? Create the account.
- Two workers picking up the same job.
- A double click on a button that submits a form.
- Counters and balances.
Questions you will hear in a meeting
- What happens if two of these arrive at the same time?
- Is the check and the write one operation, or two?
- Could two workers take the same job?
In an interview
Raising it yourself is the signal. When you design anything with a balance, a stock count or a unique name, say where two requests could collide and which of the four fixes you would use.