Stop overbooking workshops: book seats in a serializable transaction

Database · PostgreSQL · advanced · modification

Fixes overbooking on popular workshops. The booking endpoint counted the bookings and inserted the new one at READ COMMITTED, so two customers booking the last seat at the same moment could both get it. `app/workshops.py` now runs the whole booking as one transaction at `SERIALIZABLE`, so PostgreSQL rejects any interleaving that would let the count and the insert disagree, and the endpoint maps the outcomes (unknown workshop, already booked, sold out) through small exception classes. `tests/test_workshop_bookings.py` (new) covers the endpoint.

Workshop booking API: FastAPI 0.115 on Python 3.12 with psycopg 3.2 (plain SQL, no ORM), 4 pods against one PostgreSQL 16 primary whose `default_transaction_isolation` is the default, READ COMMITTED. `app/db.py` holds a `psycopg_pool.ConnectionPool` (at most 10 connections per pod). `pool.connection()` hands out a connection that is not in autocommit mode, commits on a clean exit and rolls back on an exception; on such an idle connection `conn.transaction()` issues `BEGIN` and commits at the end of the block, or rolls back if the block raises. An exception that an endpoint does not handle becomes a 500 (FastAPI's default). When the API is overloaded it answers 503 with `Retry-After`, and the web and mobile clients retry those; a 500 shows the customer "Booking failed". Tables from earlier migrations: `customers` (`id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY`, `email text NOT NULL UNIQUE`, `created_at timestamptz NOT NULL DEFAULT now()`); `workshops` (`id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY`, `title text NOT NULL`, `capacity integer NOT NULL CHECK (capacity BETWEEN 1 AND 500)`, `starts_at timestamptz NOT NULL`); `bookings` (`id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY`, `workshop_id bigint NOT NULL REFERENCES workshops (id)`, `customer_id bigint NOT NULL REFERENCES customers (id)`, `created_at timestamptz NOT NULL DEFAULT now()`, `UNIQUE (workshop_id, customer_id)`, whose index serves both lookups by workshop). Bookings are never deleted or edited by the API. `app.auth.current_customer_id` (existing) returns the signed-in customer's id or answers 401, and `app/main.py` already includes the `workshops` router. The test suite (`tests/conftest.py`, existing) builds a fresh test database from the migrations, empties it between tests, and provides `create_customer(email)`, `create_workshop(title, capacity)` (starting in 7 days), `fetch_one(sql, params)` and `client_for(customer_id)` (a test client signed in as that customer).

Requirements

Files touched

Review this PR

Database practice