Skip to content

Design a Flash Sale

A system design interview walkthrough for a flash sale, covering limited stock under extreme spikes, atomic counters, load shedding and asynchronous orders.

Advanced24 minUpdated 2 December 2026

Before this: Rate Limiting, Idempotency, Caching

"Design a flash sale" has one product, a small number of units and a very large crowd. At noon, 5,000 phones go on sale at half price, and a million people press Buy in the same few seconds. Almost all of them will lose, and the system must tell them quickly, sell every unit exactly once, and still be standing afterward.

The interviewer is checking that you understand contention on a single hot item and that you know the cheapest request is the one you reject before it touches a database. Two ideas carry the answer: shed load early, and make the winner decision a single atomic step in a fast store.

This question differs from its neighbors on purpose. A hotel sells many dates of many room types over a day, and Ticketmaster sells unique seats the buyer chooses. A flash sale sells one interchangeable SKU, a counter, in a burst. The cart and the order pipeline behind it are in Design Amazon's Shopping Cart and Checkout. Background: rate limiting.

Clarify the requirements

Functional requirements:

  1. Users see a countdown, and at the start time can try to buy the sale item.
  2. A user can buy at most one unit (or a small fixed limit).
  3. A successful buyer gets the item reserved and a limited time to pay.
  4. Everyone else learns quickly that the item is sold out.
  5. Unpaid reservations return to stock.

Out of scope, said aloud: the product catalog, the cart for other items, shipping, recommendations and the details of payment (see Design a Payment System).

Non-functional requirements: these decide the design.

  • Never oversell. Selling 5,001 units of a 5,000-unit stock produces canceled orders and angry customers.
  • Survive the spike. The system cannot be taken down by the crowd it was built for.
  • Fast, honest failure. The 99% who lose should see "sold out" in well under a second, not a spinner.
  • Fairness within reason. One person, one unit, and no unfair advantage to a script.
  • Durable results. Every winner's order is eventually written, even if a downstream system is slow.

Estimate the scale

Assume 5,000 units, and 1 million interested users who all try within the first 10 seconds, retrying about 3 times each.

The spike: 1M × 3 = 3 million requests ÷ 10 seconds = 300,000 requests per second. On an ordinary day, the same service might see a few hundred.

Winners: exactly 5,000, which is 0.5% of the users. So 99.5% of requests must end in a rejection, and a rejection should cost almost nothing.

One hot key: a single Redis instance can handle on the order of 100,000 simple operations per second. If every request decremented the same stock counter, 300,000 per second would exceed one node's capacity, so you cannot send every request to the counter.

Admitted traffic: suppose we admit 4× the stock into the purchase path, so unpaid and failed attempts do not leave units unsold: 5,000 × 4 = 20,000 admitted requests. Even compressed into 5 seconds, that is 4,000 per second, which one counter handles comfortably.

Orders: only 5,000 orders are created. Spread over a minute, that is about 83 orders per second: a trivial write load for a queue and a database.

Stock data: one counter and 5,000 reservation records are tiny. Size is not a concern.

"The spike is 300,000 requests per second but there are only 5,000 winners. So this is not a throughput problem on the order path. It is a filtering problem: reject the 99.5% cheaply, at the edge, and let only a small stream reach the one place that makes the decision."

The capacity estimator shows the day totals for this event. They average a burst over 24 hours, so use the figures above for design.

API and data model

GET  /v1/sales/{id}/status                  -> { state: upcoming|live|sold_out, startsAt }   (CDN, 1 s)
POST /v1/sales/{id}/purchase   (Idempotency-Key = user + sale)   -> 202 { ticketId } | 409 sold_out | 429
GET  /v1/purchases/{ticketId}               -> { status: pending|reserved|failed, payBy }
POST /v1/purchases/{ticketId}/pay           -> order
stock counter (Redis):  sale:{id}:stock = 5000
claimed set   (Redis):  sale:{id}:buyers  (user ids that already claimed)
orders        (id PK, sale_id, user_id UNIQUE per sale, status, reserved_until)
sale          (sale_id PK, total_units, sold_units)  -- CHECK (sold_units <= total_units)

The non-obvious choice is the pair of guards. Redis decides fast, and the database CHECK and the unique (sale_id, user_id) constraint decide correctly. If Redis ever disagrees with the database, the database wins.

High-level design

The slice worth running is the purchase path: a gateway that sheds excess load, a purchase service, the stock counter, and a queue that carries winners to workers that write orders.

A gateway sheds excess load, a purchase service decrements an atomic stock counter in Redis, and winning orders are queued for durable processing.clientsgatewaypurchase apistock counterorder queueorder workers
A gateway sheds excess load, a purchase service decrements an atomic stock counter in Redis, and winning orders are queued for durable processing.
  • Clients reach the purchase API through a gateway that limits and rejects excess requests.
  • The purchase service decrements the stock counter in Redis and queues each winner for order workers.
Describe this diagram

