Hypothetical scenario. Northwind recognizes retries of one reservation, but now two different buyers request its last unit. Each intention has a different identifier. Dev reads the available quantity before inserting each reservation; Priya pauses both requests just after that read.
Dev: “Neither request is a duplicate.”
Maya: “Then which shared rule decides whether both may be accepted?”
Move from operation identity to a local business invariant. Define the condition that must survive concurrent legitimate intentions, then put its decision and state change inside the chosen transaction boundary. These reservation examples are separate from the browsing workload.
Which different intentions are allowed to succeed together?
Idempotency binds repeated attempts to one intention. It does not decide whether two distinct intentions can both succeed. The business invariant here is that accepted active reservations cannot exceed the allocatable units of the selected item. Returning an old receipt correctly does not protect that quantity against another buyer.
Start with the rows representing authority: available quantity, accepted reservation, operation identity and any durable downstream intent. If they can share one PostgreSQL transaction, define their transition together. Moving a stock check into another service would add a coordination problem before there is evidence that the local boundary is inadequate.
The obvious read-then-write approach is vulnerable even when each individual statement is valid. Both callers can read an eligible quantity before either records its reservation. A transaction is necessary for a grouped decision, but the isolation level and predicates determine which concurrent histories remain possible. Merely surrounding statements with a transaction label does not describe those histories.
Make the authority decide conditionally
One possible design stores the available count in the item’s authoritative row. A transaction conditionally decreases it only when sufficient quantity remains, inserts the reservation and binds the successful result to its logical operation. Failure of any required local change aborts the grouped transition. A failed conditional update means insufficient current authority for that request; an uncertain commit response remains a recovery problem tied to the same operation.
The condition must be enforced when the database performs the change. An application-side check of a stale copy does not supply equivalent protection. For this design the item row is a deliberate coordination point. Contention there reflects competing demands for a scarce unit, rather than a flaw that can be removed simply by giving every worker its own counter.
Protect a predicate with a real contention point
Hypothetical scenario. The rule permits at most one active reservation per tenant. Two transactions insert different reservation rows after each snapshot reports zero active rows. A row-level uniqueness rule on reservation identity cannot protect the shared predicate because the written identities differ.
| Invariant | Insufficient protection | Candidate authority |
|---|---|---|
| One active per tenant | Unique reservation ID | Active-only uniqueness / guard |
| Quantity cannot go negative | Old application read | Conditional decrement |
| Remote payment once | Local transaction isolation | Provider operation identity |
One possible PostgreSQL design represents the active-only uniqueness condition with an appropriate unique index; another serializes through a tenant-owned guard row; serializable isolation is another option with required retry handling. The chosen design must match the real predicate, including expiry and status transitions. Do not assume a generic lock on any row protects records that have not yet been inserted.
A retry after serialization failure must replay the transaction's decision from fresh evidence, not just resubmit its final insert. Keep external side effects outside a retryable local transaction unless a separate protected protocol makes them safe. Contention is both a workload issue and evidence that the authority boundary is doing real coordination.
Work the last-unit race
Hypothetical worked example. Choose one available unit and two concurrent requests, each asking for one unit. If both independently accept their old observation, accepted quantity is 1 + 1 = 2. It exceeds capacity by 2 − 1 = 1 unit. Each request can have a perfectly unique operation identity while the combined result is invalid.
Under the proposed conditional transition, the first accepted transaction reduces available quantity by 1 − 1 = 0. The competing transaction cannot satisfy its quantity condition against that committed state. Its rejection creates no reservation. Accepted quantity is one and remaining quantity is zero, preserving 1 + 0 = 1 total unit in this simplified model.
This calculation assumes no replenishment, expiry or cancellation during the two decisions. Those actions must enter the same invariant argument. A release must correspond to an existing reservation and must not add the unit repeatedly when its own delivery is retried. Conservation is a state-transition property, not just an arithmetic check on the happy path.
Isolation needs a specific anomaly argument
Row locking can serialize competing changes to the selected item. Optimistic version checks can reject a transition whose expected version no longer matches. Serializable execution can reject transactions whose combined behavior cannot match an allowed serial ordering. These mechanisms differ in blocking, retry and operational behavior; none removes the need to state the business predicate.
Consider an invariant spanning several rows, such as a limit on all active reservations in a tenant. Locking just one existing reservation does not necessarily protect the set, including new rows. The design might use a tenant authority row, an appropriate constraint or serializable transactions with whole-transaction retries. Explain the actual mechanism instead of extending a single-row proof to every possible predicate.
A serialization failure requires retrying the complete decision with fresh observations. Repeating only the final statement can preserve conclusions drawn from an invalid earlier snapshot. Retain the logical operation identity across the retry, and ensure that external effects have not escaped before the local transaction commits.
Protect a predicate when the transactions write different rows
Hypothetical scenario. Northwind permits at most one active reservation for a tenant. Initially no reservation is active. Transactions A and B take snapshots in which the active count is zero. Each decides to insert one active reservation with a different identifier. Their row identities do not conflict. If the chosen isolation permits both decisions to commit, the resulting count is 0 + 1 + 1 = 2, exceeding the allowed one by 2 − 1 = 1.
This is a predicate-level write-skew problem: each decision relies on the absence of a competing active row, while the transactions write distinct rows. Neither a unique operation key nor locking one existing reservation covers the absent future row. A plain read of zero followed by an insert is not an atomic claim on the tenant’s remaining right.
One repair serializes every relevant transition through the same tenant authority row, locks it before evaluating the active count and holds that lock through commit. Under a statement-snapshot design, the count must be read after acquiring the lock; reusing an older snapshot can defeat the intended reasoning. Every insertion, activation, cancellation or transfer affecting the invariant must participate. This trades a deliberate coordination point for a simple authority argument.
A second repair encodes the exact invariant as a database constraint where the schema supports it. A third runs the complete decision at serializable isolation and handles serialization failure by retrying the whole transaction with fresh observations. PostgreSQL 18’s isolation documentation distinguishes its snapshot-based Repeatable Read from Serializable and explains retry obligations. A consistent snapshot can still allow an anomaly involving concurrent decisions.
Keep three different failures distinct. A lost update overwrites another change using an obsolete value. A phantom concerns a changed qualifying set between reads. Write skew can violate an invariant even when a transaction’s repeated snapshot reads remain stable. Naming the isolation level is useful only when paired with the history it permits and the invariant the mechanism protects.
For this exercise, choose the explicit tenant authority when the tenant-level coordination cost is acceptable. Prefer an exact constraint when it expresses the real rule cleanly; consider serializable transactions when the invariant spans predicates awkward to lock manually. Measure contention and whole-transaction retries before introducing another distributed authority. None of these database choices retracts an external action performed before an abort.
Can A and B both be valid in a serial execution of this predicate check and insert?
No. Starting at zero, whichever transaction is first inserts the single active reservation. The second then observes one and cannot accept under the declared rule. Accepting both snapshots therefore has no valid serial explanation for these complete decisions.
In the wild: isolation rules are inspectable
PostgreSQL documents its transaction-isolation behavior, including serializable execution and retry obligations. Use those documented rules to evaluate the proposed transition. They describe the database boundary, not the atomicity of a subsequent broker publication or external payment.
An outbox record can share the local commit with the accepted reservation. Its dispatcher can still deliver more than once. The protected-effect lesson therefore continues to matter downstream. Local atomicity and safe repeated delivery compose different parts of the end-to-end argument.
A protected row does not contain a remote action
Hypothetical failure scenario. A reservation transaction holds the item row while calling a payment provider. The provider completes, but the local transaction later aborts. The database releases its local changes while the external payment survives. Holding a lock longer did not extend the database’s authority over the provider.
Keep irreversible external calls outside a falsely advertised local atomic boundary. Record intent and progress, then use the cross-service workflow contract developed next. Conversely, do not introduce a distributed workflow when stock and reservation can remain one coherent local decision. The boundary should follow the required invariant and actual ownership.
Use contention as evidence
A hot item can cause waiting or repeated transaction aborts. Measure that behavior before selecting a more elaborate ownership model. Admission control, per-item ordering or a different allocation policy can help, but changing the policy changes what buyers are promised. Splitting authority across independent counters can accept too many reservations unless a separate allocation argument bounds their combined rights.
This example excludes partial fulfillment, backorders and multi-item carts. A multi-item reservation needs a declared all-or-nothing or partial-success policy, consistent lock ordering where relevant and recovery for uncertain completion. The single-item example is a foundation for that reasoning rather than proof that all commerce workflows are solved.
Challenge the proposed mechanism
Both inserts have unique IDs and both transactions saw zero. Which proof obligation is missing?
Reveal the design reasoning
Show how concurrent decisions conflict at the invariant owner. Provide the constraint, serialized guard or isolation argument, including rejection and retry behavior. Unique intentions prevent duplicate requests but do not resolve distinct competing intentions.
Decision and reconsideration: Choose the narrowest enforceable invariant boundary. Test a concurrent history that writes different rows before claiming protection.
Check the transaction boundary
Both requests have unique keys. Why can the last unit still be oversold?
Separate identity from scarcity
The requests represent different intentions, so deduplication correctly permits both to compete. The authoritative quantity transition must decide which can succeed.
A transaction aborts after an external charge completes. Does rollback undo the charge?
Locate the resource boundary
No. The provider did not participate in the local database commit. Preserve external uncertainty and reconcile the original operation using supported evidence.
A tenant-wide predicate spans many rows. Is locking one reservation enough?
Protect the actual predicate
Not by itself. Concurrent inserts or other reservations can change the set. Select a mechanism covering the tenant invariant and account for its contention and retries.
The local transaction can protect the reservation it owns. Page 29 adds an independent payment provider and asks which promises remain local, which need coordination and which outcomes must remain pending.
Northwind decision log
Keep stock, reservation, operation result and downstream intent in one justified local boundary.
Enforce quantity and identity with separate appropriate mechanisms.
Next, model intermediate states when an obligation crosses authorities.
Go deeper: isolation and enforcement
- Book chapter: Transaction Processing, chapter 7: Isolation Concepts — Jim Gray and Andreas Reuter. Analyze concurrent histories.
- Book chapter: Transaction Processing, chapter 8: Lock Implementation — the same authors. Connect a predicate to its enforcement. This historical reference does not specify current PostgreSQL defaults.
- Video lecture: F2023 #15: Concurrency Control Theory — CMU Database Group. Inspect interleaved transactions and correctness.
- Primary document: Transaction Isolation — PostgreSQL. Check the selected implementation’s behavior.