Design Amazon: Who Gets the Last Item?
What the video says
2 shoppers tap Buy on the last teapot at the same instant. There is 1 box. Who gets it?
In an interview, I'd start simple: read the stock, then write the new number. But both orders read 1 left, and both write 0. 2 orders for 1 box. It oversold.
So lock the item while one shopper checks out? Everyone else queues behind the slowest shopper. Reserve it in the cart? Then carts hoard stock that never sells.
The fix is one atomic step: subtract 1, only if at least 1 is left. The first write wins, and the counter flips to 0. The second is told no at once: sold out.
And every order carries its own ID, so a double tap or a retry counts once.
Amazon has not published how checkout picks a winner. But in 2007 its Dynamo paper said Add to Cart can never be forgotten or rejected. And AWS documents a conditional write: it succeeds only if its conditions are met.
So that's the design. 1 counter, 1 atomic check and subtract, an instant no for the loser, and an ID on every order.
Follow for the next system. Next time, how can a Spotify playlist play offline?
Sources
Every fact in the video was checked against these when it was made.
- DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store
- AWS, Working with items and attributes in DynamoDB: Conditional writes
- Berenson et al., A Critique of ANSI SQL Isolation Levels
- Locking Reads
- PostgreSQL 18, 13.3 Explicit Locking
- PostgreSQL 18, 13.2 Transaction Isolation
- Featonby, Making retries safe with idempotent APIs