The problem: everyone clicks at the same moment
Selling tickets looks like basic CRUD. A user picks seats, pays, gets a ticket. Insert a row, send an email, done.
Then a popular event goes on sale. Hundreds of people hit "Buy" within the same few seconds, and a lot of them want the same front rows. Now the boring CRUD app has to answer a hard question over and over: who actually got that seat?
At work I spent a good stretch on the backend of a SaaS ticketing platform built with FastAPI, PostgreSQL, Celery, Redis, Docker and Pytest. This post covers the parts that decided whether it was reliable: holding seats safely under concurrent requests, tuning PostgreSQL before reaching for a cache, moving slow work into background jobs that are safe to run twice, and the tests that let me change all of it without fear.
The flow, end to end
The short version: FastAPI validates the request and works out the price. PostgreSQL decides who gets the seat, inside one transaction. Only after that commits do Celery workers pick up the slow stuff through Redis. Pytest and Docker wrap the whole thing so what I test locally behaves like what runs in production.
Holding seats without overselling
The bug you get by default
The obvious code reads the seat, checks it's free, then marks it as held:
seat = await db.get(Seat, seat_id) if seat.status == "available": seat.status = "held" await db.commit() This works perfectly in development. It breaks the first time two requests run that if at the same moment. Both read "available", both write "held", and two people now think they own seat 14C. Your support team finds out before you do.
The fix is to stop checking in Python and make the database do the check and the write as one step.
Option 1: a conditional UPDATE
For general admission, where you only care about a count, a single conditional UPDATE is enough:
UPDATE ticket_types SET available = available - :qty WHERE id = :ticket_type_id AND available >= :qty RETURNING available; If no row comes back, there wasn't enough stock and the request fails cleanly. PostgreSQL takes a row lock for the update, so two concurrent buyers queue up on that row instead of both winning. No read-then-write gap, nothing to race on.
Option 2: SELECT ... FOR UPDATE for specific seats
Reserved seating is messier. A user picks several specific seats, and you want all of them or none. Here I lock the rows first, then decide:
async with db.begin(): seats = (await db.execute( select(Seat) .where(Seat.id.in_(seat_ids), Seat.event_id == event_id) .order_by(Seat.id) # same lock order everywhere avoids deadlocks .with_for_update() )).scalars().all() if len(seats) != len(seat_ids) or any(s.status != "available" for s in seats): raise SeatsUnavailable() hold = Hold(event_id=event_id, user_id=user.id, expires_at=now() + HOLD_TTL, status="held") db.add(hold) for s in seats: s.status, s.hold = "held", hold A second request asking for any of those seats waits at the FOR UPDATE until the first transaction commits or rolls back. When it gets its turn it sees "held" and fails with a clear error instead of overselling.
Two small details mattered more than I expected. Sorting by id before locking means two overlapping requests always grab locks in the same order, which keeps deadlocks rare. And keeping the transaction short matters. Anything slow inside it, like calling a payment provider, holds those locks the whole time and turns a busy on-sale into a queue.
The trade-off: row locks make busy rows a bottleneck. For a hot event, a lot of requests end up waiting on the same few rows. That's still the right call. A short wait is annoying. Selling one seat twice is a refund, an angry customer, and a bad review.
Never trust the price from the client
The checkout request carries ticket type IDs and quantities. It does not carry a price the server uses. The server recomputes everything from the database:
class CheckoutIn(BaseModel): event_id: int items: list[CartItem] # ticket_type_id + quantity, nothing else promo_code: str | None = None def price_order(ticket_types, items, promo) -> Decimal: subtotal = sum(ticket_types[i.ticket_type_id].price * i.quantity for i in items) discount = promo.discount_for(subtotal) if promo and promo.is_valid() else Decimal("0") return (subtotal - discount + service_fee(subtotal)).quantize(Decimal("0.01")) If the frontend shows a total, that's for display. The amount we charge comes from this function, using prices read inside the same transaction as the hold. Pydantic also rejects anything odd at the edge, like zero or negative quantities, before it gets near the database.
PostgreSQL performance: EXPLAIN ANALYZE before caching
When some endpoints got slow, the first suggestion on the table was Redis caching. I'm glad we didn't start there.
Caching inventory in a ticketing system is risky. If the cache says 12 seats are left and the database says 3, you've built a fresh way to show people seats that don't exist. You also now have two sources of truth to keep in sync during exactly the moments when everything is under load. So the rule I followed was simple: find out why the query is slow first.
A concrete example: the hold expiry query
Unpaid holds need to expire so the seats go back on sale. A scheduled job runs something like this:
EXPLAIN ANALYZE SELECT id FROM holds WHERE status = 'held' AND expires_at < now() ORDER BY expires_at LIMIT 500; The plan (trimmed and illustrative) showed the problem straight away:
Limit -> Sort (Sort Key: expires_at) -> Seq Scan on holds Filter: ((status = 'held') AND (expires_at < now())) Rows Removed by Filter: <most of the table> The holds table keeps every hold ever made: paid, expired, cancelled. Only a small slice is still active at any moment. But without a useful index, PostgreSQL reads the whole table to find that slice, every time the job runs.
A partial index covers exactly the rows the job cares about:
CREATE INDEX CONCURRENTLY idx_holds_active_expiry ON holds (expires_at) WHERE status = 'held'; After that, the plan becomes an Index Scan using idx_holds_active_expiry, and it only touches active holds. The index stays small because finished holds drop out of it.
The same idea applied to the read side. Organiser dashboards and checkout checks kept filtering by event and status, so a composite index fit there:
CREATE INDEX CONCURRENTLY idx_orders_event_status ON orders (event_id, status, created_at); Column order matters. event_id goes first because almost every query filters on it, and status narrows it down from there.
Across this kind of work, mostly indexes like these plus rewriting a few queries that were fetching far more than they used, we got about 25% better database efficiency. No cache layer was involved.
The trade-off with indexes
Indexes aren't free. Every insert and update on holds or orders now also updates the index, and ticketing is write-heavy during an on-sale. So I didn't index every column that showed up in a WHERE. Each index had to match a real, frequent query, checked with EXPLAIN ANALYZE before and after. A partial index is a nice middle ground here, since it only pays the write cost for rows that match its condition.
I also used CREATE INDEX CONCURRENTLY on live tables. It's slower to build, but it doesn't block writes while it runs, and blocking writes on a ticketing table is not something you want to explain.
Async work with Celery and Redis
Get slow work out of the request
Generating a PDF ticket with a QR code, sending the confirmation email, expiring unpaid holds: none of this needs to happen while the user stares at a spinner. Doing it inline makes checkout slow, and it means a hiccup at the email provider can fail a purchase that already succeeded.
So the request does the transactional part, commits, and then queues the rest:
async with db.begin(): order = await confirm_payment(db, order_id) generate_tickets.delay(order.id) Queueing after the commit matters. Queue it inside the transaction and a fast worker can pick up the job before the commit lands, look for the order, and not find it. Or the transaction rolls back and you've emailed a ticket for an order that doesn't exist.
Retries are easy, safe retries take thought
Celery makes retries a one-liner. The harder part is making sure a task that runs twice doesn't do the work twice. And it will run twice eventually. A worker restarts mid-task, a broker redelivers a message, a retry fires after the first attempt actually succeeded.
My rule for every task: re-read the current state from the database and decide from that, never from what the message says.
@app.task(bind=True, acks_late=True, autoretry_for=(TransientError,), retry_backoff=True, max_retries=5) def send_confirmation(self, order_id: int): with session_scope() as db: order = db.get(Order, order_id, with_for_update=True) if order.status != "paid" or order.confirmation_sent_at: return # already done, or not ours to do email.send_tickets(order, idempotency_key=f"confirm-{order.id}") order.confirmation_sent_at = utcnow() The confirmation_sent_at check means a duplicate run does nothing. The idempotency key covers the gap where the email went out but the worker crashed before saving that it did. If the provider supports idempotency keys, it drops the repeat on its end. Ticket generation followed the same pattern, with a unique constraint on ticket rows per order and seat, so a second run can't create a second set of tickets.
Hold expiry works the same way. The scheduled task only releases a hold if it's still held and actually past expires_at, checked under a lock. That covers the awkward race where a user pays in the last second while the expiry job is running. Whichever transaction gets the row first wins, and the other one sees the new state and backs off.
acks_late=True is part of this trade. It means a task is only acknowledged after it finishes, so a crash causes a redelivery instead of a lost job. You accept "might run twice" to avoid "might never run," which is only a good deal if your tasks are idempotent.
Testing: where the confidence came from
I wrote 400+ Pytest tests on this backend. Along with the fixes they pushed us into, that work helped cut user-reported bugs by 35%. The count isn't the point, though. Most of the value came from a handful of patterns.
Edge cases as tables
Pricing and hold rules have lots of small cases. parametrize keeps them readable:
@pytest.mark.parametrize("qty, available, ok", [ (1, 1, True), # last ticket (2, 1, False), # asking for more than what's left (0, 5, False), # zero quantity (-1, 5, False), # negative quantity ]) def test_hold_quantity_rules(client, make_ticket_type, qty, available, ok): tt = make_ticket_type(available=available) resp = client.post("/holds", json={"ticket_type_id": tt.id, "quantity": qty}) assert (resp.status_code == 201) is ok Most of the bugs users reported were some version of a row in a table like this that nobody had written down yet.
Testing the race, not just the logic
Unit tests won't catch a race condition. So I had a few tests that actually start two transactions against a real PostgreSQL and make them collide:
def test_two_buyers_one_seat(seat, run_concurrently): results = run_concurrently( lambda: hold_seats([seat.id], user="a"), lambda: hold_seats([seat.id], user="b"), ) assert sorted(r.ok for r in results) == [False, True] assert count_holds_for(seat.id) == 1 run_concurrently uses two threads, each with its own connection, and a barrier so both reach the lock at the same time. I also tested the rollback path. If something fails halfway through a checkout, the seats must come back as available. That test caught more than one bug where an error was handled but the transaction wasn't.
API contracts
For the endpoints the frontend depends on, tests check the shape of the response, not just the status code: required fields, types, and error formats. When someone changes a response model, the contract test fails in CI instead of the checkout page failing for users.
Docker keeps test and prod honest
All of this runs against real PostgreSQL and Redis in Docker, the same versions as production. I tried SQLite for tests early on and dropped it. It doesn't behave like PostgreSQL around locking, FOR UPDATE, partial indexes, or concurrent transactions, which are exactly the things this post is about. A test that passes on the wrong database doesn't tell you much.
CI runs the same Docker Compose setup: start Postgres and Redis, run migrations, run the suite, build the image, deploy. If it passes there, it behaves the same way in production.
If you're building something like this
Let PostgreSQL decide who gets the seat. A conditional UPDATE or SELECT ... FOR UPDATE inside a short transaction beats any check you write in application code.
Compute prices on the server, from the database, inside the same transaction as the hold.
Run EXPLAIN ANALYZE before you add a cache. Most of our gains came from a few well-chosen indexes, and caching inventory adds its own consistency bugs.
Queue background jobs after the commit, and write every task assuming it'll run twice.
Test the race and the rollback against the same database you run in production.
Wrapping up
The hard part of a ticketing backend isn't the endpoints. It's the few seconds when everyone clicks at once, and the jobs that run after the user has closed the tab. Getting those right came down to plain things: database locks, the right indexes, idempotent tasks, and tests that run against the real stack.
I'm a Python backend and AI engineer working with FastAPI, Django, PostgreSQL, LangGraph and RAG, and I'm open to mid-level backend and AI engineering roles in India or remote. You can find me on LinkedIn, GitHub, or X.



