Ten thousand people and one hundred tickets broke my first implementation in ways I didn’t expect. I built a Flash Sale engine thinking I understood concurrency. On day one it crashed and oversold tickets.
The Naive Approach (And Why It Fails)
When I first sketched out the architecture, the logic seemed simple enough:
- Read the current inventory from the database
- Check if tickets are available
- If yes, decrement the count and create the order
Here’s what that looks like in Python with SQL:
@app.post("/reserve")
async def reserve_ticket(user_id: str):
# Step 1: Read
result = await db.fetch_one("SELECT inventory FROM events WHERE id = 1")
current_inventory = result["inventory"]
# Step 2: Check
if current_inventory > 0:
# Step 3: Write
await db.execute(
"UPDATE events SET inventory = inventory - 1 WHERE id = 1"
)
await db.execute(
"INSERT INTO orders (user_id, event_id) VALUES (?, ?)",
user_id, 1
)
return {"status": "success"}
return {"status": "sold_out"}
This works in development with one user and fails in production.
The Race Condition Window
The bug is in the microseconds between read and write. At thousands of requests per second, many operations land in that gap:
- User A reads inventory: 1 ticket remaining
- User B reads inventory: 1 ticket remaining (before User A writes)
- User A buys: inventory → 0
- User B buys: inventory → -1
That’s an oversell, the classic “lost update” problem.
Attempt 1: Database Row Locking
My first fix used SELECT FOR UPDATE, the standard approach for database consistency:
async with db.transaction():
result = await db.fetch_one(
"SELECT inventory FROM events WHERE id = 1 FOR UPDATE"
)
# ... rest of the logic
This prevents overselling, but performance is terrible. At high concurrency, requests queue for locks and latency rises from 15ms to over 2 seconds. Flash Sale users expect instant feedback.
Moving to Redis
Database locking prevented overselling but took 2 seconds per response. I moved the hot path into Redis after reading about atomic Lua scripts.
Here’s the Lua script for the inventory check:
local inventory_key = KEYS[1]
local user_reservation_key = KEYS[2]
local user_id = ARGV[1]
local ttl = tonumber(ARGV[2])
-- Check if user already has a reservation
local existing = redis.call('ZSCORE', user_reservation_key, user_id)
if existing then
return {err = "ALREADY_RESERVED"}
end
-- Check inventory
local current = tonumber(redis.call('GET', inventory_key) or 0)
if current <= 0 then
return {err = "SOLD_OUT"}
end
-- Atomic decrement and reservation
redis.call('DECR', inventory_key)
redis.call('ZADD', user_reservation_key, ttl, user_id)
return {ok = "SUCCESS"}
Redis runs a Lua script on a single thread, and no other commands run while it executes. The check and decrement happen as one operation, so the race condition is gone. This gives the same correctness as database locking with latency under 15ms instead of 2000ms.
The Distributed State Machine
Reservations are more involved than purchases. A user reserves a ticket and has 10 minutes to pay; if they don’t, the ticket goes back into the pool.
I implemented this using Redis Sorted Sets (ZSET) where the score is the expiration timestamp:
# When reserving: ZADD reservations <expiry_timestamp> <user_id>
# The reaper worker runs every second:
expired = redis.zrangebyscore('reservations', 0, current_time)
for user_id in expired:
redis.incr('inventory') # Return ticket to pool
redis.zrem('reservations', user_id)
ZRANGEBYSCORE is O(log N + M), where M is the number of expired entries returned, so even with thousands of active reservations, finding the expired ones takes microseconds.
Event-Driven Architecture
Users don’t want to refresh the page to see if tickets are available, so I used WebSockets with Redis Pub/Sub for live inventory updates:
- When a reservation succeeds, the backend publishes to a channel
- All connected clients receive the update within 15ms
- The UI updates without polling
This stopped the “F5 spam” typical of high-demand sales and cut server CPU load by 40% compared with polling.
The Write-Behind Pattern
Redis is fast but volatile, so orders eventually need to reach PostgreSQL. Writing to the database synchronously would bring back the latency.
Instead there’s an async write-behind queue:
- Successful reservations go into a Redis List
- A background worker consumes the list and batches writes to PostgreSQL
- If the worker crashes, the list persists in Redis (with AOF enabled)
User-facing latency no longer depends on database writes. The user gets instant confirmation and the order is persisted asynchronously.
Load Testing and Chaos Engineering
I built a “Bot Swarm” simulator that runs directly in the browser. It spawns N concurrent agents that authenticate, reserve and pay, which creates realistic lock contention.
For automated testing, I used k6 to simulate 10,000 concurrent users:
export const options = {
stages: [
{ duration: '30s', target: 1000 },
{ duration: '1m', target: 10000 },
{ duration: '30s', target: 0 },
],
};
The results: 8,500+ RPS sustained, 12ms average latency, zero overselling incidents.
What I’d carry over
Hot state in memory, cold state on disk. Redis gives speed and PostgreSQL gives durability.
Atomic operations. Application-layer logic can’t fix race conditions. You need atomic operations at the database (or Redis) level.
A way to see it. The Chaos Simulator page shows the naive SQL approach and the Redis Lua approach side by side in real time. I built it to check that the system worked.
Fairness from day one. Rate limiting, per-account purchase limits and queue fairness need planning from the start.
Try It Yourself
The system is live here. Open the Chaos Simulator to see the race condition, then watch the Redis approach keep inventory counts exact under load.
The same patterns apply to inventory management, seat reservations and other limited-quantity sales.