The 9 PM Maggi Rush
200,000 users add Maggi to their cart simultaneously. There are only 340 packets in the dark store. How do we prevent 199,660 broken hearts at checkout without crashing the app?
The Problem: The Thundering Herd
- Pessimistic Locking (Database): Locking a database row for 200,000 carts is too slow. The database will melt, resulting in 503 Gateway Timeouts.
- Optimistic Locking (Check at Checkout): Letting everyone add it to the cart, but checking stock only at payment. Result: 1.6+ Lakh users get an "Out of Stock" error after they spent time navigating. Terrible UX.
The Solution: Soft Allocation via Redis
We use a blazing-fast, single-threaded in-memory datastore (like Redis) to perform Soft Allocation (temporary reservations) at the exact moment a user clicks "Add to Cart".
- Extremely Fast: Redis handles 100k+ operations/sec.
- Atomic: No two users can grab the exact same packet.
- Time-Bound: Carts expire if users don't buy within X minutes.
How it works under the hood
1. The Redis Atomic Counter (DECR)
Instead of reading from a SQL database, the app maintains an inventory counter in Redis. When 200,000 requests hit the server, it fires a Redis DECR (decrement) command for each. Because Redis is single-threaded, it queues these microsecond operations one by one perfectly.
SET dark_store_101:maggi_stock 340
# When user clicks 'Add to Cart'
DECR dark_store_101:maggi_stock
2. Lua Scripting (Preventing Negative Stock)
A simple DECR might take the stock into negatives. To prevent this atomically, we use a small Lua script executed by Redis. If the stock is > 0, it decrements. If it's 0, it returns an error instantly. The cart page receives this and says "Out of Stock" before the item enters the cart.
if stock > 0 then
redis.call('DECR', KEYS[1])
return 1 -- Success: Add to cart
else
return 0 -- Fail: Reject add to cart
end
3. Cart Expiry / TTL (Time-To-Live)
What if a user adds to cart and closes the app? We don't want those 340 packets locked forever.
We reserve the stock with a TTL (e.g., 10 minutes). A background worker (or Redis Keyspace Notification) listens for cart expirations. If a cart expires without payment, the worker executes an INCR to return the item to the available pool. Only successful payments write the final deduction to the persistent SQL database.