An integration worker submits an approved voucher, sales order, or cash receipt to an ERP over HTTP POST. The ERP commits the entry, then the socket drops—or a proxy returns 500 before the response returns. An automatic retry sends the POST again and creates a second posted document.
Idempotent ERP posting on retries protects a different layer than accounts payable checks. Duplicate supplier invoice detection catches separate vendor bills for the same charge, and a dead-letter queue for failed ERP imports holds exhausted messages for operator redrive. Idempotent posting guards the write boundary so one transaction posts at most once across timeouts, 5xx errors, worker crashes, and replays.
Using Stripe’s API and webhook documentation as a third-party reference (not an Insonl client), this guide covers recording a durable posting key, reconciling ambiguous responses before replay, handling webhook redeliveries, and keeping AI out of the write path.
Why retries double-post after an ambiguous response
On Stripe API v1, GET and DELETE are idempotent by definition, whereas POST creates a new resource unless the server recognizes a repeated key (Idempotent requests). ERP writes—journal entries, vendor bills, goods receipts, and payments—usually use POST, and many ERP APIs omit server-side Idempotency-Key support or expire keys before an incident clears.
Stripe’s Advanced error handling groups HTTP failures into three classes:
- Content errors (
4xx). Invalid fields, bad credentials, rate limits, or concurrency conflicts (409). On Stripe API v1, pre-execution errors (invalid parameters, invalid API key, rate limiting) are not cached and can be retried once fixed; errors after execution begins (such as a cached400) are stored against the key. - Network errors. Socket errors and timeouts where the connection closes before a response arrives. Restoring connectivity does not show whether the server committed the write.
- Server errors (
5xx). A500response is indeterminate: the operation may have produced side effects even though it returned an error.
Double posting occurs when retry logic treats a timeout or 500 as a clean failure and sends another POST—especially if the worker generates a fresh key per attempt.
Record a durable posting key before calling the ERP
Before the first outbound POST, insert a posting-intent row in your integration database with a unique constraint on posting_key. Store source_entity_id, operation_type, payload_hash, state, erp_document_id, attempt_count, and first_attempted_at.
Four rules keep that key reliable across restarts and outages:
- Persist the key across worker runs. In-memory keys protect only one process attempt. Retries across separate calls or restarts must persist one key per operation and reuse it on every attempt (Advanced error handling).
- Keep keys unique, bounded, and non-sensitive. Stripe suggests a random token (such as UUID v4) or a key derived from an attached object (such as a cart or order ID), caps keys at
255characters, and warns against sensitive data like email addresses or personal identifiers (Idempotent requests; Advanced error handling). - Bind parameters to the key. Stripe compares incoming parameters against the original request and errors on mismatch. Enforce the same rule locally with
payload_hashso edited amounts or account codes cannot reuse an unresolved key. - Write the local key into the ERP record. Stripe advises storing a local identifier in resource metadata so objects discovered later via API lookup or webhooks match local records (Advanced error handling). When an ERP lacks
Idempotency-Key, writeposting_keyto an indexed external-reference field and enforce ERP-side uniqueness where supported.
Account for server key-retention limits. Stripe API v1 retains keys for at least 24 hours and can prune them afterward; reusing a pruned key runs a new request (Idempotent requests). API v2 extends retention to 30 days within the same API and account or sandbox and accepts keys on POST and DELETE (API v2 overview). If a dead-letter queue backlog outlasts server retention, only your local ledger and pre-replay lookup stop a duplicate.
Reconcile ambiguous responses before replaying a transaction
Replace blanket retry loops with an explicit response table:
| ERP outcome | What you know | Worker action |
|---|---|---|
2xx (or Idempotent-Replayed: true) |
Write committed | Save erp_document_id, mark POSTED, stop. |
Pre-execution 4xx (401, 429, uncached validation error) |
Write did not start | Fix auth/config or back off; retry with the same key. |
409 concurrency conflict |
Original request still running | Back off and retry with the same key and payload; do not mint a new key. |
Execution-stage 4xx (e.g., cached 400) |
Failed after execution began | Confirm original attempt did not commit before abandoning the key for edited fields. |
| Network timeout / socket drop | Outcome unknown | Retry with the same key only inside a native ERP retention window; otherwise set RECONCILE_REQUIRED. |
500 / 5xx server error |
Outcome indeterminate | Stop blind retries; never mint a new key until reconciled. |
Stripe’s v1 and v2 behavior shows why 500s cannot be guessed. On API v1, 500 responses from idempotent POST calls are cached, so retrying the same key returns the cached 500—even if incident recovery later reconciles the write and emits a webhook (Advanced error handling). On API v2, retrying the same key skips completed work and retries failed or partially failed work to return an updated response (API v2 overview). Follow explicit retry headers where offered—such as Stripe-Should-Retry (true for exponential backoff, false to stop)—and otherwise reconcile 500s first.
When a row enters RECONCILE_REQUIRED, run four steps:
- Lock the posting row. Block automated retries and manual DLQ redrives from sending a concurrent
POST. - Query the ERP by
posting_key. CallGETon the external-reference field holdingposting_key(or query by document type, counterparty, date, and total if unindexed). - Branch on verified ERP state. If found, verify totals against
payload_hash, storeerp_document_id, and markPOSTED. If the ERP is healthy and returns zero matches with no in-flight lock or pending webhook, log the lookup and run one controlled replay. If the read endpoint is degraded or shows partial lines, route toMANUAL_REVIEW. - Separate edits from retries. Never alter amounts, tax codes, or vendor IDs under an existing
posting_key. Confirm absence in the ERP, mark the old rowABANDONED, and create a new key linked to it.
Guard webhook-driven postings against duplicates and reordering
Payment and commerce webhooks often trigger ERP postings or reconcile a 500 asynchronously. Stripe’s webhook documentation highlights five rules for any webhook-to-ERP worker:
- Acknowledge fast, post asynchronously. Return
2xx(200) before slow accounting writes that can time out. Stripe advises returning200before updating a customer’s invoice as paid in your accounting system, offloading work to a queue. - Verify signatures on the raw body. Check
Stripe-Signatureagainst the unmodified request body andwhsec_signing secret (plus optional IP allowlisting). Keep replay-attack timestamp tolerance enabled: Stripe libraries default to5minutes,0disables the recency check, and each retry carries a fresh signature and timestamp. - Expect overlapping retries and manual resends. Stripe retries live deliveries for up to
3days with exponential backoff (3times over a few hours in sandbox), supports Dashboard resends for15days and CLI resends for30days, and warns that a manual resend returning2xxdoes not cancel pending automatic retries. - Deduplicate on event ID and object transition. Log processed event IDs to skip redeliveries. Because two Event objects can sometimes be generated for one change, also anchor
posting_keyondata.objectID plusevent.type. - Ignore delivery order and timestamp precision. Delivery order is not guaranteed, and snapshot
createdtimestamps use second-level precision so distinct events can share a timestamp. Fetch missing objects viaGETrather than relying oncreated.
Illustrative worked example: one timed-out payment posting
(Illustrative example—not a real company, ERP instance, transaction, or Insonl client.)
Suppose a billing platform sends a settled-payment webhook (event.id = evt_01_demo, event.type = payment.settled, data.object.id = pay_9001) that must post a cash receipt to an ERP whose POST /cash-receipts endpoint has no Idempotency-Key header:
- Webhook intake. The handler verifies the raw-body signature, checks that
evt_01_demois absent fromprocessed_events, enqueues the job, and returns200. - Intent logged. The worker derives
posting_key = cash_receipt:pay_9001:v1(no personal identifiers), hashes the payload intopayload_hash, and inserts aPENDINGrow under a unique index onposting_key. - Ambiguous timeout. The worker sends
POST /cash-receiptswithexternalReference = cash_receipt:pay_9001:v1. The ERP commits receiptCR-44102, then the connection times out. - Reconcile instead of replaying. Lacking server-side idempotency, the worker suppresses blind retries and sets
RECONCILE_REQUIRED. - Read-before-write check. Reconciliation runs
GET /cash-receipts?externalReference=cash_receipt:pay_9001:v1, findsCR-44102, verifies amount and currency againstpayload_hash, savesCR-44102, and marks the rowPOSTED. - Duplicate blocked. Later, an automatic retry or manual resend redelivers the event.
processed_eventsdropsevt_01_demo; even with a new event ID forpay_9001, the unique index oncash_receipt:pay_9001:v1blocks a second write.
Had Step 5 returned zero records against a healthy ERP, the worker would log that lookup and run one controlled replay using the same externalReference.
Where AI fits—and where deterministic posting rules stay in charge
Never let an LLM or agent mint posting keys, infer whether a 500 committed, or trigger a replay POST. Unique indexes, payload hashes, state transitions, and read-before-write lookups stay deterministic code.
AI belongs only in read-only support beside the exception queue:
- Incident clustering. Grouping recurring timeout and
5xxerror payloads so engineers isolate lock contention or maintenance windows faster. - Reconciliation packets. Summarizing a
MANUAL_REVIEWcase—attempt logs, webhook payloads, and candidate ERP records—so an engineer or controller verifies status before approving redrive. - Classifier checks. Flagging newly seen ERP error strings not yet mapped in the deterministic
4xx/5xxtable.
Audit your ERP posting workflow before scaling automation
Insonl is a Ho Chi Minh City engineering studio building ERP systems and operational AI. If your team deals with duplicate ERP entries after API timeouts, webhook retries, or queue replays—or wants to separate deterministic controls from AI in your back-office integrations—start with our free AI workflow audit.
The audit is free. Follow-on work is optional; Insonl charges only for work you choose afterward.
Sources
- Stripe, Idempotent requests — Stripe API Reference: https://docs.stripe.com/api/idempotent_requests
- Stripe, Advanced error handling — Stripe Documentation: https://docs.stripe.com/error-low-level
- Stripe, API v2 overview — Stripe Documentation: https://docs.stripe.com/api-v2-overview
- Stripe, Receive Stripe events in your webhook endpoint — Stripe Documentation: https://docs.stripe.com/webhooks
- Insonl: ERP Systems · Free AI workflow audit · Dead-Letter Queue for Failed ERP Imports · Duplicate Supplier Invoice Detection in ERP
