JINNBITSResearch & insights

Who Gets the Last Seat? A PostgreSQL Booking Exercise

One seat and two confirmations expose a stale inventory read. Reproduce the failure in PostgreSQL, then make the booking depend on a successful claim.

In this fictional workshop, two buyers read remaining = 1 and receive confirmations for the same last seat. Both transactions commit because the service treats an earlier read as permission to insert. Make the inventory write decide whether the booking can exist.

Two commits against one seat

Open three dedicated connections to a scratch PostgreSQL 17 database under the same role. Use A and B for buyers. Run the fixture and observations on C in autocommit.

CREATE TABLE workshops (
  id integer PRIMARY KEY,
  capacity integer NOT NULL CHECK (capacity >= 0),
  remaining integer NOT NULL CHECK (remaining >= 0)
);

CREATE TABLE bookings (
  id text PRIMARY KEY,
  workshop_id integer NOT NULL REFERENCES workshops (id),
  active boolean NOT NULL DEFAULT true
);

INSERT INTO workshops (id, capacity, remaining) VALUES (1, 1, 1);

Run this on A and B and record their backend PIDs. Finish both reads before either buyer writes. B needs a snapshot from before A commits. If B starts its read after that commit, it sees 0 and stops at the availability check, masking the defect.

BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT pg_backend_pid();
SELECT remaining FROM workshops WHERE id = 1;

Both clients read 1 and compute 0. Run this block on A, then on B with booking ID 'B' in B's still-open transaction.

UPDATE workshops SET remaining = 0 WHERE id = 1;
INSERT INTO bookings (id, workshop_id) VALUES ('A', 1);
COMMIT;

After both commits, take this snapshot on C.

SELECT w.capacity, w.remaining,
       count(b.id) AS active_bookings,
       array_agg(b.id ORDER BY b.id)
         FILTER (WHERE b.id IS NOT NULL) AS active_booking_ids
FROM workshops AS w
LEFT JOIN bookings AS b ON b.workshop_id = w.id AND b.active
WHERE w.id = 1
GROUP BY w.id;

The snapshot shows capacity 1, remaining 0, and 2 active bookings, A and B. Each client writes the absolute value 0 from its stale read, so each new row version satisfies CHECK (remaining >= 0) even as the ledger exceeds capacity. With an unguarded SET remaining = remaining - 1, B would subtract from A's committed 0. PostgreSQL would reject the resulting −1 with SQLSTATE 23514 (check_violation) and abort B's transaction. Adding WHERE remaining > 0 lets B record sellout in the same transaction when its update returns no rows. Keep the check as a backstop for writes that would store a negative count.

Make B wait for A's decision

Reset from C between runs with both buyer transactions closed. Reuse the connections to preserve their PIDs.

BEGIN;
DELETE FROM bookings WHERE workshop_id = 1;
UPDATE workshops SET remaining = capacity WHERE id = 1;
COMMIT;

On A and B, apply these session settings before starting the guarded transactions. The 10-second lock limit and 15-second statement limit leave room for the 5-second observation window. Disable the idle and whole-transaction timers on these scratch connections so a pause at A's prompt cannot decide the outcome.

SET lock_timeout = '10s';
SET statement_timeout = '15s';
SET idle_in_transaction_session_timeout = 0;
SET transaction_timeout = 0;

Begin Read Committed transactions on both buyers. Run the statement on A and leave its transaction open after it returns the provisional ID. Submit it on B with 'B' in place of 'A'. In application code, bind both IDs.

WITH claim AS (
  UPDATE workshops
  SET remaining = remaining - 1
  WHERE id = 1 AND remaining > 0
  RETURNING id
)
INSERT INTO bookings (id, workshop_id)
SELECT 'A', id FROM claim
RETURNING id;

From C, poll the following query in autocommit with the recorded PIDs substituted for A_PID and B_PID. Start the 5-second deadline when B submits its statement. Once the query returns true, resolve A promptly. If the deadline expires or B's statement finishes before you observe the wait, fail the run. Roll back A to release B and roll back B once its statement finishes.

SELECT A_PID = ANY (pg_blocking_pids(B_PID)) AS b_waits_on_a;

Commit A in the first guarded run. PostgreSQL rechecks B's update predicate against A's committed version with 0 remaining. The empty claim feeds no rows to the insert. Commit B, then reset and repeat with A rolling back. B decrements the original count of 1, inserts its own booking, and commits.

The database and the buyer must agree

Figure 1 — Zero remaining describes all three runs. The baseline row reveals the oversell in the buyer columns. Illustrative counts of remaining seats and active bookings, not measured data.

The PostgreSQL 17 manual documents the recheck under “Read Committed Isolation Level” and lists 23514 in “PostgreSQL Error Codes.” A separate SELECT ... FOR UPDATE also works if all writers lock the workshop before checking capacity. The CTE eliminates the round trip between locking and writing. Restrict direct writes that bypass the guard.

