Retry the Transaction, Not Just the Failed Statement
Tác Giả: OmniStack
Ngày đăng: 11/24/2026

On this page
- The failure is not just a failed statement
- Classify the database outcome before choosing a retry path
- Why PostgreSQL asks you to retry the complete transaction
- Proposed template: labelled PostgreSQL transaction retry example
- Keep external effects out of the retry loop
- Bound the retry policy and expose the business exception
- Acceptance checks before this becomes production behaviour
- FAQ
- Should PostgreSQL retry the failed SQL statement or the complete transaction?
- What SQLSTATE indicates a PostgreSQL serialization failure?
- Should every constraint violation be retried?
- Can a PostgreSQL transaction retry safely repeat a payment or warehouse call?
- When should an engineering team implement this work?
- Sources and limits
The failure is not just a failed statement
A hypothetical order allocation flow makes the boundary clear. Session A reads one unit of stock, decides that an order is eligible, and attempts to reserve it. Session B reads the same availability and commits its reservation first. PostgreSQL rejects Session A under the chosen isolation and locking pattern. Retrying only Session A’s failed UPDATE can preserve a decision that was calculated from state that no longer exists.
The correct PostgreSQL retry is a restart of the complete transaction, including the reads and business logic that produced the write. Session A must begin again, read stock, verify order eligibility, re-run allocation rules and attempt a new commit. The second attempt may reserve the item, reject the order because stock is gone, or stop for another classified outcome. A successful retry is not evidence that the original decision was still valid.
This matters in multi-site operations because inventory is rarely an isolated row. A reservation can affect picking, dispatch, replenishment and customer notification. The local database transaction can protect the invariant that stock cannot fall below its permitted threshold. It cannot make a warehouse instruction, payment call or email part of the same rollback boundary.
That distinction is the core of serialization failure retry business logic: the application must replay intent against fresh state, not replay stale SQL. PostgreSQL’s MVCC serialization failure handling guidance says applications using Serializable isolation must be prepared to retry transactions that fail with serialization failures, and that the retry must include the complete transaction, including the decision logic that led to the database writes.
A team reviewing an order service should ask one concrete question: which reads and decisions make the reservation valid? Every database write that defines that invariant belongs inside the retryable transaction attempt. A wrapper around the final statement is too narrow.
Classify the database outcome before choosing a retry path
Not every database error is retryable. A serialization failure, a deadlock and a business validation rejection have different meanings, and a retry policy that treats them alike can turn a clear rejection into a loop or hide a correctness defect.
Proposed template: retry outcome classifier. This table is a proposed review template, not an OmniStack deployment.
Outcome | PostgreSQL signal or example | What it means | Retry decision |
|---|---|---|---|
Serialization failure | SQLSTATE 40001 | The attempted execution could not safely form the required serial ordering. | Rollback, start a fresh transaction, repeat reads and decision logic, then stop at the configured bound. |
Deadlock | SQLSTATE 40P01 | Concurrent transactions are waiting in a cycle and PostgreSQL aborted one. | May be worth retrying, provided the transaction is restarted and the lock pattern is inspected. |
Unique or exclusion conflict | Constraint violation | Could be an ordinary duplicate or a race for a scarce resource. | Do not retry by code alone. Map the constraint to business meaning before deciding. |
Ordinary validation failure | Insufficient stock, cancelled order or invalid state | The business condition is false in the current state. | Reject or route for business handling. Retrying does not change the rule. |
PostgreSQL identifies serialization failures with SQLSTATE 40001. The same guidance notes that deadlocks, commonly reported as 40P01, may be worth retrying. That guidance is narrower than a generic application retry wrapper because it places responsibility on the application to retry the complete transaction.
Constraint errors need more care. Two requests racing to allocate a scarce resource may collide on a unique or exclusion constraint in a way that resembles serialization. PostgreSQL cannot always identify that meaning automatically. A duplicate order number submitted twice by a user is different from two valid requests competing for the same allocation slot. The classifier needs the constraint name, operation and business context, not just a broad exception category.
Locking also needs a precise interpretation. PostgreSQL’s explicit locking documentation explains how row locks, table locks and lock waits shape interleaving. Locks can reduce the set of bad interleavings. They do not replace the invariant, and they cannot make a stale application decision valid after the transaction has been aborted.
For a production service, record at least the SQLSTATE, constraint or lock context, transaction label, attempt count and final business outcome. That record lets an engineering leader distinguish retryable contention from an invalid allocation rule or an exception that needs manual handling.
Why PostgreSQL asks you to retry the complete transaction
A serialization failure invalidates the attempted transaction’s decision context, so the safe retry is a new transaction that re-runs the reads and business logic. Repeating only the failed write is unsafe because the write may encode assumptions made from a snapshot PostgreSQL has rejected.
In a hypothetical allocation rule, the application reads available_quantity, checks that the order is eligible and calculates a reservation quantity. The final statement may look deterministic, but it is the output of earlier observations. When another transaction commits a conflicting change, the output is no longer independently trustworthy. Re-executing the same UPDATE does not ask whether the order is still eligible or whether the quantity remains available.
PostgreSQL’s transaction isolation documentation describes the visibility rules behind this. At Read Committed, each statement sees a fresh snapshot at statement start. Higher isolation levels constrain visibility differently and may reject executions that would produce unsafe serial ordering. The application response must match that mechanism: start again and make the business decision against current state.
The retry boundary should therefore include:
- the read of current inventory and any version or status used by the rule;
- the eligibility checks that determine whether the order may proceed;
- the calculation of the reservation or allocation;
- every database write that protects the local invariant; and
- the commit that makes the result durable.
The retry boundary should exclude calls whose effects PostgreSQL cannot roll back. Payment capture, email delivery, warehouse instructions and publication to another system require their own contract. Treating them as if they were part of the local transaction creates a false sense of safety.
In a hypothetical modernisation of a legacy allocation service, the transaction boundary may be spread across repository methods, service methods and message handlers. That is where web application development with a defined delivery boundary can be useful, provided the engineers can trace the business invariant through the full application. The technical question is not which framework wraps the query. It is where the decision begins and where the local commit ends.

