Relational databases: collection tree

Relational databases

Retries and uncertain commit outcomes

Deep diveAbout 10 minutes AI-generated

A retry is another attempt to carry out the same request. It can repair a transaction that the database aborted, but a missing reply asks a different question: did the first attempt already commit? Repeating a purchase without answering that question can buy twice, or tell a customer that stock is unavailable after their purchase succeeded.

The database can help answer it if the application gives the request a stable identity and commits its result with the purchase. Each later attempt can then recover that result instead of purchasing again. This is often called an idempotency key: repeated calls with the same key and meaning have one retained effect.

Every example follows Mina’s purchase of one blue mug, P7 at 20.00, and two packs of green tea, P3 at 4.50 each. Before it, stock is P7 = 1 and P3 = 12. A successful transaction creates pending order 103 and its two order lines, leaves P7 = 0 and P3 = 10, and records no payment. Transactions and isolation establishes the atomic purchase; here the problem is recovering it when an attempt fails or its reply disappears.

When the reply never arrives

Mina submits the purchase. The application sends COMMIT, then loses its database connection before it receives an answer. One possible execution stops before the commit becomes durable. Another completes the commit but loses its reply. The application cannot distinguish them from the broken connection alone.

One missing reply, two possible histories
Figure 1. Two alternative histories, not two purchases in one run.
Figure as text

The caller sends COMMIT and hears no reply. The database might have aborted the attempt or committed the whole purchase. Neither is established by the missing reply.

If the attempt never committed, there is no order 103 and the mug is still available. If it committed, the order exists and its mug has gone. A timeout tells us when the application stopped waiting; it does not choose between these histories.

A blind repeat after the committed run might see stock 0 and report “mug unavailable”. That answer is wrong for Mina’s original request: she already has the mug in order 103. With more stock, the repeat might instead create a second order. A stock guard protects the stock count, but it does not identify whose earlier purchase consumed it.

A known abort

If the database explicitly reports a transaction abort, that attempt did not commit. A serialization failure is one such answer. After ending the failed transaction, the application can make a new attempt where the failure is retryable. It must repeat the reads and the decisions that chose the writes: a stock count read by the aborted attempt is no longer a basis for the next one.

An uncertain outcome

A broken connection while committing provides no such answer. Nor does merely sending a cancellation request: it can arrive after the command finished. Losing the application’s reply to Mina creates the same problem one hop further out, even if the application received COMMIT successfully. Database commit, the database’s reply and the caller’s reply are three separate events.

Connection recovery and disposal belong at the application boundary. Once there is doubt about commit, this article’s protocol must recover the logical request on a usable connection.

One request identity across attempts

Mina’s caller creates purchase-103 before the first attempt and keeps it for every repeat of this purchase, including after a page reload or an application restart. The name is memorable for the example; in an application the token should come from an identifier scheme that avoids accidental reuse.

The key belongs to customer 1’s purchase operation. Another customer’s token is a different identity, and a refund operation must have its own scope. The resulting order number is separate: the caller needs the request identity before it knows whether an order was created.

Figure 2 What stays the same on a retry
Request identitycustomer 1 · purchase · purchase-103
Meaning supplied with the request

P7 × 1 at 20.00
P3 × 2 at 4.50

Result retained at commit

Accepted → order 103
Created pending · total 29.00

The same identity and payload recover this result. P7 × 2 under this identity is a mismatch, even if it comes from the same customer.

The service binds the key to a canonical payload, the relevant request values in an agreed representation. Here those values are the product identities, quantities and agreed prices. It validates the values, normalises their representation and compares them on every duplicate. Equivalent line ordering can be normalised if the API defines it as equivalent. Delivery address, currency or a quote identity would also belong here if they changed the operation’s meaning.

A changed quantity under purchase-103 is rejected as a key–payload mismatch, without applying it. The service must not overwrite the old payload. Two intentional purchases of identical contents need two different keys; comparing contents alone cannot tell a repeat from a second purchase. The authenticated customer determines whose results may be recovered: a token is no substitute for authorisation.

Commit the purchase and its result together

The application adds a request table. Its primary key admits one row for each customer’s token; the table itself supplies the purchase-operation scope. payload holds the canonical request and result holds the terminal answer. A terminal answer is one this request will keep returning, such as “accepted as order 103” or “refused for insufficient stock”.

CREATE TABLE purchase_requests (
  customer_id integer NOT NULL REFERENCES customers,
  request_key text NOT NULL,
  payload jsonb NOT NULL,
  result jsonb,
  PRIMARY KEY (customer_id, request_key)
);

