System design interview guide
Design a Flash Sale System: Selling Limited Stock to a Huge Crowd
Short answer
A flash sale system sells a small, fixed stock to a crowd far larger than it, all at one moment. It keeps the crowd in a waiting room at the edge and admits buyers at the rate checkout can take. It takes each unit in one atomic step, a Redis Lua script or a conditional SQL update, so the last unit goes to exactly one buyer. It holds a taken unit for a few minutes while the buyer pays and puts it back if they do not. Orders, payments and emails run behind a queue.
The same problem at one Indian company: Flipkart system design: Big Billion Days
Two courses by the author of this page:
770 lessons · 18 free to read
₹1,111 in India · $35 elsewhere, once
Get System DesignYou own this course
219 lessons · 10 free to read
₹1,333 in India · $35 elsewhere, once
Get Generative AI and Agentic AIYou own this course
Save your progress and get the interview checklist PDF
A phone launch puts 1,000 units on sale at 12 noon. Two million people are waiting with the page open. In the first second, far more people press Buy than there are phones. The system must sell each phone once, tell everyone else quickly and honestly, and keep the rest of the shop working while it happens.
A flash sale is a sale of a small, fixed stock at a known minute, so a huge crowd arrives at the same moment for something most of them cannot get. The design has three jobs. First, keep the crowd away from the parts that cannot take it, with a waiting room at the edge that lets buyers in at a steady rate. Second, count stock in one place with one atomic step, so two buyers can never take the same last unit. Third, hold a unit for a short time while the buyer pays, and put it back if they do not. Everything else, such as orders, emails and invoices, can happen a little later through a queue.
Where it shows up
Asked at e-commerce companies such as Flipkart, Amazon, Myntra and Meesho, and at ticketing and payments companies, often for SDE2 and SDE3 rounds. The same question appears as design a ticket booking system, design a limited-edition drop, or design a system that never oversells.
Spec sheetFlash Sale
- 01Page loads in the first minute
- ~33,000 per second
- 02Waiting room status checks
- ~200,000 per second
- 03Buyers admitted to the stock step
- ~500 per second
- 04Writes that actually create orders
- 1,000 plus resales
worked through below, with the maths
Why this question is asked
It looks like a shopping cart question, but the cart is the easy part. The interviewer wants to see whether you notice that the traffic and the stock do not match: millions of requests for a thousand items. A design that sends every click to the database falls over in the first second. A design that counts stock in two places sells the same phone twice. The question tests load control at the edge, correctness under concurrency, and honest handling of the people who do not get a unit.
What the interviewer asks
“Design a system for a flash sale: 1,000 units of a new phone go on sale at 12 noon, and millions of users will try to buy at once.”
Ask these back before you draw
- 1.How many units, and is it one product or many? (Assume one product, 1,000 units.)
- 2.Is there a limit per customer? (Assume one unit per account.)
- 3.How long does a buyer get to pay before the unit goes back? (Assume 10 minutes.)
- 4.Must buyers be served in arrival order, or is a fair random draw acceptable?
- 5.Does the rest of the shop have to keep working during the sale? (Yes.)
This page is the free part.
The course goes deeper on the Flash Sale design
₹1,111 in India$35 everywhere elseonce, for the whole course
The System Design course covers the Flash Sale design across a run of lessons, not one page. These 4 alone are about 87 minutes of step-by-step reading, every one with a quiz.
- Redis Cache
The same small GET measured 0.3 ms at worst on an idle server and 59.1 ms while one other client ran KEYS. Reading one field cost 0.934 ms as a blob and 0.040 ms as a hash.
- Cache Stampede Prevention
A cache stampede is many requests rebuilding expired keys at once. Single flight and TTL jitter, measured on one run: what each fixes and what it does not.
- Token Bucket Algorithm
A bucket of tokens that refills at a steady rate, the most popular rate limiting algorithm in production.
- Idempotency Keys
Safely retry failed API requests without causing duplicate side effects.
all part of
System Design Masterclass
770 lessons · about 290 hours · 18 free to read
₹1,111in India, by UPI
$35everywhere else, by card or PayPal
It is really nice and good Please join the course
You own this course
Continue with Redis Cachepay once,
yours for life
Live from the course bench
Before you design Flash Sale System, try the questions it rests on.
Real interview questions, live diagrams and measured lab results, pulled at random from the lessons. A new set every time you come back.
Requirements
Always clarify these in the first 5 minutes of the interview. Do not start drawing boxes until both lists are agreed.
Functional requirements
- Show the sale page and a countdown to everyone before the start time
- Let users join a waiting room and admit them toward checkout at a controlled rate
- Take one unit from stock for an admitted buyer, at most one unit per account
- Hold the unit for a fixed time while the buyer pays, then confirm or release it
- Tell users quickly when the stock is gone, and stop admitting new buyers
- Create the order, and send the confirmation, after the unit is taken
Non-functional requirements
- Never sell more units than exist, even when thousands press Buy in the same second
- Keep the rest of the site available, so one sale cannot take down other shoppers
- Answer sold out and please wait quickly, without touching the database
- Be fair in a way the business can state, such as arrival order
- Stop bots and duplicate accounts from taking most of the stock
- Recover cleanly from crashes: a unit is never lost and never counted twice
Back-of-envelope scale estimates
Show your math. Pulling numbers from thin air signals you have not thought about the load.
Page loads in the first minute
~33,000 per second
Assume 2 million people load the sale page within the first minute. 2,000,000 divided by 60 seconds is about 33,000 loads a second. The page is the same for everyone, so it is served from a CDN (content delivery network), and almost none of this reaches our servers.
Waiting room status checks
~200,000 per second
If each of the 2 million waiting browsers asks am I in yet every 10 seconds, that is 2,000,000 divided by 10, or 200,000 checks a second. This is the real load, so the check must be cheap: it reads a signed cookie and compares it with a number, with no database call.
Buyers admitted to the stock step
~500 per second
The stock count itself can answer far more than this, but payment, orders and the payment provider behind them have limits. Assume the slowest of them can take about 500 new checkouts a second. That is the admit rate. At that rate the 1,000 units are offered within a few seconds.
Writes that actually create orders
1,000 plus resales
Only a buyer who gets a unit creates an order. If 30% of holds are not paid in 10 minutes, about 300 units come back and are offered again, so the order table sees roughly 1,300 inserts for the whole sale. The database is not the problem once the crowd is kept out.
High-level architecture
The sale page and its countdown are static and come from a CDN. When the sale opens, the browser joins a waiting room at the edge. The waiting room gives each user a signed cookie with their arrival time and lets people through when that time is older than a moving threshold, so the admit rate matches what checkout can take. An admitted user reaches the stock service. The stock service keeps the count of units left in Redis and takes a unit with one atomic script that also records a per-user hold with an expiry. If a unit is taken, the service writes a hold row to the orders database and puts an order event on a queue. Order workers read the queue, create the order and start payment. A sweeper finds holds whose time has passed without payment and puts those units back. When the count reaches zero, the waiting room is told to show sold out, so the crowd stops asking.
In a real interview, sketch this on the whiteboard before diving into any single box.

