System Design (50 Qs)•Part 2: Real-World High-Scale Architecture Problems (11 - 25)
Design an E-Commerce Flash Sale System (High Concurrency & Inventory Reservation).
In Simple Words: Prevent overselling when 500,000 customers try to purchase 1,000 limited-stock gaming consoles within 3 seconds of a flash sale launch.
The Solution: Atomic In-Memory Inventory Reservation:
- Relational database row locks (
SELECT ... FOR UPDATE) will freeze and fail under 100,000 QPS. - Pattern: Preload inventory into Redis Decr or Lua script. Only customers who successfully decrement the Redis counter are granted a signed reservation token to proceed to payment checkout!
lua
-- Atomic Inventory Reservation Script in Redis
local stock_key = KEYS[1]
local user_id = ARGV[1]
local current_stock = tonumber(redis.call('GET', stock_key) or 0)
if current_stock > 0 then
redis.call('DECR', stock_key)
redis.call('SADD', stock_key .. ':reservations', user_id)
return 1 -- Success: Seat reserved for 10 minutes
else
return 0 -- Sold out: Reject instantly without hitting DB
end