Flipkart clone: Big Billion Day flash sale
Build the hardest part of a big sale: 100 phones, 10,000 buyers clicking at 12:00. First prove a naive version oversells, then fix it with atomic updates, Redis and queues, and show the numbers.
Educational project inspired by Flipkart. Skills101 is not affiliated with Flipkart. Give your app its own name and logo, and do not copy their branding or content.
What you’ll learn
- ◆Race conditions and why “check then update” oversells
- ◆Atomic database updates and Redis Lua scripts
- ◆Reservations with timeouts, idempotency and queues
- ◆Load testing with k6 and reading p95 latency
What you’ll build
- ✓Sale page with a server-synced countdown
- ✓“Buy now” that never sells more than the stock
- ✓One unit per user and a 10-minute payment hold
- ✓Load-test report comparing naive vs fixed
Before you start
What you need
- •Node.js and Express basics, a little SQL.
- •Docker (for PostgreSQL and Redis) and k6 installed (
k6 version). - •Read the “Inventory management” and “Load testing” guides on this page if these topics are new.
How it fits together
- 1React sale page → Express API. Before the sale, stock is loaded into Redis.
- 2A Redis Lua script checks stock and the one-per-user rule and reserves a unit in one atomic step.
- 3Reserved buyers get 10 minutes to pay; a worker returns unpaid units to stock.
- 4Orders are written to PostgreSQL by a queue worker, with a unique key so retries never create duplicates.
Project structure
bigsale/
├─ docker-compose.yml # postgres + redis
├─ api/
│ ├─ naive.ts # the buggy version (keep it!)
│ ├─ reserve.lua
│ ├─ sale.ts # routes
│ └─ worker.ts # holds expiry + order writer
├─ web/ (React) # countdown + buy button
└─ load/
├─ naive.js # k6 scripts
└─ fixed.jsStep-by-step guide
Step 1
Understand the problem before writing code
Goal: You can explain, with a timeline, how two buyers both get the last phone.
A flash sale is not about pretty product pages; it is about correctness under a stampede. At 12:00:00, thousands of requests arrive within a second for a few units.
The bug: request A reads stock = 1. Request B reads stock = 1. A writes stock = 0 and creates an order. B also writes stock = 0 and creates an order. Two orders, one phone. This is a race condition, and it only appears under concurrency, so normal clicking never shows it.
Plan: build the naive version, prove it oversells with a load test, then fix it step by step, measuring each time. That before/after story is what makes this project impressive.
✅ Check it works
You can draw the A/B timeline on paper.
Step 2
Set up the API, database and Redis
Goal: Express API, PostgreSQL and Redis running locally with a products and orders table.
Run PostgreSQL and Redis with Docker Compose. Create
products(id, name, price_paise, stock)andorders(id, user_id, product_id, sale_id, status, created_at)with a UNIQUE constraint on(sale_id, user_id)so a user can have at most one order per sale even if code has a bug.Use the
pgandredisnpm packages directly; seeing the raw SQL and Redis commands is the point of this project.Add a
POST /admin/resetroute (local only) that sets stock back to 100 and deletes orders, so you can rerun tests quickly.schema.sqlCREATE TABLE products ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, price_paise INT NOT NULL, stock INT NOT NULL CHECK (stock >= 0) ); CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, sale_id TEXT NOT NULL, user_id TEXT NOT NULL, product_id INT NOT NULL REFERENCES products(id), status TEXT NOT NULL DEFAULT 'RESERVED', -- RESERVED | PAID | EXPIRED created_at TIMESTAMPTZ NOT NULL DEFAULT now(), UNIQUE (sale_id, user_id) );✅ Check it works
docker compose up -dthenpsqlshows both tables.Step 3
Build the naive version and prove it oversells
Goal: A k6 test where 500 virtual users buy 100 units and more than 100 orders are created.
Write the obvious code: read stock, if above 0 then update and insert an order. Temporarily drop the CHECK constraint and the UNIQUE constraint for this experiment, so you can see the raw bug.
Write a k6 script with 500 virtual users, each with a different user id, all calling buy at once. Then count orders. You will usually get far more than 100.
Save the numbers (orders created, final stock, p95 latency). Keep
naive.tsin the repo; it is your “before”.api/naive.ts and load/naive.js// api/naive.ts (WRONG on purpose) app.post('/naive/buy', async (req, res) => { const { rows } = await pool.query('SELECT stock FROM products WHERE id = 1') if (rows[0].stock <= 0) return res.status(409).json({ error: 'sold out' }) await pool.query('UPDATE products SET stock = $1 WHERE id = 1', [rows[0].stock - 1]) await pool.query("INSERT INTO orders (sale_id, user_id, product_id) VALUES ('bbd', $1, 1)", [req.body.userId]) res.json({ ok: true }) }) // load/naive.js (run: k6 run load/naive.js) import http from 'k6/http' export const options = { vus: 500, iterations: 500 } export default function () { http.post('http://localhost:3000/naive/buy', JSON.stringify({ userId: 'u' + __VU }), { headers: { 'Content-Type': 'application/json' } }) }✅ Check it works
SELECT count(*) FROM ordersreturns more than 100 after the test. That is the bug, reproduced.Step 4
Fix 1: an atomic update in the database
Goal: The same load test creates exactly 100 orders.
Replace read-then-write with one statement:
UPDATE products SET stock = stock - 1 WHERE id = $1 AND stock > 0 RETURNING stock. PostgreSQL locks the row while it updates, so concurrent requests queue for that row. If it returns no row, the item is sold out.Wrap the update and the order insert in a transaction (
BEGIN … COMMIT); if the insert fails (for example, the unique constraint says this user already ordered),ROLLBACKreturns the unit.Put the CHECK and UNIQUE constraints back. Correctness now comes from the database itself.
api/sale.ts (database version)app.post('/v1/buy', async (req, res) => { const userId = String(req.body.userId) const client = await pool.connect() try { await client.query('BEGIN') const r = await client.query('UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock > 0 RETURNING stock') if (r.rowCount === 0) { await client.query('ROLLBACK'); return res.status(409).json({ error: 'sold out' }) } await client.query("INSERT INTO orders (sale_id, user_id, product_id) VALUES ('bbd', $1, 1)", [userId]) await client.query('COMMIT') res.json({ ok: true, left: r.rows[0].stock }) } catch (e: any) { await client.query('ROLLBACK') if (e.code === '23505') return res.status(409).json({ error: 'one per customer' }) // unique violation throw e } finally { client.release() } })✅ Check it works
Rerun the k6 test: exactly 100 orders and stock 0, every time. Note the new p95 latency; it is higher, because requests wait for the row lock.
Step 5
Fix 2: reserve in Redis with a Lua script
Goal: Correct results with much lower latency, because the hot path no longer waits on the database.
At peak, every request fighting for one database row is slow. Redis runs commands one at a time in memory, so an operation there is atomic and very fast. Load the stock into Redis just before the sale (
SET sale:bbd:stock 100).A Lua script runs inside Redis as a single atomic step: check if this user already bought, check stock, decrement, record the user. No other command can run in the middle, so there is no race.
The script returns -2 (already bought), -1 (sold out) or units left. Only successful requests go on to create a reservation (next step).
api/reserve.lua (+ how to call it)-- KEYS[1] = stock key, KEYS[2] = buyers set, ARGV[1] = user id if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then return -2 end local left = tonumber(redis.call('GET', KEYS[1]) or '0') if left <= 0 then return -1 end redis.call('DECR', KEYS[1]) redis.call('SADD', KEYS[2], ARGV[1]) return left - 1 -- Node (redis v4): -- const result = await redis.eval(RESERVE_LUA, { keys: ['sale:bbd:stock', 'sale:bbd:buyers'], arguments: [userId] })✅ Check it works
Run the same k6 test against
/v2/buy: still exactly 100 winners, and p95 latency clearly lower than fix 1. Put both numbers in a table.⚠️ Common mistakes
- Doing GET then DECR as two separate commands from Node: that reintroduces the race.
Step 6
Hold the unit for 10 minutes, then release it
Goal: Winners get 10 minutes to pay; unpaid units go back to stock automatically.
A winner has a reservation, not an order. Add them to a sorted set with the expiry time as the score:
ZADD sale:bbd:holds <now+600000> <userId>. When they pay, remove them from the set and mark the order PAID.A worker runs every 15 seconds: it fetches holds whose time has passed (
ZRANGEBYSCORE ... -inf <now>), and for each one atomically removes the hold, increments stock and removes the user from the buyers set (so they may try again). Use a Lua script orMULTIso a payment arriving at the same moment cannot double-release.Show the winner a countdown: “Pay within 09:41”. Mark expired orders as EXPIRED in PostgreSQL.
api/worker.ts (expiry)const RELEASE_LUA = [ "if redis.call('ZREM', KEYS[1], ARGV[1]) == 1 then", " redis.call('INCR', KEYS[2])", " redis.call('SREM', KEYS[3], ARGV[1])", " return 1", "end", "return 0", ].join('\n') setInterval(async () => { const expired = await redis.zRangeByScore('sale:bbd:holds', '-inf', Date.now()) for (const userId of expired) { const released = await redis.eval(RELEASE_LUA, { keys: ['sale:bbd:holds', 'sale:bbd:stock', 'sale:bbd:buyers'], arguments: [userId], }) if (released) await pool.query("UPDATE orders SET status = 'EXPIRED' WHERE sale_id = 'bbd' AND user_id = $1 AND status = 'RESERVED'", [userId]) } }, 15_000)✅ Check it works
Reserve without paying, wait 10 minutes (use 30 seconds while testing): stock goes up by 1 and the order shows EXPIRED.
Step 7
Write orders through a queue with idempotency
Goal: Successful reservations become PostgreSQL orders reliably, even if the worker crashes and retries.
After a successful Lua reserve, do not make the buyer wait for PostgreSQL. Push a job (
LPUSH sale:bbd:jobs {userId}) and answer “Reserved!” immediately. A worker pops jobs (BRPOP) and inserts orders.Workers can crash after inserting but before acknowledging, so a job may run twice. The UNIQUE (sale_id, user_id) constraint plus
INSERT … ON CONFLICT DO NOTHINGmakes the insert idempotent: running it twice has the same effect as once.For a production-like setup use BullMQ (retries, dead-letter queue, dashboard). Mention in your README why a queue smooths the spike: the database writes at a steady rate instead of 10,000 at once.
api/worker.ts (order writer)while (true) { const job = await redis.brPop('sale:bbd:jobs', 0) // blocks until a job arrives if (!job) continue const { userId } = JSON.parse(job.element) await pool.query( "INSERT INTO orders (sale_id, user_id, product_id) VALUES ('bbd', $1, 1) ON CONFLICT (sale_id, user_id) DO NOTHING", [userId], ) }✅ Check it works
Push the same job twice by hand: only one order row exists.
Step 8
Build the sale page: countdown, states and fairness
Goal: A page that opens at exactly 12:00 server time and always shows the right state.
Phone clocks are often wrong by seconds or minutes. The page fetches the server time once (
GET /time), computes the offset, and counts down using server time. The API also rejects buys before the start time, so editing the page does not help.States: Coming soon (countdown) → Buy now → Reserved, pay within mm:ss → Paid / Sold out / One per customer. Disable the button while a request is in flight to avoid double clicks.
Add rate limiting per user and per IP (for example 5 requests per 10 seconds with a Redis counter) so bots cannot spam. Optionally, a waiting-room: put users in a queue and let them in batches.
✅ Check it works
Set your laptop clock 2 minutes ahead: the countdown still ends at the real start time.
Step 9
Load-test the final version and write the report
Goal: A one-page report with numbers that proves no overselling under load.
Run k6 with 1,000–5,000 virtual users against naive, fix 1 (database) and fix 2 (Redis + queue). Record: orders created, final stock, p50 and p95 latency, error rate, and throughput.
p95 means 95% of requests were faster than this. It matters more than the average, because the slowest users are the ones who complain.
Make a table and two charts, and explain trade-offs: the database version is simpler and correct; Redis is faster but adds moving parts and must be synced with the database.
load/fixed.jsimport http from 'k6/http' import { check } from 'k6' export const options = { scenarios: { spike: { executor: 'per-vu-iterations', vus: 2000, iterations: 1, maxDuration: '1m' } }, thresholds: { http_req_duration: ['p(95)<300'] }, } export default function () { const res = http.post('http://localhost:3000/v2/buy', JSON.stringify({ userId: 'u' + __VU }), { headers: { 'Content-Type': 'application/json' } }) check(res, { 'won or cleanly refused': (r) => r.status === 200 || r.status === 409 }) }✅ Check it works
Every run: exactly 100 orders, stock 0 (after holds settle), no 5xx errors.
Step 10
Deploy and present the story
Goal: A live demo and a README that tells the oversell → fix story with numbers.
Deploy API, Redis and PostgreSQL with Docker Compose on a small VPS, and the React page as static files. Never run the load test against a server you do not own.
README structure: the problem (timeline diagram), naive results, fix 1 results, fix 2 results, the final table, what you would add for real scale (multiple Redis shards per product, CDN for the page, a waiting room).
Add “Educational project inspired by Flipkart's Big Billion Days. Not affiliated.” In interviews, lead with the numbers: “the naive version sold 163 of 100 units; my version sold exactly 100 with p95 under 50 ms.” (Use your real numbers.)
✅ Check it works
Someone reading only your README understands the bug, the fix and the proof.
🚀 Make it stand out
- +Virtual waiting room with position in queue
- +Multiple products and per-product stock shards
- +Grafana dashboard of orders per second during the test
- +Payment step in Razorpay test mode