Design a Flash Sale System
hard 55 minSell 10,000 units when 10 million people come at the same second.
See it run
A flash sale, one hop at a time: joining, waiting, holding the last unit, the Redis script, paying and splitting the stock.
Operations
Join and wait
A signed ticket before the start, a draw at the start, and one small file for everyone.
Step 1 of 10
20 minutes early
starts
in 20 min
The room is open. Joins spread over 30 minutes.
Step 1: 20 minutes early
def join(account): require_signed_in(account); challenge_if_doubtful(account) return sign(ticket_id(sale, account)) # same account, same ticketdef admission_step(): # one worker, each second free, undecided = read_stock() more = max(0, min(RATE, free - undecided)) cutoff += more / tickets publish("board.json", cutoff, stock_word(free))def enter(ticket): assert valid(ticket) and number(ticket, seed) < cutoff- Latency
- board ≤ 2 s old
- Load
- 16,700 joins/s peak
- Board reads
- 2M/s
- At our origin
- 300/s
The board is the same for everybody. That is what makes it cacheable.
In the real world
The same design a flash sale system doing real jobs. Pick one and step through it.
Two ways of taking it, moment by moment.
Step 1 of 4
Read, then write
| Moment | Buyer A | Buyer B | Stock |
|---|---|---|---|
| 1 | reads 1 | 1 | |
| 2 | reads 1 | 1 | |
Both believe it is free
Both read 1.
Step 1: Read, then write
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Read, check, write
criticalTwo buyers read the same last unit.
Wrongn = db.get("available")if n > 0: db.set("available", n - 1)Rightrows = db.execute("""UPDATE sales SET available = available - 1 WHERE id = %s AND available >= 1""", sale)Expiry as stock return
criticalThe hold vanishes and the counter stays low: units are never sold.
Wrongredis.decr("stock")redis.setex("hold:" + user, 300, 1)Rightredis.decr("stock")redis.zadd("ends", {user: now + 300})# a sweeper raises the stockPolling that reaches us
critical10 million people every 5 seconds are 2 million requests a second.
WrongGET /status?user=... # from our serversRightGET /board.json # CDN, 1 s, same for allConfirmed before saved
criticalA crash leaves a paid buyer without an order.
Wrongqueue.send(order)return "confirmed"Rightwith db.transaction(): orders.insert(order); outbox.add(order)return "confirmed"A timeout treated as refused
majorThe unit is sold again while the first buyer was charged.
Wrongexcept Timeout: release(hold)Rightexcept Timeout: keep_paying_and_ask_again(hold)
Interview tips
Shrink the crowd first
- 95% at the edge.
- Open early, draw at the start.
- Refusing is the cheap path.
Bring numbers
- 10 million a second at peak.
- 100 a second admitted.
- One in a thousand wins.
Own the time
- Holds have states and ends.
- Paying beats the sweeper.
- Unknown is a state.
Know where to stop
- 100 units need one database.
- Buckets only for hot rows.
- Prepare; do not autoscale the peak.