A phone brand announces that 10,000 units of its new model go on sale at exactly 12:00 noon. At 11:59:59, a million people are staring at a countdown, thumbs hovering over "Buy now". Within the first second, hundreds of thousands of requests arrive for a product that will sell out in under a minute.
This is the flash sale problem, and it is a favourite in Indian system design interviews because every big e-commerce event (Big Billion Days, Great Indian Festival, a limited sneaker drop) is a version of it. It looks like a simple checkout. It isn't. It tests whether you can reason about contention (thousands of writers fighting over one number), load shedding (rejecting 99% of requests cheaply), and correctness under failure (never selling a phone you don't have).
Requirements (functional and non-functional)
Scope the problem before designing. A flash sale is one product (or a handful) with fixed stock, a fixed start time and enormous demand.
Functional requirements
- Sale page: buyers see the product, price, a countdown before the start, and approximate stock remaining once it's live.
- Reserve: when the sale opens, a buyer can claim a unit. The claim holds the unit for a short time (say 10 minutes) while they pay.
- Checkout: the buyer pays within the hold window; the reservation becomes an order.
- Expiry: unpaid reservations expire and the unit goes back on sale.
- Limits: one unit per customer.
Non-functional requirements
- Never oversell. Selling unit 10,001 means cancelling a paid order and angry customers. Underselling a few units is acceptable; overselling is not.
- Survive the spike. Traffic at noon is roughly 100x normal, arriving within seconds.
- Fast answers. A buyer should learn within a few hundred milliseconds whether they got a unit, including "sorry, sold out".
- Fairness and bot resistance. Real buyers should have a fair chance against scripts.
- Isolation. The sale must not take down the rest of the store.
Capacity estimates
- Stock: 10,000 units.
- Interested buyers: 1 million, most of them arriving in the first 10 seconds.
- Buy requests: 1 million / 10 s ≈ 100,000 requests per second at the peak, plus retries from impatient users tapping again.
- Successful reservations: at most 10,000, so 99% of buy requests must be rejected.
- Page views: the sale page is refreshed constantly in the minutes before noon: easily 10x the buy traffic, but it is the same content for everyone.
The single most important number is the last ratio: almost every request is a "no". The whole design is about saying "no" as early and as cheaply as possible, so the few "yes" answers can be handled carefully.
API design
GET /v1/sales/{saleId} → product, price, start time, stock band ("plenty", "few left", "sold out")
POST /v1/sales/{saleId}/admission → { token, position } (joins the waiting room)
POST /v1/sales/{saleId}/reservations → { reservationId, expiresAt } (needs a valid token + Idempotency-Key)
POST /v1/orders → { orderId, paymentUrl } (body: reservationId)
POST /v1/payments/webhook ← payment gateway callback (idempotent)Two details matter. The reservation call carries an idempotency key, so a buyer who taps twice or retries on a flaky network gets the same reservation instead of two (see idempotency and exactly-once). And the sale page returns a stock band, not an exact count. Exact counts would need a strongly consistent read on every page view.
Data model
| Entity | Store | Why |
|---|---|---|
| Sale (product, price, start, stock) | MySQL, cached at the edge | Read constantly, changes rarely |
| Live stock counter | Redis | The hot path: atomic decrement at 100k requests per second |
| Per-user purchase count | Redis hash, mirrored in MySQL | Enforces one per customer in the same atomic step |
| Reservation (id, user, sale, status, expires_at) | MySQL | Source of truth for holds; status HELD → PAID / EXPIRED |
| Order | MySQL, unique on reservation_id | One order per reservation, even if the payment webhook fires twice |
Redis is the gatekeeper; MySQL is the ledger. Every unit that leaves Redis must be traceable to a reservation row, and a reconciliation job compares the two after the sale.
High-level architecture
The request path narrows like a funnel: the CDN absorbs page views, the edge drops bots and floods, the waiting room admits buyers at a rate the system can handle, Redis atomically hands out the 10,000 units, and only successful reservations ever touch MySQL, asynchronously, through Kafka.
Deep dives
1. Never oversell: where the decrement happens
Every reservation is a check-and-decrement: "if stock > 0, take one". If the check and the decrement are separate steps, two buyers can both see stock = 1 and both take it. There are three common ways to make them one step.
Option A: a conditional database update.
UPDATE sale_stock SET stock = stock - 1 WHERE sale_id = 42 AND stock > 0;
-- 1 row affected → you got one; 0 rows → sold outThis is correct, simple and survives crashes. The problem is that every buyer is updating the same row, so the database serialises them on one row lock. A single hot row tops out at a few thousand updates per second, far below 100,000.
Option B: an atomic counter in Redis. Redis runs commands one at a time, so a small Lua script makes check-and-decrement atomic, and it can also enforce the per-user limit in the same step:
-- KEYS[1] = stock counter, KEYS[2] = per-user counts (hash)
-- ARGV[1] = user id, ARGV[2] = per-user limit
local bought = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '0')
if bought >= tonumber(ARGV[2]) then return -2 end -- limit reached
local left = tonumber(redis.call('GET', KEYS[1]) or '0')
if left <= 0 then return -1 end -- sold out
redis.call('DECR', KEYS[1])
redis.call('HINCRBY', KEYS[2], ARGV[1], 1)
return left - 1 -- units left after this oneOne Redis node handles well over 100,000 such scripts per second. In Redis Cluster, both keys must live on the same shard, so give them a hash tag like {sale:42}:stock and {sale:42}:buyers.
Option C: pre-allocated tokens. Split the 10,000 units into, say, 100 buckets of 100 spread across shards. Each request hashes to a bucket and decrements it; when a bucket empties, it tries a neighbour. This removes the single hot key at the cost of slightly uneven sell-out (a few units may be stranded in a bucket nobody hits, which is underselling, the safe direction).
For most interviews, Option B is the right answer, with Option C mentioned as the next step if one Redis key becomes the bottleneck.
Here is the core logic as an in-process model: reserve with a per-user limit and idempotency, confirm on payment, and expire unpaid holds. In production the check-and-decrement lives in the Lua script above; the shape of the logic is the same.
import threading
import uuid
class FlashSaleInventory:
"""Reserve-then-confirm inventory that can never oversell."""
def __init__(self, stock: int, hold_seconds: float = 600, per_user: int = 1):
self.available = stock
self.hold_seconds = hold_seconds
self.per_user = per_user
self.holds = {} # reservation id -> (user id, expires at)
self.by_key = {} # idempotency key -> reservation id
self.user_count = {} # user id -> active holds and orders
self.lock = threading.Lock()
def reserve(self, user_id: str, idem_key: str, now: float):
with self.lock:
if idem_key in self.by_key: # a retry of the same tap
return self.by_key[idem_key]
if self.user_count.get(user_id, 0) >= self.per_user:
return None # one per customer
if self.available == 0:
return None # sold out: reject cheaply
self.available -= 1 # check and decrement together
rid = str(uuid.uuid4())
self.holds[rid] = (user_id, now + self.hold_seconds)
self.by_key[idem_key] = rid
self.user_count[user_id] = self.user_count.get(user_id, 0) + 1
return rid
def confirm(self, rid: str, now: float) -> bool:
with self.lock:
hold = self.holds.pop(rid, None)
if hold is None:
return False
user_id, expires_at = hold
if expires_at < now: # paid too late: give the unit back
self._release(user_id)
return False
return True # becomes an order; the unit stays sold
def expire(self, now: float) -> int:
with self.lock:
late = [rid for rid, (_, exp) in self.holds.items() if exp < now]
for rid in late:
user_id, _ = self.holds.pop(rid)
self._release(user_id)
return len(late)
def _release(self, user_id: str) -> None:
self.available += 1
self.user_count[user_id] -= 1Notice that confirm handles a payment that arrives after the hold expired but before the expiry worker ran: it returns the unit itself. Without that branch, a late payment would silently leak a unit. That's the kind of edge case interviewers love to probe.
2. The virtual waiting room
Even with Redis, letting a million clients hammer the reservation service at once is a bad idea: connection storms, retries, and noisy neighbours for the rest of the site. A virtual waiting room turns the stampede into a queue.
- Before noon, clients call the admission endpoint and receive a signed token containing their user id, the sale id, and the earliest time they may attempt to buy.
- At noon, the waiting room releases admissions at a controlled rate (for example 20,000 per second) using a token bucket. Everyone else sees their position and an estimated wait.
- The reservation service verifies the token's signature and time locally (no database lookup), so invalid or early requests are rejected in microseconds.
How do you order the queue? First come, first served rewards whoever has the fastest connection (and scripts). Many large sales instead randomise everyone who joined before the start time, then admit in that order. It is fairer and removes the incentive to hammer the endpoint at 11:59:59.
Once the counter hits zero, flip a "sold out" flag that the CDN and the waiting room both read. From that moment every new request is answered at the edge without touching any service.
3. Reservations, payments and expiry
A reservation holds a unit for, say, 10 minutes. Three things can happen:
- The buyer pays in time. The payment gateway calls the webhook; the order service marks the reservation
PAIDand creates the order. Theorderstable has a unique constraint onreservation_id, so a duplicate webhook cannot create a second order. - The hold expires. An expiry worker scans for
HELDreservations pastexpires_at(indexed onstatus, expires_at), marks themEXPIREDin a transaction, and only then increments the Redis counter. Returned units go to the next buyers in the waiting room. - The payment succeeds after expiry. Rare, but it happens with slow UPI or card authentication. Either refund automatically or, if stock is still available, try to re-reserve on the buyer's behalf. Decide the policy explicitly; don't leave it to chance.
Reservations are written to MySQL asynchronously: the Lua script succeeds, the reservation service publishes ReservationCreated to Kafka, and the order service persists it. If the service crashes between Redis and Kafka, a unit is "lost": Redis says it's taken but no reservation exists. The reconciliation job catches this after the sale (Redis decrements versus reservation rows) and puts stranded units back. That is underselling, temporarily, which is the safe direction.
4. Keeping everything else alive
- Static sale page. Product details, images and the countdown are served from the CDN. The countdown runs on the client against a server time offset fetched once; nobody polls for the start.
- Stock bands, not counts. The page shows "plenty", "only a few left" or "sold out", refreshed every second or two from a single cached value, not 100,000 reads of Redis per second.
- Backoff with jitter. Clients that are told to wait retry after a randomised delay, so they don't all come back at the same instant.
- Bulkheads. The sale runs on its own service instances, Redis and connection pools, so a meltdown stays contained and normal shopping keeps working.
- Pre-warming. Scale instances, warm caches and open connections before noon. Autoscaling reacts in minutes, and the spike lasts seconds.
Bottlenecks and trade-offs
| Decision | Trade-off |
|---|---|
| Redis as the gatekeeper | Fast, but an in-memory store can lose recent writes on failover. Run with replication and AOF, and reconcile against MySQL after the sale; design so that failures undersell rather than oversell. |
| One stock key vs bucketed tokens | One key is simple and exact; buckets remove the hot key but can strand a few units. |
| FIFO vs randomised waiting room | FIFO feels intuitive but rewards bots and fast networks; randomisation is fairer but needs clear messaging. |
| Short vs long holds | Short holds recycle stock quickly but fail buyers on slow payments; long holds frustrate those still waiting. Ten minutes is a common middle ground. |
| Exact vs approximate stock display | Exact counts are expensive and create read storms; bands are cheap and good enough. |
| Asynchronous persistence | Keeps MySQL out of the hot path; needs a reconciliation job and a clear story for crashes between steps. |
Bots deserve their own line: device fingerprinting, CAPTCHAs at admission (not at checkout, where it slows real buyers), per-account and per-payment-instrument limits, and requiring a logged-in account with purchase history all raise the cost of scripting.
Questions an interviewer will ask next
- Redis fails over in the middle of the sale and loses the last second of decrements. What happens? (Possible oversell if the counter goes back up. Mitigate by persisting reservations before acknowledging, or by recomputing the counter from MySQL before reopening.)
- How do you enforce one per customer when a person has five accounts? (Limit per verified phone number, address or payment instrument, not just per account.)
- How would you run the same sale across two regions? (Split stock per region, or keep one authoritative counter and accept cross-region latency.)
- The payment gateway slows down at noon. What breaks first? (Holds expire before payment completes; extend holds dynamically or queue payment attempts.)
- How do you load-test this? (Replay realistic traffic shapes, a spike rather than a ramp, and run game days where you kill Redis and the order service mid-sale.)
- How would you show buyers their position in the queue without a database read per refresh? (Encode it in the signed token and compute the estimate client-side from the published admission rate.)
If you can explain why 99% of requests must be rejected cheaply, how the check-and-decrement stays atomic, and what happens to a unit at every failure point, you have covered what interviewers are really looking for in this question.