The protocol temporarily leaves result null while its transaction works. It must never commit that intermediate row. Access to this table must go through the protocol, which either fills the result or rolls the whole transaction back. Null is not a separately committed “in progress” job requiring another worker to finish it.

The purchase and its retained result need the same commit boundary. A crash between separate commits can leave recovery with only one of those facts.

The work and its saved answer
Figure 3. A saved success is trustworthy only when it commits with the work.
Figure as text

An atomic commit records the request identity, its purchase and its accepted answer together. Splitting those commits creates a crash gap: either a purchase without its answer or an answer without its purchase.

With one transaction, an aborted attempt leaves neither purchase nor request record. A committed attempt leaves both. Committing the purchase first can leave an order without a way to recognise its repeat. Committing the answer first can leave a success record for a purchase that never happened. Either separate order creates a gap.

A business refusal is a result

Suppose the purchase cannot obtain all its stock. This service’s contract retains “insufficient stock” as a terminal refusal. It commits the refusal with no order and no stock change. A later restock does not turn a repeat of that key into a new purchase; the caller must deliberately start a new request with a new key.

That differs from a database abort. An abort retains no decision from the failed attempt. The next attempt may make a different decision from fresh data. Choose and document which business refusals your API retains; input rejected before the protocol begins need not consume a key.

Two attempts for the same request

Checking for an existing request before buying is insufficient. Two application instances can both read “absent” before either inserts a row. The database-enforced unique key must decide which attempt may do the purchase.

This PostgreSQL example starts a Read Committed transaction and attempts to insert the key. $1 is the validated canonical payload, supplied as a parameter. Only an attempt that receives a row from RETURNING may enter the purchase branch.

BEGIN ISOLATION LEVEL READ COMMITTED;

INSERT INTO purchase_requests
  (customer_id, request_key, payload)
VALUES (1, 'purchase-103', $1::jsonb)
ON CONFLICT (customer_id, request_key) DO NOTHING
RETURNING request_key;

A competing insert for the same key may wait while the first transaction is unresolved. Call the first attempt A and the waiting attempt B. A’s commit or abort determines whether B recovers the existing result or may carry out the purchase itself.

One request key, one purchase
Figure 4. A selected Read Committed schedule; errors can require a whole retry.
Figure as text

Attempt A inserts the unique request key before changing stock. B’s same-key insert waits. If A commits, B reads and compares the retained result in a fresh statement without purchasing again. If A aborts, B can acquire the key and perform the purchase.

If A commits, B’s DO NOTHING returns no row. B then runs the following separate statement to obtain a fresh Read Committed snapshot, compares the payload and returns the stored result if it matches.

-- A separate statement, after INSERT returned no row:
SELECT payload, result
FROM purchase_requests
WHERE customer_id = 1
  AND request_key = 'purchase-103';

The separation matters. PostgreSQL can decline an ON CONFLICT DO NOTHING insert because of a concurrent row that its statement snapshot cannot see. Combining the insert and an ordinary fallback read in one statement can therefore return nothing. A missing row in that observation is not evidence of rollback. Under the retained-record protocol, the next Read Committed statement can read the committed row. If an implementation still cannot obtain it, it must re-enter the protected protocol or report unresolved recovery. It must never bypass the gate.

If A aborts, its row and purchase disappear. B’s waiting insert can then succeed, and B may carry out the purchase itself. At Repeatable Read or Serializable, be prepared for an abort and a fresh transaction instead of assuming a later statement refreshes visibility. These are possible branches, not a claim about a particular server’s timing.

The purchase branch

Once the attempt owns the key, it performs the complete atomic purchase. The following outline shows where each decision belongs. The order number 103 is the result allocated in this example, not a caller-chosen replacement for the request key.

  1. Claim the key. If it already exists, compare its payload, finish the read transaction and return its terminal result. Reject a mismatch.
  2. For a new key, establish a savepoint after the claim. Apply the guarded stock changes, checking that each returns one row.
  3. If stock is insufficient, roll back to that savepoint, removing every purchase change while keeping the claim. Store the refusal in the request row.
  4. Otherwise create order 103 and its two order lines, then store the accepted result in the request row.
  5. Commit. Return the terminal answer only after commit is confirmed. If confirmation is lost, recover using this same key and payload.

For the fixed basket, the guarded stock statements are below. Stop at the first statement that returns no row. The savepoint lets the service undo an earlier tea decrement before recording a mug refusal; simply committing a refusal after a partial decrement would break the purchase.

