Two requests can each pass a business-rule check and still produce an invalid combined result. Placing each request inside a transaction does not by itself establish that the checks coordinate correctly. Choose transaction isolation and locking from the state the business must preserve under concurrent execution.
In the PostgreSQL 18 example below, a project must keep at least one active approver. Following two simultaneous removals shows why separate row updates can violate that rule, how a shared lock changes the schedule, and why a retried transaction can legitimately reject the requested removal.
Write the rule independently of the implementation
Start with a precise invariant: a condition that must remain true after committed changes. In the synthetic workflow, at least one active approver must remain assigned to a project. Two different approvers may request removal at the same time.
Describe the rule in terms of committed state, including relevant transitions. Creating a project, removing an approver, disabling an account, and moving membership may all affect the same invariant. A correct removal endpoint is insufficient if another path can invalidate the assignment indirectly.
List the records and predicates used to decide whether removal is allowed. Distinguish the request's target row from the set of rows whose combined state matters. Locking only the target row may not coordinate two removals that concern different targets.
Choose a useful failure response before implementation. If a concurrent operation makes removal invalid, the caller should receive a stable business rejection or a bounded retry outcome. Exposing a database exception or internal query does not help the user understand whether the requested change occurred.
Interleave the decisions on paper
Consider project P with active approvers Alice and Bob. Neither request is allowed to remove the last approver. The following is a synthetic schedule, not an execution transcript:
- Transaction A begins and counts two active approvers for P.
- Transaction B begins and also counts two active approvers for P.
- A decides Alice may leave and updates Alice's assignment to inactive.
- B decides Bob may leave and updates Bob's assignment to inactive.
- A and B commit. There are no active approvers left.
The writes touch different rows, so a simple same-row write conflict need not stop this schedule. At Read Committed, both count statements can finish before either update commits. A stable Repeatable Read snapshot also does not make this cross-row decision serial: both transactions can retain their original view of the set. This is the write-skew problem the invariant exposes.
The PostgreSQL 18 isolation documentation describes statement snapshots at Read Committed and the stronger snapshot behavior of Repeatable Read. It also distinguishes the serialization anomalies that Repeatable Read can still allow from Serializable behavior. Use those documented semantics rather than assuming that a stable snapshot coordinates every cross-row business decision.
If A commits before B counts under Read Committed, B can see the remaining approver and reject the removal. A sequential test exercises that favorable schedule and can pass while the overlapping schedule above remains broken.
Repeat the exercise for every writer affecting the invariant. A scheduled account-disabling job may matter as much as the public endpoint. Capture these writers in the design review so the coordination protocol has a defined participation boundary.
Choose a coordination mechanism the writers share
Evaluate whether a database constraint can express the rule directly. When it cannot, consider an explicit shared coordination record, an appropriate locking protocol, or Serializable transactions. The correct choice depends on the affected set, expected contention, and supported failure behavior.
For this workflow, an existing project row can provide a shared coordination target. Under Read Committed, use a separate lock-acquisition statement before reading the assignment count. The intended schedule is:
- A locks project P's coordination row for update.
- B tries to lock the same row and waits.
- A reads the assignment count, removes Alice, and commits.
- B obtains the lock, then runs a new count statement.
- B sees one active approver and rejects Bob's removal without changing it.
The order matters: B must not count first and use the saved count after waiting. It must also not assume that a count taken in an earlier snapshot becomes fresh merely because a lock was later acquired. This protocol is specifically described at Read Committed, where the subsequent statement can observe A's committed change. Re-evaluate it before moving the transaction to another isolation level.
Every removal, account disablement, membership move, and maintenance writer affecting P must acquire the same coordination lock before making the decision. If one operation affects two projects, it also needs a common order for those locks; the deadlock guide explains why direction-dependent ordering is insufficient.
Serializable execution offers another approach, with applications prepared to handle rejected concurrent schedules. In the Alice/Bob example, both transactions must perform the count and update inside Serializable transactions; one may receive a serialization failure instead of both invalid decisions committing. On retry, the surviving approver count is one, so the correct outcome can be a business rejection. Retrying successfully does not mean the requested removal must eventually be accepted.
Serializable does not make external actions transactional or remove the need for database constraints and authorization. Keep the invariant calculation inside the transaction whose isolation provides the evidence.
Compare operational costs with representative contention. A shared lock can serialize unrelated work if its scope is too broad. Retries can increase work under conflict. Record why the selected mechanism fits the actual project-level operation rather than calling one isolation level universally best.
Retry the whole decision within a bound
The serialization failure guidance identifies SQLSTATE 40001 and explains that retry must include the complete transaction logic. Repeating only the final write can reuse a decision made from an invalidated observation.
Place the retry boundary around reading current state, checking the invariant, choosing the change, and committing. Limit attempts and total elapsed time according to the request budget. Release the failed transaction before waiting, and stop work when the caller's operation is canceled through the supported execution path.
Separate a confirmed transaction rejection from an ambiguous connection failure during commit. If commit acknowledgment is lost, blindly rerunning can repeat a change that already committed. Use the operation's identity and recovery procedure to determine the authoritative result; the idempotent write guide addresses that boundary.
Keep email, payment, and other remote effects outside a retry body unless their repetition has a separately supported protocol. For durable downstream intent, assess the transactional outbox guide. A local rollback cannot recall a request already accepted by another service.
Test committed outcomes under controlled contention
Build an integration exercise with two independent database sessions and explicit synchronization points. Arrange for both operations to reach the relevant decision boundary before releasing them. Assert the final committed invariant and the callers' outcomes rather than expecting a particular transaction to win.
Add the account-disabling and administrative paths to the same exercise. Include retry exhaustion, cancellation, and a normal business rejection after another transaction succeeds. Verify that the public error remains stable while internal diagnostics preserve only the sanitized information needed to investigate.
Record retry counts and contention duration without placing project or user identifiers in metric dimensions. Revisit the mechanism when the writer set or data distribution changes. The design is acceptable when every writer participates in a known protocol and unfavorable schedules still preserve the business rule.
Was this guide useful?
Your rating helps us prioritize clearer, more practical technical content.
Review diffs, run checks, and prepare the release in Arezgit.
Keep Git review, security scanning, API checks, database inspection, and release preparation together in one local desktop application.
Explore Arezgit