One buyer, from the sale page to a paid order
- 1
Load the page
The phone loads the sale page and countdown from the CDN. No request reaches our servers yet.
- 2
Join the waiting room
At noon the browser asks to buy. The edge gives it a signed cookie with its arrival time and shows a please wait page that checks again every few seconds.
- 3
Get admitted
When the threshold passes the user's arrival time, the edge lets the request through to the stock service. Earlier arrivals always go first.
- 4
Take a unit
The stock service runs one atomic script in Redis. It checks that units are left and that this user has no hold, records the hold with a 10 minute expiry, and lowers the count by one.
- 5
Record the hold
The service writes a hold row with an expiry time to the orders database and puts an order event on the queue. The user sees you have 10 minutes to pay.
- 6
Pay
An order worker creates the order and starts payment with an idempotency key, so a retried payment request never charges twice.
- 7
Confirm or release
On payment success the hold becomes a sale. If the 10 minutes pass first, the sweeper releases the hold and adds one unit back to the count, and a waiting user can get it.
Core components
Walk through each service. The interviewer wants to hear what each one owns, not just the names.
CDN and static sale page
Serves the page, images and countdown to everyone from the edge. The page has no stock number on it that must be exact, so it can be cached.
Waiting room
Runs at the edge. It gives each user a signed cookie with their arrival time and admits users whose time is older than a threshold. The threshold moves forward when checkout has spare room and holds back when it is busy. It needs no shared database, because the state lives in the cookie and the threshold.
Stock service
The only place that changes the stock count. It runs one Redis script that checks the count, checks for an existing hold by the same user, records the hold and lowers the count, all in one step.
Redis stock count
One key with the number of units left and one key per active hold. Kept in memory for speed, with a replica, and rebuilt from the orders database if it is ever lost.
Orders database
The record of truth for holds and orders. Each hold row has a status (held, paid, released) and an expiry time. Redis is fast; this is what you trust after a crash.
Order queue and workers
Takes order creation, payment start, emails and invoices off the hot path. Workers process events at their own pace, so a burst of buyers does not become a burst of database writes.
Hold sweeper
A job that runs every few seconds, finds holds that passed their expiry without payment, marks them released in the database and adds the units back in Redis.
Bot and abuse filter
Checks at the edge before a user joins the queue: one hold per verified account, rate limits per device and IP address, and a challenge for suspicious traffic.
Data model
Pick the right store per table. Justify each choice with the access pattern, not by reflex.
salesale_idproduct_idstarts_attotal_unitshold_minutesper_user_limitOne row per sale. The total is fixed before the sale starts and is what the Redis count is loaded from.
holdhold_idsale_iduser_idstatus (held, paid, released)expires_atcreated_atOne row per unit taken. A unique index on (sale_id, user_id) enforces one unit per account in the database too. The sweeper reads rows where status is held and expires_at is in the past.
orderorder_idhold_iduser_idamountpayment_statusidempotency_keyCreated by the order worker from the queue event. The idempotency key makes a retried create or payment safe.
Redis keysstock:<sale_id> (units left)hold:<sale_id>:<user_id> (expires after hold_minutes)The fast copy. The count plus the paid and held rows in the database must always equal total_units, which is what a reconciliation job checks.
Deep dives
These are the conversations the interviewer is steering you toward. Practice each one until you can talk through it without notes.
Why the waiting room matters more than the database
Millions of people want a thousand phones. If every press of Buy reaches the database, the database is busy saying no to people who were never going to get a phone, and the people who could have bought one time out. Shopify described exactly this in 2017: one merchant's flash sale took down not only her store but every store on the same database shard. Their fix was a throttle at the edge, in Nginx with Lua scripts, that let a set number of checkouts through every 5 seconds and sent the rest to a cached please wait page instead of an error. The lesson for the interview: protect the slow parts by deciding at the edge who goes in, and make the answer to everyone else cheap.
Fair order without a shared database
Shopify's first throttle let users retry at random times, which turned the queue into a lottery. Some people waited 40 minutes for a sale that lasted about 40 minutes. Their second version gave each user a timestamp in a signed cookie when they first arrived, and let a request through when its timestamp was older than a threshold, like a now serving counter. Each load balancer moved the threshold by itself, forward when checkout had spare room and back when it was overloaded, so no shared store was needed. Signed means the server adds a cryptographic signature, so a user cannot edit the cookie to put themselves earlier in line. Hosted products such as Cloudflare Waiting Room do the same job with settings for total active users and new users per minute, and let people out in first in, first out order.
Taking a unit without overselling
Overselling happens when two requests both read units left = 1, both decide there is stock, and both write 0. The fix is to make the check and the change one step that nothing can interrupt. In Redis, a Lua script runs atomically: no other command runs while it runs. So one script can check the count, check that this user has no hold, record the hold with an expiry, and lower the count. Two buyers racing for the last unit are handled one after the other, and the second sees zero. In the script below, run on Redis 8.10 with 2 units, user u1 gets a unit (1 left), u1 again is refused because they already hold one, u2 gets the last unit (0 left), and u3 is told sold out.
local left = tonumber(redis.call('GET', KEYS[1]) or '0')
if left <= 0 then return -1 end
if not redis.call('SET', KEYS[2], ARGV[1], 'NX', 'EX', ARGV[2]) then return -2 end
return redis.call('DECR', KEYS[1])
-- redis-cli --eval take.lua stock:sale42 hold:sale42:u1 , u1 600
-- stock 2: u1 -> 1, u1 -> -2, u2 -> 0, u3 -> -1The database version of the same idea
Without Redis, the same guarantee comes from one conditional update: UPDATE sale SET units_left = units_left - 1 WHERE sale_id = 42 AND units_left > 0. If it changes one row, you got a unit; if it changes zero rows, it is sold out. In PostgreSQL at the default READ COMMITTED level, a second update waiting on the same row re-checks the WHERE condition against the newest version of the row, so it cannot take a unit that is already gone. This is correct but every buyer now locks the same row, so the row becomes a queue of its own. It works when the waiting room keeps the admit rate low, and it is a good answer for a smaller sale. For a very large one, split the stock into a few buckets, such as 10 rows of 100 units, and pick a bucket per request, so the locks spread out.
Holds, payment and putting units back
Taking a unit is not selling it. The buyer still has to pay, and many will not finish. So a taken unit becomes a hold with an expiry, here 10 minutes. Two things can end it. Payment succeeds and the hold becomes paid. Or the time passes and the hold is released, and the unit goes back to the count so a waiting user can have it. Do not rely on Redis key expiry events for this: Redis keyspace notifications are fire and forget, so a crashed listener misses them for good. Instead, the hold row in the database has an expires_at time, and a sweeper job finds and releases expired holds. Payment must also use an idempotency key, so a buyer who presses Pay twice or a retried request never pays twice for one hold.
Keeping Redis and the database in agreement
There are now two copies of the truth: the fast count in Redis and the hold rows in the database. Write the order so a crash cannot lose a unit. The stock service takes the unit in Redis first, then writes the hold row. If the service crashes between the two, Redis says one fewer unit than the database explains. A reconciliation job compares them: units left in Redis plus held and paid rows in the database must equal the total for the sale. If a unit is missing, it is added back. If Redis itself is lost, rebuild the count from the database: total minus held minus paid. The database wins every disagreement, because it is durable and Redis is the fast copy.
Sold out should be the fastest answer
Once the count reaches zero, most remaining requests are from people who will not get a unit. Answer them without work. The stock service sets a sold out flag, the waiting room reads it and shows sold out instead of please wait, and the CDN page can switch to a sold out banner. If holds are released later, the flag clears and admission restarts for the people still in the queue, in their arrival order. Be honest on the page: say all units are taken or held, and that some may come back in the next few minutes.
Bots, limits and fairness rules
A flash sale is a target for bots, because the product often resells for more. The basic defences sit before the queue. Require a signed-in account, and in many markets a verified phone number. Allow one hold per account, enforced in the Redis script and again by a unique index on (sale_id, user_id) in the database. Rate limit per device and per IP address. Challenge suspicious traffic before it gets a queue cookie. None of these is perfect, so the business should also decide what fair means and state it: arrival order, or a random draw among everyone who joined in the first minute. A random draw removes the advantage of the fastest script, which is why some ticket sellers use one.
Trade-offs to discuss
Every senior interviewer expects you to surface at least 3 of these. Pick the decisions, state the alternatives, and justify your choice.
Waiting room at the edge vs letting everyone hit checkout
The waiting room adds a step and a please wait page, but it keeps the database, payments and the rest of the shop alive. Without it, the slowest part decides who gets through, which is random and fails loudly.
Redis count vs a conditional update in the database
Redis answers many thousands of atomic checks a second from memory but is a second copy that must be reconciled. The database update is one source of truth and simpler, but every buyer locks one row. Use the database when the admit rate is low, Redis when it is high.
Arrival order vs random draw
Arrival order feels fair and is easy to explain, but rewards the fastest connections and scripts. A random draw among early arrivals is fairer to people on slow networks but must be explained clearly, or it feels like a trick.
Short hold vs long hold
A short hold returns unpaid units quickly to people still waiting, but rushes buyers on slow payment methods such as some bank approvals. A long hold is kind to buyers but leaves stock locked while the crowd gives up. 5 to 15 minutes is common; pick it with the payment team.
Create the order synchronously vs through a queue
Creating the order in the same request gives the buyer a final answer at once, but puts the database on the hot path. Taking the unit synchronously and creating the order through a queue keeps the hot path tiny; the buyer sees you have a unit, pay within 10 minutes, which is what matters.
One stock row vs split buckets
One row is simplest and always exact. Splitting stock across several rows spreads the lock contention but can say sold out in one bucket while another still has units, so a request must try another bucket before it gives up.
Free PDF · 18 pages
Get the free System Design Interview Cheat Sheet
The interview in seven stages, the numbers worth knowing by heart, and twelve classic systems on one page each, every line linked to the lesson it comes from.
Follow-up questions to expect
After the main design, the interviewer usually picks one part and asks more. Here is what to say.
What if the payment provider is slow or down during the sale?
Payments are already behind the queue, so a slow provider makes workers slow, not the stock step. Holds keep their expiry, so units are not lost. If the provider is down for longer than the hold, extend all holds for that sale in one update and tell buyers on the page, rather than releasing units people tried to pay for.
How do you run many sales for many products at once?
Each sale has its own stock key and its own hold keys, so sales do not touch each other. Spread sale keys across Redis cluster shards by sale id, and give each big sale its own waiting room settings. The rest of the shop runs on separate servers, so a hot sale cannot slow normal browsing.
How would you test this before the real sale?
Run a load test against a copy of the system with the expected crowd, with real network delays, and check three numbers afterwards: units sold equals units available, no account has two units, and the rest of the site stayed within its normal response times. Shopify's first post describes one merchant whose sales came every seven or eight days, so rehearsing at that load is part of the job.
What if a user opens the sale in two tabs or two phones?
Both tabs share the account, so the one-hold-per-account check in the script refuses the second hold. Two accounts for one person is the harder case, handled by phone verification, device limits and the bot checks before the queue.
How Flash Sale actually does it
Shopify's engineering blog has the clearest public account of this problem. In February 2016 a flash sale by Kylie Cosmetics took down her store and every other store on the same database shard, because each checkout created and kept updating a MySQL row. The quick fix was a checkout throttle in the Nginx edge tier, written as OpenResty Lua scripts: a leaky bucket that passed a set number of requests every 5 seconds, a cached queue page instead of a 429 error, and a signed cookie for users who got through. Random polling made it unfair, with waits of up to 40 minutes, so the second version used a timestamp in a signed cookie and a threshold moved by a proportional controller on each load balancer, with no shared data store. Cloudflare Waiting Room offers the same idea as a hosted product, with limits for total active users and new users per minute and first in, first out release. The atomic stock step is plain Redis (a Lua script runs atomically) or plain SQL (a conditional update that re-checks its condition).
Sources
- Shopify Engineering: Surviving flashes of high-write traffic, Part I
- Shopify Engineering: Surviving flashes of high-write traffic, Part II
- Cloudflare Waiting Room: how it works
- Redis docs: scripting with Lua (atomic execution)
- Redis docs: keyspace notifications (fire and forget)
- PostgreSQL docs: transaction isolation (READ COMMITTED re-checks)
Lessons to study before this interview
If any of these topics are fuzzy, the interviewer will catch it. Each lesson is 15 to 60 minutes with diagrams, code, and a quiz.
Redis Cache
foundation / caching strategies
Cache Stampede Prevention
foundation / caching strategies
Token Bucket Algorithm
intermediate / api design protocols
Idempotency Keys
intermediate / api design protocols
Message Queues
intermediate / messaging event systems
Load Shedding
advanced / reliability resilience
Backpressure for Resilience
advanced / reliability resilience
Frequently asked questions
Go deeper
This guide is built on these 6 lessons. Each one teaches one piece of the Flash Sale design above, step by step.
- Redis CacheSystem Design · caching strategies · 26 min
- Cache Stampede PreventionSystem Design · caching strategies · 25 min
- Token Bucket AlgorithmSystem Design · api design protocols · 18 min
- Idempotency KeysSystem Design · api design protocols · 18 min
- Message QueuesSystem Design · messaging event systems · 20 min
- Load SheddingSystem Design · reliability resilience · 20 min
Practice with 770 system design lessons
Lifetime access for ₹1,111 in India or $35 elsewhere. Interactive diagrams, quizzes, and 20 capstone projects to practise on.
This one question is not enough for the interview.
Get all 200 questions in the System Design and Distributed Systems pack
Each question has why it is asked, a full answer, what the interviewer listens for, the follow-ups, the common mistakes and a diagram (268 diagrams in all). A PDF you keep, junior to staff level.
Pay by UPI, cards or netbanking through Razorpay. Pay by card or PayPal, in US dollars. Download at once from My packs.
NEWSystem Design Hands-On
Included in the System Design course: real systems, built live
Postgres Sharding: Complete Hands-On (PgBouncer + Citus). 2 h 36 min and 20 chapters: one PostgreSQL loaded until it breaks, then four shards behind a router you write, PgBouncer and Citus, with the 139-page slide deck. The first 15 minutes are free to watch.


