At a glance
The demo succeeds once. The production problem begins when it succeeds and nobody receives the answer. Follow one export through a lost response, a repeated request and a concurrent duplicate, then break a small implementation yourself.
- Give each intended operation a stable identity; equal payloads do not necessarily mean equal intent.
- Commit the receipt, business mutation and durable work together, then recover that receipt on retries.
- Test failure at the commit boundary and treat worker or provider effects as separate retry contracts.
Start with the moment the user cannot see
The most revealing production test can look like nothing happened. A customer clicks Export. The server accepts the work. The connection disappears before the response arrives. The customer waits, then clicks again. This is where the software either preserves their intent or makes them pay for its uncertainty.
Use the export product from the architecture field guide: one accepted export consumes one credit and creates one durable job for an immutable dataset snapshot. We will make admission safe to repeat. Rendering and artifact publication happen later. This is one deep slice of production readiness; it does not establish deployment safety, backup recovery or authorization for a complete product.
Write the promise before the handler: for the same authorized tenant, operation and request key, the same validated payload recovers one accepted job; a different payload is rejected. A fresh key means a new intentional export, even if its parameters happen to match.
Define identity, intent and the response you will remember
The client creates a request key before the first attempt and retains it through timeouts and retries. The server derives the tenant from authenticated context and checks permission before returning a stored receipt. Scope uniqueness to (tenant, operation, key). A key is a deduplication identity, never a substitute for authorization.
Normalize validated intent before hashing it. Here that means exactly two string fields: dataset_version and format. The dataset version identifies an immutable, retained input; “latest” would allow the same request to mean different work tomorrow. Apply defaults before serialization and exclude transport noise such as trace IDs. Do not assume generic JSON hashing defines semantic equality for arbitrary numbers, Unicode or unordered collections.
Our authored API contract returns a stored 202 receipt with a job ID and stable status URL. Every accepted duplicate returns that receipt; a separate GET reports current progress. Same key with different normalized input returns 409. Invalid input never claims the key. This follows the distinction between caller intent and merely similar requests explored in the Amazon Builders’ Library on idempotent APIs.
Publish the identity retention window. Keep it longer than the supported offline/retry horizon and retain active job identities. After deleting a key, a late retry can become new work. A retained tombstone or a contract for rejecting expired tokens can preserve the distinction; silently shortening retention changes the promise.
Decide how long the server remembers a key. A client that retries for 24 hours needs a receipt that lives longer than 24 hours. If a key expires after one hour and a phone retries after two, the second attempt is a new order.
Then price the failure you prevent. At 20,000 exports a month and one lost response in 500, 40 customers a month click again. Without the key, each of them pays twice, or support refunds each one by hand.
Put the promise on the same side of the commit
A lost response does not tell you whether the work exists.
↔ Scroll across diagrams and tables to inspect the detail.
Cut A: restart sees no accepted request, debit, job or dispatch intent. Retrying can perform admission.
Cut B: restart sees all four. Retrying must recover that exact receipt. If the database connection fails during commit, the caller must also treat the outcome as unknown.
Inspect nodeClaim or find K⌄
The unique tenant, operation and key identify the receipt. A concurrent insert may wait for the first transaction. A bounded wait can end in a retry with the same K.
A cache entry saying “seen” is insufficient if the business write can commit separately. Crash between them and either the request disappears without its job or the retry creates another job. Put request identity, receipt, conditional quota debit, job and outbox in one transaction.
The admission algorithm below is PostgreSQL-oriented pseudocode, with branching performed by the application. It assumes retained ledger rows and Read Committed isolation:
authorize tenant and snapshot; validate and normalize input
BEGIN
INSERT request(key scope, payload_hash, proposed_receipt)
ON CONFLICT (tenant, operation, key) DO NOTHING
RETURNING key
if no row inserted:
SELECT payload_hash, receipt FROM request WHERE key scope matches
if hash differs: ROLLBACK; return 409
COMMIT; return stored receipt
UPDATE quota SET remaining = remaining - 1
WHERE tenant matches AND remaining > 0
if affected rows != 1: ROLLBACK; return quota rejection
INSERT job(immutable input reference)
INSERT outbox(stable event ID, job ID)
COMMIT
return proposed receipt
The unique constraint chooses the winner under contention. A competing insert can wait on an uncommitted conflicting row. With ON CONFLICT DO NOTHING, a conflict can involve a row invisible to that statement’s snapshot; issue the duplicate SELECT as a subsequent statement with its new Read Committed snapshot. Do not collapse both into a single snapshot query and assume the competing row will be visible. See PostgreSQL’s documented isolation behavior and INSERT conflict handling.
Bound database waits. A wait limit or retryable database failure rolls back the attempt; return a documented retryable response and keep the client’s original key. If commit acknowledgement is lost, the outcome is unknown: reconnect and recover through that same identity. Keep external calls outside this transaction.
Break the implementation where its promise lives
Test the durable state, not just the HTTP response.
↔ Scroll across diagrams and tables to inspect the detail.
| Injected case | Before recovery | Required result |
|---|---|---|
| Crash after request insert | 0 / 0 / 0 / 10 | Retry creates 1 / 1 / 1 / 9. |
| Crash after quota debit | 0 / 0 / 0 / 10 | Uncommitted debit rolls back; retry creates one job. |
| Crash after job insert | 0 / 0 / 0 / 10 | No job survives without its dispatch intent. |
| Crash immediately before commit | 0 / 0 / 0 / 10 | All four writes roll back together. |
| Crash after commit, before reply | 1 / 1 / 1 / 9 | Retry returns the original receipt; state unchanged. |
| 8 callers, same key + payload | Concurrent submissions | One receipt, one job and one debit. |
| Same key, changed snapshot | Prior request committed | Payload mismatch; no state change. |
| Same key, different tenant | Separate authorized namespaces | Independent job and quota; no receipt collision. |
| Same payload, new key | New caller intent | Another job and debit, deliberately. |
| No remaining credits | 0 / 0 / 0 / 0 | Reject admission; leave no partial records. |
Download the executable retry lab (.py) · Python standard library · temporary local files · no network
Inspect nodeTen-credit fixture⌄
Each crash case starts in a temporary database with ten credits. Reconnect after the child process terminates and count committed rows before retrying.
- Stop after the first write → After request insert
- Stop with an uncommitted debit → After quota debit
- Stop with an uncommitted job → After job insert
- Stop after staging the outbox → Immediately before commit
- Stop after durable acceptance → After commit, before reply
- Submit matching intents together → Eight equal callers
- Resubmit a changed snapshot → Same key, new snapshot
- Change the tenant namespace → Same key, different tenant
- Express another intent → Same input, new key
- Set initial credit to zero → Exhausted balance
Download the self-contained Python lab, inspect it and run it locally:
python3 retry-lab.py
It creates temporary SQLite databases, kills child processes at five precise points, reconnects, inspects durable state and retries. It also submits eight competing calls and tests changed intent, tenant namespaces, a new request key and exhausted quota. The matrix records the ten passing cases.
The implementation uses BEGIN IMMEDIATE to serialize writers before checking the ledger. That makes its query-before-insert safe within this model. PostgreSQL allows concurrent writers and needs the unique-claim path above; copying the SQLite handler without its transaction semantics would change the guarantee. SQLite’s transaction documentation explains its single-writer behavior.
Use the lab as a fault map for your actual adapter. Replace its admission function with your database implementation and retain the outcome assertions. Add your engine’s lock-timeout, disconnect-during-commit and failover cases. Eight SQLite callers establish a property of this fixture, not throughput or correctness under your database’s isolation rules.
The accepted job is only the next boundary
An outbox closes the gap between committing a job and remembering to dispatch it. It does not make dispatch unique. A relay can publish, crash before recording success and publish again. The outbox pattern’s documented duplicate-delivery case is exactly why the worker needs its own policy.
| Failure | Recovery rule | Assertion |
|---|---|---|
| Same job delivered twice | Claim or inspect the durable job; completed work is acknowledged. | No second published completion. |
| Lease expires during a slow render | New claimant increments generation; completion must match the current generation. | Late worker cannot overwrite the winner. |
| Object saved; worker dies before completion | Use immutable attempt objects and a guarded database pointer; sweep orphans. | Visible job points to one completed artifact. |
| Paid provider times out after accepting work | Retry using provider-supported identity, or query/reconcile an unknown outcome. | Never infer “no effect” from a timeout. |
Inspect nodeInspect the durable job⌄
Look up the authoritative job ID before rendering. A completed job can be acknowledged immediately. New work requires an eligible claim.
A lease limits who should work; a generation check limits who may publish. Neither can undo an external charge. If the provider offers no deduplication or lookup, park ambiguous work for reconciliation and make that state visible. Calling the pipeline “exactly once” would erase the hardest part of the contract.
Let the operator recover the same intention
Expose accepted, running, succeeded, failed and needs-reconciliation states with the job ID. Record request identity, job identity, attempt and claim generation in structured operational events, without logging sensitive payloads. Watch age of the oldest undispatched or unfinished job as well as error counts: silent stalled work can produce no new errors.
Give transient retries a bounded budget with backoff and jitter, and designate one layer to own that budget; several retrying layers multiply attempts. Authentication, payload mismatch and exhausted quota require a different action from a temporary unavailable dependency. The Builders’ Library on timeouts and retries explains why repeated load can worsen an overloaded system.
Before rollout, have a second engineer recover a failed job using the recorded identity. They should preserve the original request and inspect ambiguous side effects before replaying. There is a quiet satisfaction in getting this right: someone returns after an interruption and their work is still there, with one clear history. You have made their uncertainty smaller.