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

FIG. 01 / Crash map · export admission · time runs down

A lost response does not tell you whether the work exists.

↔ Scroll across diagrams and tables to inspect the detail.

A retry recovers an export receipt after a post-commit response loss A client submits request K. The API writes the request receipt, quota debit, export job and outbox inside one transaction. Crashes before commit leave none of these changes. After commit all exist even if the response is lost. A retry with the same key and payload reads and returns the stored receipt with no new debit. A concurrent duplicate waits for the first transaction or receives a retryable wait-limit response. CLIENTAPIDATABASE POST · key K · snapshot 7 ONE TRANSACTION claim request identity + receipt debit quota; create job + outbox A · before commit COMMIT All writes durable together, or none on rollback. commit acknowledged B · receipt lostThe job exists. The client is unsure. retry · same K + payload load committed receipt same 202 + job ID · no additional debit CONCURRENT K: wait for the winner; compare payload; replay its receipt. Never execute twice.

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.

The commit is the point where server state changes together. The client learns that fact later, if its response arrives. This diagram models admission only; rendering and external side effects cross further failure boundaries.
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.

Explore diagram10 nodes · 12 connectionsMermaid

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

FIG. 02 / Executable evidence · local SQLite teaching lab

Test the durable state, not just the HTTP response.

↔ Scroll across diagrams and tables to inspect the detail.

Fixture: 10 initial credits; tuples are requests / jobs / outbox / remaining credits
Injected caseBefore recoveryRequired result
Crash after request insert0 / 0 / 0 / 10Retry creates 1 / 1 / 1 / 9.
Crash after quota debit0 / 0 / 0 / 10Uncommitted debit rolls back; retry creates one job.
Crash after job insert0 / 0 / 0 / 10No job survives without its dispatch intent.
Crash immediately before commit0 / 0 / 0 / 10All four writes roll back together.
Crash after commit, before reply1 / 1 / 1 / 9Retry returns the original receipt; state unchanged.
8 callers, same key + payloadConcurrent submissionsOne receipt, one job and one debit.
Same key, changed snapshotPrior request committedPayload mismatch; no state change.
Same key, different tenantSeparate authorized namespacesIndependent job and quota; no receipt collision.
Same payload, new keyNew caller intentAnother job and debit, deliberately.
No remaining credits0 / 0 / 0 / 0Reject admission; leave no partial records.

Download the executable retry lab (.py) · Python standard library · temporary local files · no network

These ten cases passed in the supplied lab. Crash cases terminate a subprocess without graceful rollback; concurrency uses eight callers. SQLite serializes writers, so this is evidence for this teaching implementation—not PostgreSQL concurrency, power-loss durability, tenant authorization or a production worker.
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.

Explore diagram14 nodes · 22 connectionsMermaid

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.

Required worker tests · design cases, not executed by the admission lab
FailureRecovery ruleAssertion
Same job delivered twiceClaim or inspect the durable job; completed work is acknowledged.No second published completion.
Lease expires during a slow renderNew claimant increments generation; completion must match the current generation.Late worker cannot overwrite the winner.
Object saved; worker dies before completionUse immutable attempt objects and a guarded database pointer; sweep orphans.Visible job points to one completed artifact.
Paid provider times out after accepting workRetry 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.

Explore diagram10 nodes · 11 connectionsMermaid

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.

ABOUT THEBSQ

thebsq builds and operates software and connected hardware. Our engineers use market evidence to set the brief and direct AI agents to test designs and trace faults in production.

Explore our work