A retry should recover the order, not create a second one. The difficult case is not a double-click before processing starts. It is a timeout after the order system has committed, while the integration still has no result to show the buyer.
For an integration engineer, the task is to connect four things: a durable identity for the purchase intent, the receiving API’s retry contract, evidence of downstream effects, and a recovery path when that evidence is incomplete. An idempotency key helps with one part of that task. It is not a permanent, end-to-end “exactly once” guarantee.
Use this guide to specify an order API contract and build a failure-focused acceptance set. The examples are synthetic and were not executed: design examples, not production-ready code, live test results, or claims about a Dinarys deployment.
What is idempotency in a REST API?
Idempotency means repeating an operation has the same intended effect as performing it once. For HTTP, RFC 9110, Section 9.2.2 defines this property for the intended effect on the server—not for identical response bytes or the absence of every incidental side effect.
PUT, DELETE, and safe methods such as GET are idempotent under the RFC’s semantics. A repeated DELETE can legitimately return a different status after the resource is gone. Request logs can grow on every attempt. Neither fact alone disproves method idempotence.
Conceptual distinctions, not a permanent cross-system exactly-once guarantee or a substitute for the receiver’s contract.
POST /orders is not idempotent merely because it uses REST or carries a header named Idempotency-Key. The receiving application must implement and document the behavior. Renaming an unsafe “create another order” action to PUT does not establish a reliable contract either.
Keep these layers separate:
Layer
What it identifies or controls
What it does not establish
HTTP method idempotence
The intended effect of repeating the same method/request
Identical status codes, response bodies, or a cross-system transaction
Provider idempotency-key facility
Repeated requests within that provider’s documented scope and retention window
Duplicate intents sent under different keys, or protection after pruning
Message/event deduplication
Redelivery of an identified message to a particular consumer
Whether two different messages request the same business action
Business-operation identity
One accepted intent, such as submitting checkout confirmation op-41
That every external effect and local record committed atomically
End-to-end acceptance
Observable orders, reservations, payments, and fulfillment work across the agreed flow
A universal guarantee beyond the tested scope and recovery assumptions
1. Define the operation before generating its key
An idempotency key is a token the receiver uses to recognize a repeated request. A business-operation ID answers a different question: is this the same purchase intent, even if another browser session, worker, import, or support agent submits it?
For a checkout submission, define an identity such as (tenant, accepted checkout confirmation ID, create-order). Persist it before the first outbound attempt. Bind it to the authorized buyer/account and the accepted order revision. An attempt gets its own trace ID; a retry retains the operation identity and the key assigned to that target operation.
Do not use “same customer plus same products” as the identity. A customer can intentionally buy the same items twice. Likewise, a reusable cart ID alone may outlive one purchase: distinguish a retry of its submitted confirmation from a new confirmation or reorder.
Document three decisions:
Same intent, same accepted body: recover or replay the existing operation.
Same identity, changed body: stop and surface a conflict; do not silently overwrite quantities, delivery details, price, or currency. A correction needs an explicit policy and knowledge of the first operation’s outcome.
Genuinely new intent, identical products: create a new operation identity and appropriate new target keys.
A payload fingerprint can detect a changed request. It cannot decide customer intent. If you use one, version the normalization rules and define the significant fields; a raw JSON hash can treat harmless serialization changes as different bodies. Keep the accepted payload or a protected reference to it so the decision can be explained.
Namespace both business records and target keys deliberately. Include the tenant, environment, destination account, target action, and contract version where relevant. Authenticate and authorize access before returning an existing operation’s result. Knowing a key or operation ID must not expose another customer’s order.
2. Read the receiving API’s actual retry contract
Do not copy one provider’s numbers into your order API specification. Record the endpoint/version, key placement and length, account scope, parameter comparison, concurrent-request behavior, retention, cached errors, and lookup/recovery options.
Stripe is a bounded example—not a generic order API
All POST requests accept keys; keys can be up to 255 characters. Stripe recommends sufficiently unique tokens and avoiding sensitive data in them.
Once endpoint execution begins, Stripe saves the first status and body, including 500 responses. Same-key retries return that saved response while retained.
Parameters are compared with the original request; mismatches error. Validation failures and conflicts with a concurrently executing request do not save an idempotent result when execution has not begun.
Keys are retained for at least 24 hours and can be pruned afterward. Reusing a pruned key can execute a new request.
For a same-key 409 caused by an in-progress request, the guidance is to wait and retry with the same key and parameters—not start another operation under a new key.
Stripe’s API v1 guidance limits unresolved retries to the first 24 hours after the original request. If the outcome remains unknown afterward, reconcile it rather than retry with either the old key or a new one. A 500 is also indeterminate: side effects may have occurred, and replaying a cached error does not resolve that uncertainty.
Those are API v1 rules. Stripe API v2 documents a 30-day replay window scoped to the same API and account or sandbox, with different recovery/replay behavior, including updated responses. “Stripe always caches the first error forever” is therefore wrong on both version and duration.
For an order-specific contrast, Square CreateOrder, API version 2026-09-16, uses a body field named idempotency_key, with a maximum length of 192. It documents retrying an uncertain create with the same key without creating duplicate orders. The reference read for this guide does not specify a retention duration or complete concurrency/error-replay policy; those remain contract questions here. Stripe’s 24-hour guidance does not fill those gaps.
Write the stop condition as well as the retry condition
For your target API, specify a bounded retry policy with backoff, an attempt budget, and a deadline inside its documented protection window. Account for retries in SDKs, proxies, queues, and operator tooling so they do not independently generate new operations.
Classify outcomes by evidence, not status code alone:
Evidence
Next action to specify
Documented rejection before execution, with no effect possible
Correct the request under the API’s documented rules; record its relationship to the original intent
Same operation still executing
Wait or inspect documented operation status; retain its identity
Timeout, connection loss, or error with possible effects
Treat outcome as unknown; use only a documented protected retry or authoritative recovery path
Protection window ended, or replay behavior unknown
Hold automatic creation and reconcile; an old token is not evidence of protection
Confirmed resource/effect
Attach its authoritative ID and continue only the remaining steps
An unknown order outcome is not permission to place another order. An unknown payment outcome is not permission to create a new charge. Changing the key does not turn uncertainty into a clean failure.
3. Keep an operation ledger—but expose its transaction boundary
An operation ledger is a durable record for explaining attempts and recovery. The following fields are a design-review template, not a complete state machine or a proven execution algorithm.
Record
Minimum useful content
Operation identity
Tenant, environment, account/buyer binding, source confirmation ID, action, contract version
Accepted request
Revision, significant-field fingerprint and its version, protected payload reference
Target attempts
Destination/account/action, stable target key, attempt IDs, first-send time, retry deadline, last response/error
Evidence
Commerce order ID, external order ID, relevant payment/reservation IDs, lookup source and time
Recovery
pending, unknown, confirmed, or rejected evidence label; unresolved steps, owner, next permitted action and review time
Audit
Event receipts and processing outcomes, manual actions, reconciliation decisions and their reasons
Design-review categories from synthetic, not-executed examples; neither a ledger row nor a lock proves the external effect’s outcome.
Use a separate target-operation identity/key for each distinct action: creating an ERP order is not capturing a payment. Track partial completion rather than marking the entire flow “done” because the order API returned success.
Within a database you control, a unique constraint and transaction can coordinate admission of the same operation across workers, bind its payload, and record local changes together. A “check then insert” in application code alone leaves a race. Even a correctly transactional local record does not atomically commit an external order, payment, or warehouse action.
The critical gap is: external effect commits → process crashes → local success record never commits. A worker lock, a lease timeout, or an in_progress row cannot tell the next worker whether the effect happened. Marking a message processed before the effect risks missing work; marking it afterward leaves a replay gap. Neither ordering alone solves the external-effect problem.
Recovery needs a target capability you have actually verified: for example, same-key replay while protected, or a durable unique external business reference with an authoritative lookup. A reference echoed in metadata is useful correlation, but is not necessarily unique or enforced. A search that currently returns no results may also be insufficient if indexing is delayed or another request is still running. If the target offers no reliable way to resolve the ambiguity, hold the operation for investigation instead of inventing certainty.
4. Walk through a timeout after commit
Synthetic sequence, not executed. Assume a fictional target called Order System X. For this example only, its contract protects same-key creates for 10 minutes and enforces a durable unique (tenant, external business reference) with authoritative lookup. These are stipulated example capabilities, not Stripe, Square, or arbitrary ERP behavior.
Tenant T-A submits accepted confirmation op-41, body revision r1, fingerprint label fp-A. The labels below are illustrative, not real hash values or credentials. The integration maps its ingress key k-A to target create key x-A; these keys serve different receiving systems.
Step
Attempt or failure
Ledger evidence and expected handling—not an observed result
1
Two workers receive op-41, k-A, r1 concurrently
Transactional local admission binds one operation to r1. The second worker observes its existing record; it does not independently start another target create.
2
The active worker sends target key x-A, reference T-A/op-41/create
Record the attempt and its protection deadline. X commits external order X-501, but the response is lost.
3
The worker crashes before recording X-501
Local evidence remains unresolved. On recovery, pending is not evidence that X did nothing; classify the stale attempt as unknown for investigation.
4
Recovery runs inside X’s 10-minute window
Use X’s documented same-key replay or its authoritative reference lookup. In this stipulated sequence, lookup confirms X-501; record that ID and evidence. Resume only unfinished work.
5
The client sends k-A with changed revision r2
Reject the identity/body conflict without overwriting r1 or creating an extra order. Changing shipping or quantity needs an explicit amendment/new-intent decision.
6
A client restart sends a new key k-B but still op-41
The business-operation identity leads to the same ledger record. A new transport key must not bypass that boundary.
7
The buyer intentionally confirms op-42 with identical products
This is a separate accepted intent with new target-operation identity/key. It must not be suppressed just because its product fingerprint resembles op-41.
8
Recovery instead begins after X prunes x-A
Do not submit a fresh create based on key memory alone. Use the stipulated durable reference/lookup to resolve X-501; if authoritative evidence is unavailable, keep the operation on hold.
Counterexample: a ledger plus keys can still produce duplicates
Remove X’s enforced unique reference and authoritative lookup. Keep only its 10-minute key cache. After step 3, recovery starts after pruning and blindly sends x-A again. X can create X-502 for the same intent, even though the integration still has just one locally unique op-41 row. Sending a fresh key can cause the same problem before pruning.
Conversely, treating every stale local attempt as completed can leave a missing order when the original request never reached X. The local row alone distinguishes neither history. In this reduced contract, the safe handling of that ambiguity is a hold with an accountable recovery path, not a claim that a few pseudo-steps prove exactly-once execution.
5. Deduplicate events without losing real changes
Request retries and message redelivery are separate paths. Stripe’s webhook documentation says the same event can arrive more than once, and separate Event objects can sometimes represent duplicates. It also states that delivery order is not guaranteed. Its event-ID advice is provider-specific evidence, not a universal event schema.
For your consumer, document the provider/account/environment/consumer namespace for receipt deduplication. Where supported, verify event signatures using the provider’s requirements before accepting the event. Durably accept work before acknowledging successful receipt; acknowledgment is not evidence that all business effects have finished.
A repeated event ID should not repeat the action. But different event IDs can still trigger the same downstream order-creation intent, so connect them to the business operation as well. Do not permanently suppress every event with the same object ID and type: repeated legitimate updates may need processing. Define event semantics and the target action before choosing that rule.
Section 6 gives a replay test for an older status event arriving after a newer one. Stripe specifically warns against using snapshot-event created timestamps as an ordering or dedupe mechanism because distinct events can share a timestamp.
6. Duplicates are only one failure: handle out-of-order and missing events too
A webhook consumer that ignores repeated event IDs can still end with the wrong order. Two other failures need their own rules: an older event arriving after a newer one, and an event that never arrives. Shopify’s webhook documentation states that it doesn’t guarantee ordering within a topic, or across different topics for the same resource; that webhook delivery isn’t always guaranteed; and it recommends reconciliation jobs that periodically fetch data from Shopify. Its headers, such as X-Shopify-Webhook-Id for duplicate deliveries and X-Shopify-Triggered-At, are Shopify’s own—do not assume another platform sends the same fields or semantics.
Synthetic, not-executed timelines for one order: in-order, duplicated, reversed and missing events must all end with the same final state as the source system.
Write the rules for each event-driven flow as a replay and reconciliation matrix:
Element
What to record
Rule to specify
Event identifier
The provider’s event ID, in its provider/account/environment/consumer namespace
A repeated ID is recorded as a receipt but does not repeat the business action
Delivery identifier
The delivery or attempt ID, where the provider distinguishes it from the event
Retries of one event are traced to that event, not treated as new changes
Business key
The order or operation reference the event changes
Different events for the same business action reach the same ledger record
Version or timestamp rule
The resource version, sequence or documented ordering field; otherwise none
Never roll a status back to an older version, but keep facts the stored state lacks, confirmed by an authoritative fetch; if no reliable ordering field exists, fetch authoritative state instead of trusting arrival order
Retry
Processing attempts, last error and next attempt time
Processing is safe to repeat; a temporary failure is retried within the documented window
Dead-letter handling
Events that keep failing, with the reason
Moved to an owned queue with an alert, never silently dropped
Periodic source reconciliation
Cadence, time window and the source queried
Compare final business orders with the source and record every correction
Owner
The person or team for each queue and discrepancy
Named before go-live, with a review cadence
A pass/fail replay test
Record one synthetic event sequence for a test order—created, paid, shipped—in an authorized test environment, then replay it four ways: in order; with the payment event duplicated; with shipped delivered before paid; and with the payment event removed, followed by a reconciliation run.
Run
Pass if
Fail if
Normal
One order, one payment, final state matches the source
Any extra resource or effect
Duplicate
The repeat is recorded as a receipt; no second payment, reservation or shipment
Any repeated business effect
Reversed
The status is not rolled back; any fact missing from the stored state, such as the payment record, is taken from an authoritative fetch; one payment is recorded
The order regresses to an older status, or the late payment record is lost
Missing, then reconciled
Reconciliation detects the gap within the agreed cadence, applies the source state and records the correction with its owner
The gap is found only by a customer or a support ticket
In every run, judge the result by the final business order compared with the source system—not by a successful webhook HTTP response. A 200 proves receipt, not that the order is right.
7. Use the duplicate-order acceptance checklist
For every scenario, collect both request evidence and business-effect evidence. “Received one 200” is not enough. Compare operation records with actual target orders and any in-scope reservations, payments, fulfillment jobs, and manual work. Record pending or unknown effects rather than hiding them in a successful request count.
Scenario
Acceptance evidence to request
Same key/body, sequential retries and process restart
Same operation/resource association; target key survives restart; no additional unintended effect
Concurrent same key/body
Documented in-progress/conflict/replay behavior; race-controlled local admission; downstream effects counted
Same key, changed body
Conflict evidence; original payload/result unchanged; no silent new create
Different keys, same intent
Business-operation boundary still identifies the existing operation
Identical products, legitimate second confirmation
Separate intended operation completes; no false deduplication
Timeout after target commit
Resource recovered through documented evidence; no blind replacement create
Crash after external effect, before ledger update
Unknown outcome exposed; safe recovery or hold demonstrated at the actual boundary
Key expiry/pruning and late replay
Expired protection not assumed; reconciliation path exercised
Duplicate event/message
Receipt and business-action controls prevent repeated effects; processing remains recoverable
Out-of-order or distinct related events
Valid later changes retained; stale state does not overwrite newer authoritative state
Same token/ID in another tenant, account, or environment
No cross-namespace collision or result disclosure; correct account routing
Manual entry or batch import during API recovery
Shared intent reference and operator coordination, or explicit exception handling if a channel cannot participate
Missing event that is never delivered
Periodic source reconciliation detects and applies the change; the correction is recorded with its owner
Partial completion or missing/extra target resource
Reconciliation identifies the discrepancy, its owner, permitted action, and closure evidence
Use this table as your acceptance checklist. For each scenario, record the target contract details, where the evidence is kept, and the actual outcome. Treat a scenario as open until an authorized test environment has produced that evidence, and do not paste production customer data or credentials into your test records.
Reconciliation must include channels that bypass the API
A support agent who manually enters an order while an API request is unresolved can duplicate the purchase without repeating any API key. Give operations visibility into the shared business reference and unresolved status. If the manual channel cannot enforce that reference, document its coordination procedure and remaining duplicate risk; do not describe the whole flow as protected.
Assign a reconciliation owner and review cadence for aged unknown operations, confirmed operations missing a target resource, extra target resources, and partially completed flows. Establish which system is authoritative for each effect and what constitutes conclusive absence—not simply “not found in one log.” Record manual decisions before restarting automation. Cancellation or compensation requires its own authorized business process; it is not an automatic consequence of detecting a possible duplicate.
Start with the contract, then prove the recovery path
Use the checklist with the commerce owner, target-system owner, and operations team. First test whether the existing connector’s documented behavior covers these failure cases. A supported connector repair may be sufficient; a custom integration is not automatically the next step.
If the gap spans commerce and ERP order handling, Dinarys’ existing ERP integration services is a relevant route for discussing that specific scope. The published SanMar integration case describes integrating Magento with the client's existing ERP system through a custom API connector; it does not establish that the ledger or tests in this article were implemented there.
The useful acceptance question is not “Do we send idempotency keys?” It is: After a retry, a crash, or a manual intervention, can we explain which business operation happened, which effects remain unknown, and who can safely resolve them?
You may share this article
Lassen Sie Profis Ihre Herausforderung meistern
Unsere zertifizierten Spezialisten finden die optimale Lösung für Ihr Unternehmen.