Components

  • clients (Client)
  • gateway (API gateway)
  • purchase api (Service)
  • stock counter (Redis)
  • order queue (SQS queue)
  • order workers (Service)

Connections

  • clients sends to gateway
  • gateway sends to purchase api
  • purchase api sends to stock counter
  • purchase api sends to order queue
  • order queue sends to order workers

Run it, then try pushing the load past what the counter and the queue can take, and see which one gives first.

Before the sale: the countdown page and the sale status come from a CDN. Product images and descriptions are static. The stock counter is loaded into Redis ahead of time.

During the sale: a request passes the gateway's rate limit, the purchase service checks the user has not already bought, runs one atomic Redis script (decrement if stock is above zero), and on success enqueues an order message and returns 202. Workers read the queue and write orders to the database.

After the sale: an unpaid reservation expires after a few minutes, a job returns the unit to stock and the sale reopens briefly for people still waiting.

The interesting problem: deciding the winners without overselling

Two requests must not both take the last unit, and the decision must survive 4,000 attempts a second on one item.

Approach A: decrement a database row

UPDATE sale SET sold_units = sold_units + 1 WHERE sale_id = ? AND sold_units < total_units.

Good: correct, durable, and a single source of truth.

Bad: every attempt, win or lose, is a write on one row, and concurrent updates to a hot row serialize on a row lock. The database becomes the bottleneck, and failed attempts consume the capacity that winners need.

Approach B: an atomic counter in Redis

Run a short Lua script that checks the user has not claimed, checks stock > 0, decrements and records the user, all in one step:

if redis.call('SISMEMBER', buyersKey, userId) == 1 then return 'already' end
if tonumber(redis.call('GET', stockKey)) <= 0 then return 'sold_out' end
redis.call('DECR', stockKey)
redis.call('SADD', buyersKey, userId)
return 'ok'

Good: Redis runs a script one at a time without interleaving, so there is no race. A failure is a cheap in-memory read, and a win costs microseconds.

Bad: Redis is not the durable record, so a failover can lose the last few decrements. And one key on one node still has a ceiling.

Approach C: split the stock across several counters

Divide 5,000 units into 10 keys of 500, route each user to a key by hash, and when a key is empty, try the others.

Good: spreads the hot key over several nodes and raises the ceiling.

Bad: more complex, and the last few units can be stranded in one bucket while another user's bucket looks empty, unless you add a fallback search across buckets.

The recommended answer is B, protected by shedding, with the database as the final guard. The key observation is that the counter does not need to be sharded if it never sees 300,000 requests a second: the gateway rate limit, a cached "sold out" flag, and admission control keep the arrivals at the counter near the 4,000 a second we computed. Offer C as the next step if the numbers grow. For safety, the order write enforces sold_units <= total_units and UNIQUE (sale_id, user_id), so if Redis loses a decrement in a failover, the extra orders are rejected by the database, not sold.

Conceptual diagramabout 4,000 req/soksold out300,000 req/sEdge and gateway: rate limit, sold-out flagPurchase serviceRedis Lua: dedupe, check, decrementQueue winnerFast 409, set sold-out flagWorkers write orders under DB constraints
Diagram, as text
  • 300,000 req/s leads to Edge and gateway: rate limit, sold-out flag
  • Edge and gateway: rate limit, sold-out flag leads to Purchase service (about 4,000 req/s)
  • Purchase service leads to Redis Lua: dedupe, check, decrement
  • Redis Lua: dedupe, check, decrement leads to Queue winner (ok)
  • Redis Lua: dedupe, check, decrement leads to Fast 409, set sold-out flag (sold out)
  • Queue winner leads to Workers write orders under DB constraints

The second decision: shedding, fairness and asynchronous results

Shed at several layers. The first layer is a static page and a CDN, so the countdown costs nothing. The second is a gateway rate limit per user and per IP (a token bucket works), so one client cannot send 100 requests a second. The third is a global cap on in-flight purchase requests: when the purchase service is at its limit, return 429 immediately instead of queueing. A fast "try again" is better than a slow timeout, because timeouts cause retries and retries cause more load.

Respond before the order is written. The purchase call decides the winner and returns 202 with a ticket. The order itself is created asynchronously from the queue. The user sees "reserved, pay within 10 minutes" a moment later. This keeps the spike off the database and means a slow order service delays the confirmation, not the decision.

Idempotency. The key is the user and the sale. A retry from a user who already won returns the same ticket, not a second unit. The queue delivers at least once, so the order worker upserts on (sale_id, user_id): "effectively once", not magic exactly-once.

Fairness and bots. Require sign-in before the sale, limit one claim per account with the Redis set, and add a challenge for suspicious clients. A randomized admission window (all requests in the first second are equal, then the rest in order) avoids rewarding the lowest-latency script. Say that it is a product choice and no filter is perfect.

Unpaid reservations. A winner has a few minutes to pay. A delayed job or a TTL key returns the unit and clears the user's claim if unpaid, which lets the next person in a waiting list win. Without this, abandoned units are stranded.

Bottlenecks and failures