A statement error discards the decrement. Clear the failed transaction with ROLLBACK, or recover with ROLLBACK TO SAVEPOINT if you set a savepoint before the claim. Adding ON CONFLICT DO NOTHING to the booking insert can spend a seat on a duplicate ID because the skipped insert raises no error. Resolve duplicates before decrementing inventory.

The predicate protects only the workshop it updates. For a quota shared across workshops, serialize the check and change on a common quota row or run all quota checks and changes at Serializable. The shared row puts independent workshops in one lock queue. Serializable can discard work at commit after the client has received a provisional ID. On SQLSTATE 40001, retry the full transaction with fresh reads and the original request key.

If you add a boolean sale flag and filter the claim with AND on_sale, an empty result can mean closed, missing, or full. If the endpoint needs distinct outcomes, lock by workshop ID first and classify the result from that read. A lookup after an empty claim may see a seat that a cancellation just reopened.

The connection drops during commit

Treat the returned booking ID as provisional until commit succeeds. Give each logical request a unique key scoped to the caller and operation. Claim that key before taking the inventory lock and store the normalized parameters alongside it. Commit the final request outcome with the inventory change and booking, or with a definitive sellout. A retry with the same key and changed parameters receives a conflict.

At Read Committed, claiming the key with INSERT ... ON CONFLICT DO NOTHING can wait on another transaction. If the first writer commits and the insert skips, fetch the existing outcome in a separate statement. The snapshot of the insert statement can miss the very row that caused the conflict. If the first writer rolls back and the second acquires the key, the second proceeds to inventory. Keep request records through the supported retry window. A stored sellout remains the answer to that request after a cancellation reopens inventory. A buyer who wants to try again submits a new request.

Test ambiguous commit with the request ledger in place. Suppress A's response after commit, then replay its key and assert the same ID with inventory unchanged. Reset inventory, bookings, and request records before testing rollback. Roll back A's transaction, then replay and assert that it claims the seat.

PostgreSQL 17's “Statement Behavior” section distinguishes the limits. lock_timeout caps each lock acquisition attempt, statement_timeout caps each statement, and idle_in_transaction_session_timeout terminates sessions idle too long inside a transaction. PostgreSQL 17 added transaction_timeout, which terminates sessions that exceed a whole-transaction budget including idle time. The caller's deadline also covers pool checkout, commit acknowledgment, and replay. If time runs out while the outcome is unknown, report an unconfirmed outcome and retain the key for later recovery. Roll back failed transactions on live pooled connections before reuse. Discard broken or terminated connections.

A cancellation can strand sellable inventory

Compare stored remaining with capacity minus active bookings in one snapshot. Extend the fictional fixture from a guarded run with one committed booking. At booking commit, both balances are 0. A faulty cancellation clears the active flag and omits the credit. Ledger availability rises to 1 while stored remaining stays at 0. After a fix that credits only active-to-inactive transitions, a retry finds the booking inactive and leaves those balances unchanged. Reconciliation raises stored remaining to 1.

Figure 2 — The ledger records the freed seat at cancellation. The counter records it at repair because the retry finds no transition to credit. Illustrative balances from the fictional cancellation, not measured data.

For pooled seats, lock the workshop before changing a booking. Credit inventory in the same transaction only if the update finds active = true and changes it to false. A writer that locks the booking first can deadlock with one that already holds the workshop row and needs the booking. Capacity edits take the same workshop lock and apply the capacity delta only if the new capacity covers the active bookings. Alert on either sign of drift. A high counter can admit bookings the ledger has no capacity for. At Read Committed, acquire the workshop lock first, then count active bookings in a separate statement so the snapshot includes commits that finished while the repair waited. Set the counter from that count while holding the lock. If active bookings exceed capacity, resolve which bookings to honor or increase capacity before resetting the counter.

Choose which row can establish exhaustion

For buyers eligible for any seat, scan free, preallocated slots in a stable order with LIMIT 1 FOR UPDATE SKIP LOCKED. Mark the slot occupied and insert the reservation together. Require a non-null foreign key to the slot and a partial unique index on slot ID for active reservations. Cancellation locks the slot before changing assignment and availability together.

The PostgreSQL 17 SELECT reference warns that skipping locked rows provides an inconsistent view of the data. An empty claim scan can skip a slot with an uncommitted assignment. If the lock holder rolls back, that slot is still free. Read eligible slots again in a fresh Read Committed statement without a locking clause. If the snapshot shows every eligible slot occupied, it supports a sellout as of that read. If it shows a free slot, end the transaction before backing off and retry within the deadline, or return a transient result. Measure from the empty scan through all retries and flag requests that reach their deadline without a definitive inventory decision.

Use the pooled counter when seats are interchangeable and a workshop can afford to serialize short writes. Use fixed slots when seat identity matters or workshop-level lock waits dominate admission and buyers can claim different slots in parallel. Near sellout, those buyers converge on the same few rows and a fast claim scan can leave the decision unresolved. In either design, confirm a booking only from a committed claim and resolve an interrupted confirmation through the original request key.