SAVEPOINT purchase_work;

UPDATE products SET stock = stock - 2
WHERE product_id = 'P3' AND stock >= 2
RETURNING stock;

UPDATE products SET stock = stock - 1
WHERE product_id = 'P7' AND stock >= 1
RETURNING stock;

On success the attempt inserts the pending order, P7 on line 1 at 20.00 and P3 on line 2 at 4.50, then records the answer before committing:

UPDATE purchase_requests
SET result = '{"outcome":"accepted", "order_id":103,
  "status_at_creation":"pending", "total":"29.00"}'::jsonb
WHERE customer_id = 1 AND request_key = 'purchase-103';

COMMIT;

On refusal it executes ROLLBACK TO SAVEPOINT purchase_work, stores outcome: refused with reason: insufficient_stock in the result and commits. An unexpected SQL error instead ends the attempt by rolling the entire transaction back. Database retry logic must not catch such an error and commit an unfinished request row.

Recover the recorded result

Now let the successful commit reply disappear. The application knows the key and payload but does not know whether they committed. It starts another attempt of the same protocol. If the original transaction is still running, the unique key coordinates with it. If it committed, the duplicate branch returns accepted order 103; stock stays P3 = 10 and P7 = 0. If it aborted, the new attempt can claim the key and try the purchase.

Losing the application’s reply works the same way. Mina’s caller sends purchase-103 again and receives order 103. The key must survive at the caller too: generating a new token after every timeout makes each recovery look like an intentional new purchase.

Use the database authority that accepts the key, with a current view, for recovery. A lagging replica or an old snapshot may say “absent” after the purchase committed. Even a fresh absence read is only an observation: another attempt could still be running. Re-entering the unique-key protocol resolves ownership without treating that absence as permission to bypass it.

The retained answer describes what the original request achieved. If order 103 is later cancelled or paid, that does not rewrite “created pending for 29.00”. Recover the creation result first; read the order’s current state through the ordinary order query when that is what the caller needs.

Choosing what to retry

The outcome determines the next action. “Something went wrong” is too broad a retry condition.

Four outcomes for one logical request
EvidenceNext action
Known retryable abortEnd the failed transaction. Retry the entire transaction and its decision logic with the same request key.
Committed business resultReturn the retained acceptance or refusal. A deliberate new purchase needs a new key.
Persistent error or payload mismatchStop and correct the request or application. Repetition alone cannot fix it.
Uncertain commit or missing caller replyRecover through the protected protocol with the same key and payload.

In PostgreSQL, 40001 identifies a serialization failure. A deadlock abort, 40P01, can also merit a complete retry, alongside fixing recurring lock-order problems. A uniqueness error may instead mean permanently invalid data; do not retry every constraint violation. In this protocol an existing request key is an expected duplicate branch, with a payload comparison, rather than a reason to submit a new purchase.

Bound both the number of attempts and the elapsed time. Between retryable failures, use backoff with jitter, a random variation in the delay, so competing callers do not all return together. Put responsibility for retries at a deliberate layer: retries in a caller, driver and service can otherwise multiply the work during an outage.

Exhausting the caller’s budget ends its wait, not the uncertainty. Preserve the key and offer a way to recover later, using a subsequent request or a status lookup that returns a retained result or says it is still unresolved. Do not label an unresolved purchase “failed”, invite a new key or promise that cancellation undid it merely because the timer expired.

The limits of duplicate protection

The guarantee lasts as long as the service retains enough history to recognise the key and its meaning. Delete the request row and a late repeat can claim the key again. Agree the caller’s retry window with the retention policy, and define how expired requests are refused or reconciled. Keeping a small tombstone can preserve rejection of old keys, but a payload hash alone cannot recover the original answer.

One key, one payload comparison, one atomic commit and a retained result protect this database operation. They do not make an email or payment-provider call part of the database transaction. Calling a provider inside a transaction that may be replayed can repeat the external effect even when every database attempt is correct. Outboxes and database-backed jobs develops durable external intentions and worker recovery. CockroachDB transactions and retries applies the same logical identity to its native retry and ambiguous-result paths.

Sources and further reading

The shop histories and attempt schedules are conceptual examples. Sequential SQL was checked in PGlite 0.5.8, PostgreSQL 18.3 compiled to WebAssembly. The two request-key wait branches were also checked on an owned Linux PostgreSQL 18.6 server. These checks do not simulate losing a real network reply.