Proposed template: labelled PostgreSQL transaction retry example
The following is a proposed template, not an OmniStack deployment. Its purpose is to label the transaction so reviewers can see which actions are replayed, which decisions must be recalculated and which effects need a separate mechanism.
- Attempt scope: open a new database transaction for every attempt.
- Decision scope: perform all reads and business rules inside that attempt.
- Conflict scope: retry only classified transient outcomes.
- Effect scope: keep payment, email, warehouse and downstream publication outside the local retry loop.
Label | Inside transaction | Decision boundary | Retry rule |
|---|---|---|---|
T0: Intent received | No database write yet | Order ID and requested SKU are captured | Safe to start first attempt |
T1: Read current stock |
| Business rule uses current committed state | Must be repeated after retry |
T2: Decide reservation | Check stock is available and order is still eligible | This is not reusable across attempts | Recompute after rollback |
T3: Write reservation |
| Local invariant is stock cannot go below allowed threshold | Retry whole transaction on classified transient conflict |
T4: Commit result |
| Only committed state is accepted | Stop retrying after success or bounded failure |
T5: External effect | Outside the local transaction | Email, payment capture or warehouse event is handled separately | Do not duplicate by blind transaction retry |
A language-neutral retry shape makes the intended behaviour explicit:
- Capture the caller’s intent, such as order ID and requested SKU.
- Start attempt one with a fresh database transaction.
- Read stock, order status and any version used by the rule.
- Calculate the reservation from those reads.
- Write the reservation and inventory change within the same transaction.
- Commit and record the committed result.
- If PostgreSQL returns a classified transient error, roll back fully and start a new transaction within the bounded policy.
- Repeat the reads and decision logic. Never reuse the prior decision object as if it were current.
- Stop on success, business rejection, an unclassified exception or the configured attempt limit.
The phrase complete transaction does not mean every operation in the order journey. It means the complete local database operation that establishes the invariant. If the inventory update commits but a warehouse event is sent before the commit result is known, the application has created an external-effect problem, not solved one.
Proposed review questions: Can a reviewer identify the exact invariant? Are all writes that enforce it in one transaction? Does a retry create a new transaction object and connection state? Are reads repeated after rollback? Is a business rejection represented separately from a transient conflict?
Related:performance and scalability optimisation guidance, useful when repeated contention points to query shape or capacity decisions rather than a retry classifier alone.
Keep external effects out of the retry loop
A PostgreSQL rollback does not roll back a payment provider call, an email already sent, a warehouse task already created or a message already delivered to another system. The local retry mechanism protects the database transaction only. It does not provide a single-delivery outcome across system boundaries.
In a hypothetical payment flow, a reservation transaction calls a payment provider after reading stock but before committing. PostgreSQL later reports a serialization failure. The database state rolls back, but the payment provider may already have accepted the capture. Retrying the complete database transaction can issue a second capture unless the provider contract and request identity make the operation semantically safe.
The Amazon Builders’ Library article on making retries safe with idempotent APIs is useful because it frames retries around caller intent, semantic equivalence, late arriving requests and the risk that the same request identifier can be reused for a different intent. That source supports the mechanism, not a universal contract. Each provider and downstream system defines its own semantics.
A proposed effect boundary can record the local business result and the intent to notify another system after the local outcome is known. That makes the boundary reviewable. It still does not make the downstream system behave as part of the PostgreSQL transaction. Consumers and providers need their own duplicate-handling or idempotency rules.
Proposed template: external-effect boundary table.
Effect | Local retry can do | Local retry cannot do | Required design question |
|---|---|---|---|
Payment capture | Record a committed payment intent and retry local database work safely | Undo or deduplicate a provider call without provider support | What request identifier and provider response contract define a repeat? |
Warehouse instruction | Record the instruction intent after the local result is known | Determine that a warehouse system did not execute a prior request | Can the warehouse accept an idempotency key and expose status? |
Record notification intent and delivery state | Recall an email already sent | What duplicate notification is acceptable to the customer? | |
Message publication | Commit a local effect intent with the business change | Force a single downstream delivery | How does the consumer deduplicate or apply the event safely? |
Do not place an external call inside the database retry loop merely because it is convenient in the service method. Move it behind an explicit effect boundary, use the downstream contract available to you and make uncertainty visible to operations.

