Why 10,000 Users Clicking Buy at Once Broke Our Database (And How 28 Lines of Go + Redis Lua Fixed It)
Shafikul Islam
Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Executive Summary & Production Diagnostic
When flash-sale or ticket-reservation systems scale past 10,000 concurrent buyers clicking Buy in the same 500-millisecond window, standard relational database transactions collapse. The failure is rarely caused by slow CPUs. It is caused by row-level lock contention, serial queue buildup, and connection pool starvation.
In a standard textbook reservation flow, an application reads the available stock, checks if it is greater than zero, and issues an update statement:
-- Standard Textbook Reservation Flow (Fails Under 10,000 RPS)
SELECT available_stock FROM inventory WHERE item_id = 'item_42' FOR UPDATE;
UPDATE inventory
SET available_stock = available_stock - 1
WHERE item_id = 'item_42' AND available_stock > 0;
In local testing or at 20 requests per second, this works fine. Under a 10,000-user flash-sale spike, two failure modes occur immediately:
- Without row locking: Hundreds of concurrent workers read positive stock at the exact same microsecond and oversell the inventory.
- With pessimistic row locking: 9,999 database connections block in a serial queue waiting on a single PostgreSQL row lock, exhausting your PgBouncer pool and spiking P99 latency into multi-second timeouts.
Technical Metric Benchmark Comparison
| Metric / Benchmark Area | Initial Postgres Row-Lock State | Post-Redis Lua (EVALSHA) Engine | Improvement / Impact |
|---|---|---|---|
| P95 Reservation Latency | 3,850ms (Pool Timeout) | 3.9ms | 99.8% Latency Drop |
| Double-Booking / Oversell Rate | 4.2% under race conditions | 0.00% (100/100 Exact) | Zero Race Conditions |
| PostgreSQL Primary CPU Load | 96% (Lock Wait Saturation) | 11% (Async Ledger Writes) | 88.5% CPU Reduction |
| Concurrent Buyers Verified | Choked at ~600 parallel users | 10,000 Concurrent Goroutines | 16x Throughput Scale |
Architecture Pivot: Atomic Gatekeeping at the Edge with Redis Lua
Instead of forcing PostgreSQL to absorb 10,000 competing row locks on a hot inventory row, we moved the reservation gatekeeper into Redis using a pre-loaded Lua script executed via SHA digest.
Why Lua inside Redis? Because Redis executes a Lua script atomically on a single thread. No other command can interleave between checking user idempotency, reading the stock counter, decrementing stock, and creating a 60-second payment hold TTL.
-- KEYS[1]: stock_key (e.g., "drop:item:42:stock")
-- KEYS[2]: hold_key (e.g., "drop:item:42:hold:user_991")
-- ARGV[1]: requested_qty (1)
-- ARGV[2]: ttl_seconds (60)
-- 1. Idempotency guard: block duplicate clicks from the same buyer
if redis.call("EXISTS", KEYS[2]) == 1 then
return -2 -- Buyer already holds an active reservation
end
-- 2. Verify available inventory
local current_stock = tonumber(redis.call("GET", KEYS[1]) or "0")
local qty = tonumber(ARGV[1])
if current_stock < qty then
return -1 -- Sold out
end
-- 3. Atomically decrement stock and create self-healing 60s hold
redis.call("DECRBY", KEYS[1], qty)
redis.call("SETEX", KEYS[2], tonumber(ARGV[2]), qty)
return current_stock - qty
How Self-Healing 60-Second Holds Work
Reserving the item at the edge is only half the architecture. What happens when a buyer reserves the last unit and closes their browser tab without completing checkout?
1. Fast Edge Reservation (Under 4ms)
The Go API executes the pre-loaded Lua script in Redis. If it returns zero or higher, the buyer receives a signed 60-second checkout token and an asynchronous reservation event is published to our worker queue.
2. Asynchronous PostgreSQL Ledger Persistence
When the payment webhook confirms checkout within the 60-second window, our background worker writes the finalized order into PostgreSQL and removes the temporary hold key.
3. Automatic Inventory Recovery on Abandonment
If the 60-second TTL expires without payment confirmation, a lightweight reconciliation loop restores the expired hold quantity back to the Redis stock pool, requiring zero manual database cleanup.
Proving Zero Race Conditions Under Load
We never trust concurrency claims without deterministic race-detector verification. We wrote a Go concurrency harness spawning 10,000 parallel goroutines competing simultaneously for 100 available items:
func TestConcurrentFlashSaleReservations(t *testing.T) {
const totalBuyers = 10000
const initialStock = 100
var successCount int64
var wg sync.WaitGroup
wg.Add(totalBuyers)
for i := 0; i < totalBuyers; i++ {
go func(userID int) {
defer wg.Done()
reserved, err := engine.ReserveSeat(ctx, "item-42", fmt.Sprintf("user-%d", userID), 1)
if err == nil && reserved {
atomic.AddInt64(&successCount, 1)
}
}(i)
}
wg.Wait()
if successCount != initialStock {
t.Fatalf("expected exactly %d reservations, got %d", initialStock, successCount)
}
}
Key Takeaways for Founders & Engineering Leaders
- Protect PostgreSQL from hot-key lock storms: Use PostgreSQL as your durable financial ledger of record, not as a 10,000-RPS spinlock counter.
- Never split check-and-decrement across network round-trips: Always fuse stock verification and decrementing into a single atomic Redis Lua execution.
- Every inventory hold must have a deterministic TTL: Unbounded holds turn abandoned carts into permanent inventory deadlocks during high-traffic launches.