The problem
When many people try to buy the last few tickets at once, a naive backend reads the count, does some work, and writes the new count back. Every request that reads between someone else’s read and write sees stale stock, so the shop sells tickets it doesn’t have.
Row locks (SELECT ... FOR UPDATE) fix that by making every buyer wait in line on the database. I wanted the check and the decrement to happen as one step without locking Postgres at all.
How it works
The inventory counter lives in Redis. Reserving runs a Lua script, and Redis runs scripts one at a time, so no other request can slip in between the check and the decrement:
local tickets = redis.call('get', KEYS[1])
-- if enough are left: DECRBY the count, add the user to a sorted set
-- of holds scored by expiry time, and store the held quantity
A ticket then moves through four steps:
- Reserve. The Lua script checks stock, decrements it, and records a 30-second hold.
- Pay. The hold is removed and the order is pushed onto a Redis list.
- Expire. A reaper polls the sorted set every second with
ZRANGEBYSCOREand returns expired holds to stock. - Persist. A worker pops orders off the list and writes them to PostgreSQL.
The reserve path never touches Postgres, and paying doesn’t wait on a database write.

Every stock change is published on a Redis channel. A FastAPI subscriber forwards it over WebSockets, so every open page sees the count drop without polling. Users log in with a JWT. The backend enforces a per-user ticket cap and a per-IP rate limit in Redis that returns 429 when exceeded. Confirmed orders can also be published to GCP Pub/Sub. That step is optional and skipped when it isn’t configured.
Trying it
The live demo has three pages:
/livelets you send a swarm of browser bots at the sale and watch the stock reach zero without going negative./simulatorruns the naive read-check-write version next to the Lua version under the same concurrency. The naive counter drifts, and the Lua one stops at exactly zero.- the landing page explains the design.
A k6 script runs 50 virtual users through login, reserve and pay. I haven’t published k6 numbers, so this page doesn’t quote any.
Infrastructure
The app runs on Render from render.yaml and locally with Docker Compose. The repo also has Terraform modules for AWS S3, RDS and GCP Pub/Sub, raw Kubernetes manifests, a Helm chart with an autoscaler and a disruption budget, and a hardened Postgres config. GitHub Actions runs pytest and validates the Terraform and Helm files.