Bound the retry policy and expose the business exception
A retry policy is complete only when it defines when to stop. Each attempt should classify the error, roll back the failed transaction, start fresh, repeat the decision and record the result. A loop without a bound can turn contention into queue growth and hide the fact that the system needs a design change.
- Attempt limit: set a defined maximum for the operation. The PostgreSQL guidance requires preparedness to retry, not infinite retries.
- Classification: record SQLSTATE, constraint context, lock context and the application operation.
- Decision replay: re-run reads and business rules after every rollback.
- Final state: distinguish committed, rejected by business rule and escalated exception.
- Operational signal: expose attempt count, final outcome and transaction label to logs and monitoring.
Repeated 40001 outcomes may indicate contention around a scarce resource. Repeated 40P01 outcomes should prompt review of the lock acquisition pattern even if a later attempt succeeds. These observations should not be hidden behind a generic retry wrapper.
This is where the common answer fails. Add a retry wrapper treats database contention as a generic infrastructure event. The wrapper cannot decide whether a duplicate constraint error represents user error, a valid race or a broken invariant. It cannot determine whether a warehouse instruction has already been executed. It cannot choose the correct business outcome after stock changes.
For APAC CTOs, CIOs and multi-site operations leaders, the accountability question sits above the code loop. A dedicated external engineering team can implement and document the retry boundary, but the accountable organisation still needs to know who owns the code, the decision rules, the operational evidence and the downstream contracts.
OmniStack can be considered as a dedicated engineering team option when the invariant, operating rules and acceptance evidence are defined, but implementation capacity is the constraint. In-house engineering is the better choice when the domain rules, risk appetite and ownership model are still unsettled, because those decisions need to remain close to the business.
Proposed template: operating model decision table.
Operating model | What is being acquired | Who must own the retry decision | Where it fits |
|---|---|---|---|
Staff augmentation or individual developer supply | Additional individual capacity | Client engineering leadership and the assigned individuals | Useful when the client already owns architecture, acceptance criteria and delivery coordination. |
Dedicated delivery team | Continuing team capability across engineering and related platform work | Shared delivery governance, with the client retaining business accountability | Useful when the outcome is defined and implementation capacity is the constraint. |
In-house team | Permanent internal ownership of domain, code and operational decisions | Client organisation | Right when rules, controls and long-term product ownership are still being formed. |
Acceptance checks before this becomes production behaviour
The first acceptance test should force two concurrent reservation attempts against one scarce unit. The test passes only if the final committed state preserves the stock invariant and the losing attempt either recalculates and rejects or reaches a valid alternative outcome. A test that merely observes a retry count has not proved correctness.
The second test should prove that the business decision is recalculated. Arrange for the first attempt to read availability, pause it, let a competing transaction commit, and force the first attempt to fail. On retry, assert that the application reads current stock and applies the current eligibility rule. The test must fail if the old reservation quantity or old eligibility result is reused.
The third test should place an external effect at the boundary and prove that the local retry does not emit it twice. A proposed local effect-intent test can assert that one committed business result creates one effect intent, while a publisher or provider test separately exercises duplicate handling. A payment test should use the provider’s documented idempotency contract rather than assuming PostgreSQL rollback provides protection.
Proposed template: acceptance matrix.
Test | Induced condition | Expected database result | Expected external-effect result | Evidence to retain |
|---|---|---|---|---|
Concurrent reservation | Two transactions compete for the same stock | At most one committed result satisfies the scarce-stock invariant | No blind duplicate instruction from the local retry | Transaction labels, SQLSTATE and final states |
Stale decision rejection | Competing commit occurs after the first read | Retry repeats reads and recalculates eligibility | Only the accepted final outcome creates an effect intent | Attempt-level read and decision trace |
Deadlock recovery | Two paths acquire locks in conflicting order | Classified 40P01 rolls back and a fresh attempt is made | No external call occurs before the local result is durable | Lock context, retry count and final outcome |
Constraint race | Two valid requests compete for a unique or exclusion constraint | Application-specific classifier chooses retry or rejection | Downstream state remains consistent with the chosen result | Constraint name and business classification |
Ordinary rejection | Stock or order eligibility is false | No retry loop; transaction ends with a business rejection | No payment, email or warehouse effect is emitted | Rejection reason and correlation identifier |
Observe the transaction label at every stage: T1 read, T2 decide, T3 write, T4 commit and T5 external effect. Log the attempt count and SQLSTATE, but avoid logging sensitive payment or customer data. The useful record is enough to answer which attempt committed, which state it read and why the application stopped.
Infrastructure changes may be necessary when contention is a symptom of deployment, monitoring or operational visibility gaps. cloud and DevOps engineering support can help make deployment, monitoring and rollback evidence part of the implementation, but it cannot substitute for a settled invariant or a downstream idempotency contract.
If the acceptance tests fail because no one can state whether a duplicate warehouse task is acceptable, the problem is not yet a PostgreSQL retry problem. It is an unresolved operating rule. If the rule is clear but the internal team cannot implement and test the boundary without displacing operational work, a dedicated engineering team can provide that capacity while the client retains business accountability. If the rule itself is still disputed, keep the decision in-house and resolve it before assigning delivery.
The next decision is concrete: choose one contention path, write down its invariant and external-effect boundary, induce the conflict in a test environment, and reject any implementation that retries a stale decision.
FAQ
Should PostgreSQL retry the failed SQL statement or the complete transaction?
Retry the complete transaction. A serialization failure can invalidate the reads and business decision that led to the failed statement. The next attempt should start a fresh transaction, repeat the reads, recalculate the decision and write against the new state.
What SQLSTATE indicates a PostgreSQL serialization failure?
PostgreSQL reports serialization failures with SQLSTATE 40001. Deadlocks are commonly reported as 40P01 and may also be worth retrying, provided the transaction is fully restarted and the lock pattern is inspected.
Should every constraint violation be retried?
No. A duplicate identifier caused by repeated user input is different from a race between valid requests competing for a scarce resource. The application needs business-aware classification before retrying a unique or exclusion constraint failure.
Can a PostgreSQL transaction retry safely repeat a payment or warehouse call?
No. PostgreSQL rollback cannot undo an external call. Use the provider’s documented idempotency semantics and a clear effect boundary. Do not assume the database retry loop controls downstream delivery.
When should an engineering team implement this work?
A dedicated engineering team is suitable when the invariant and operating rules are defined but implementation capacity is the constraint. In-house ownership is the better choice when domain rules, risk appetite or accountability are still unsettled.
Sources and limits
These sources support the mechanisms described here. They do not create universal behaviour across every application, provider or downstream system.
- PostgreSQL documentation: Serialization Failure Handling, for the requirement to retry complete transactions, including decision logic, after serialization failures.
- PostgreSQL documentation: Transaction Isolation, for visibility rules at Read Committed and higher isolation levels.
- PostgreSQL documentation: Explicit Locking, for row locks, table locks and lock waits as interleaving controls rather than substitutes for invariants.
- Amazon Builders’ Library: Making retries safe with idempotent APIs, for caller intent, semantic equivalence and late-arriving request considerations in API retries.

