10 lakh people hit "Buy Now" at the exact same time during a flash sale. Only 2 units are left.
How does Amazon make sure it does not sell the same item 10 lakh times? I’m a Backend engineer and I love these types of questions; let’s break it down.
One simple answer that comes to mind is: "Just update the database." But this falls apart the moment traffic spikes.
The problem here is not inventory storage. It is concurrent reservation under extreme contention. Here is the high-level way to think about it:
1. Fast gate in front of the DB
You do not want all 10 lakh requests hammering the database. So systems often keep a fast in-memory inventory counter, usually in something like Redis.
If stock = 2, only the first 2 atomic decrements succeed.
Everyone else gets rejected immediately.
That gives you a very cheap first filter.
2. Atomic decrement matters
This has to happen as one indivisible step.
Not:
- read stock
- subtract 1
- write back
Because 1,000 servers doing that in parallel will oversell instantly.
You need one atomic operation so only 2 requests can win.
3. Soft hold, not instant final sale
Even after a user "wins" the decrement, the item is usually not sold forever yet. It is placed on a temporary hold for a short time window.
Why?
Because users abandon carts.
Payments fail.
Sessions die.
So the system reserves inventory briefly, then releases it if checkout does not complete.
4. Database is still the final authority
Redis is the speed layer.
The database is the truth layer.
At checkout or order confirmation, the DB uses optimistic or pessimistic locking to make sure the final stock transition is valid. That is your last line of defense.
5. Why both layers exist
If you only use the DB:
- too much lock contention
- poor latency
- system melts during flash sales
If you only use Redis:
- faster, but risky if you skip durable confirmation
So the usual pattern is:
Redis for fast distributed reservation
DB for final correctness
If you want more help with LLD or HLD, check out these links:
1. HLD: https://lnkd.in/eAvAtm2K
2. LLD: https://lnkd.in/e3T6gxaA
Some important points to keep in mind:
1. Redis persistence matters for recovery
If Redis holds the inventory counter and it crashes right after selling the last two units, you could lose that state. When Redis comes back up, it might think stock is still 2, and you risk overselling.
To avoid this, use Redis with AOF (append-only file) persistence or a Redis Cluster with replication. Even then, treat Redis as a fast gate, not the final ledger.
2. The hold window needs careful sizing
If you hold inventory for too long, genuine buyers get "sold out" messages while abandoned carts lock up stock. If you hold it for too short, users start checkout, but inventory gets released before they finish.
Common approach: start with a short hold (5–10 minutes), then extend if the user is actively progressing through checkout.
No comments:
Post a Comment