The hot counter. A single key has a ceiling. If admission control cannot hold the arrivals under it, split the stock across keys with a fallback across buckets.

Redis fails over mid-sale. A replica may be missing the last decrements, so the counter could show more stock than exists. The database constraint on sold_units stops overselling at order creation, and the loser gets a clear apology. Better, pause the sale for a few seconds on a failover and reload the counter from the database before reopening.

Redis is down. Fail closed: stop selling and show "try again shortly". Never fall back to a path without the guard.

The queue backs up. Winners wait longer for confirmation, but decisions are already made. Scale the workers and keep the reservation timer paused until the order exists, or users lose their window to a slow queue.

Thundering retries. Clients that retry on failure in a tight loop multiply the spike. Return Retry-After, add jittered backoff in the app, and make sold-out responses cacheable.

A deploy during the sale. Freeze deployments for sale windows, and warm up instances beforehand so cold starts do not appear at second zero.

Trade-offs to name aloud

  • Redis for the decision, the database as the guard: speed for the hot path, with a durable backstop, in exchange for two places that must agree.
  • Asynchronous orders: a fast decision and a protected database, in exchange for a short pending state the UI must show.
  • Shedding with 429: the system stays up, in exchange for turning away some users who would have won on a slower, fair retry.
  • One counter or many: simplicity now, with sharding held in reserve until the numbers demand it.

What interviewers listen for

  • A working answer: an atomic decrement, a unique-per-user check, an order queue, and a statement that the decision must not be a read followed by a write.
  • A strong answer: computes the spike and the number of winners, rejects the majority at the edge, uses a Lua script in Redis with a database constraint as the final guard, and answers asynchronously.
  • A standout answer: caches the sold-out result, handles Redis failover without overselling, returns unpaid units to stock, uses jittered retries and a Retry-After, and says "effectively once" for the order write.

Check your understanding

Common mistakes

Decrementing in the database for every attempt. A hot row serializes everything, and losers consume the capacity winners need.

Sending every request to the counter. The counter is not the problem if you shed first. Without shedding, even a fast counter melts.

Doing the order write synchronously. The spike then lands on the database. Decide fast, write behind a queue.

No guard behind the cache. If Redis is the only record, a failover quietly oversells.

Slow rejections. A request that waits for a timeout holds a connection and invites a retry. Reject fast with 429 or 409.

Forgetting unpaid reservations. Winners who never pay strand units unless a timer returns them to stock.

Practice

Your sale sells out in 2 seconds, but analytics later show 5,040 orders were created for 5,000 units. How did this happen, and what do you do now and next time?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Look for a place where the fast decision and the durable record could disagree.

Show a strong answer

Likely cause. A Redis failover or a restart reloaded a stale counter, so about 40 decrements were forgotten and 40 extra users were told they had won. The order worker had no database constraint on total units, so it created the orders.

What to do now. Identify the last 40 orders by creation time, cancel them with an apology and a small credit, and void any payment holds. Do not silently ship an item you do not have.

Next time. Add CHECK (sold_units <= total_units) (or a conditional update) in the order write, so the database rejects extras. Pause the sale on a Redis failover and reload the counter from the database before reopening. Add an alert on any mismatch between the counter and the order count.

The pattern worth keeping: a fast store may decide, but the durable store must be able to veto.

The product team wants the sale to feel fair: no one should win just because their connection is a few milliseconds faster. What can you change?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

You cannot make the network fair, but you can change what the first moments of the sale mean.

Show a strong answer

Open a fairness window. Treat all purchase requests received in the first second (or the first few hundred milliseconds) as equal. Collect them, shuffle them with a random order and run them through the claim script in that order, then switch to arrival order.

Remove the advantage of many requests. One claim per account is enforced by the set. Limit requests per account and per IP so that sending 100 requests does not help.

Be honest about the limits. Verified accounts and a challenge for suspicious clients reduce bots, but cannot eliminate them. Choose and document the policy as a product decision.

The pattern worth keeping: when speed decides, fairness is a policy you build into the admission step, because the infrastructure alone will always favor the fastest client.

Key takeaways

  • It is a filtering problem: 300,000 requests a second for 5,000 units means rejecting over 99% cheaply.
  • Shed at the edge with a CDN, rate limits, a global in-flight cap and a cached sold-out flag.
  • Decide winners with one atomic step in a fast store, never a read followed by a write.
  • Keep the database as the veto: a check on total units and a unique constraint per user.
  • Respond first, write the order behind a queue, and use "effectively once" order creation.
  • Return unpaid units to stock and plan for failover, retries and fairness.

Further reading

  • Redis documentation: the DECR command and Lua scripting with EVAL, including the guarantee that a script executes atomically.
  • Betsy Beyer et al. (eds.), "Site Reliability Engineering" (O'Reilly, 2016): the chapters on handling overload and addressing cascading failures.
  • Martin Kleppmann, "Designing Data-Intensive Applications" (O'Reilly, 2017): chapters on transactions and on the limits of exactly-once processing.

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track