Browse Engineering journal
Architecture & reliability

Reserve the last seat with one SQL statement

On this page

Put the availability check inside the update and trace what PostgreSQL does when a second buyer arrives.

Databases & Data Engineering · Dec 4, 2026 · 2 min read

At 09:00 a workshop has one remaining seat. Two connections each read the value one. Each application subtracts one and writes zero. The counter looks plausible, yet two buyers can receive confirmation. The missing piece is a condition evaluated at the moment the row changes.

UPDATE workshop
SET remaining = remaining - 1
WHERE id = 42 AND remaining > 0
RETURNING id, remaining;

Assume id is the primary key, remaining is a non-null integer and every reservation follows this path. On PostgreSQL at Read Committed, the second updater waits if the first holds the row. After a successful commit it evaluates the condition against the changed row. Zero fails the test. A rollback by the first updater instead leaves the seat available to the second. PostgreSQL transaction isolation.

What does an empty result mean?

It means the statement claimed no row. An unknown workshop ID and a sold-out workshop both fit that result. An API may deliberately collapse these cases into “unavailable.” If the product needs different messages, obtain the extra information separately and treat it as explanatory. The update result remains authoritative for the claim.

Insert the reservation record in the same transaction, then confirm only after commit. When the client can retry after a lost response, give the request a stable unique identifier and retrieve the previous outcome on a duplicate. Conditioning the decrement prevents a negative count. Identifying the request prevents a single buyer from consuming two available seats.

The single-row technique has a boundary. “Any two adjacent seats” involves a relationship across rows. A predicate on one row cannot by itself enforce that promise. Model the larger invariant explicitly before reusing this query.

Who crossed the validation split?Test a ticket classifier against a new customer, a new week and a repeated incident. Each split answers a different question.Where to draw a service boundaryFollow a seat reservation through two concurrent requests before deciding which components should deploy independently.

Search ObjectFAQ