Prevent duplicate automated emails from webhook retries
A signup, order, or registration webhook times out. The source retries it, and a person receives two identical emails. The retry is expected behavior; the duplicate send is an integration failure. This guide helps the team that connects a source system to an email platform define one intended message per recipient and business event, then prove that repeated delivery does not create another send.
Boletolibre editorial team
Published
Write the message contract before choosing a key
Name the exact source event, business object, recipient, message purpose and condition that makes the email appropriate. A registration-confirmed message and a later venue-change notice are different sends even if they concern the same registration. Conversely, two webhook deliveries with different request IDs can still describe one business action. Write “one confirmation per confirmed registration and recipient” rather than “one email per HTTP request.”[1]
Record who owns the source state, who owns the send, and which system decides the current recipient and consent or transactional eligibility. Do not infer permission merely because a webhook arrived. A ticket buyer and ticket holder may be different people; an edited record can change the recipient. If the email platform has its own automation entry rules, test those as an additional path to the same send instead of assuming the integration is its only trigger.[1]
Use a written contract with fields that can be checked before any send: source and environment, accepted event types, authoritative object ID, eligible object states, recipient role, message purpose, version rule, payload owner, and suppression or contact-policy owner. Mark each field as known, looked up, or unresolved. For an order-confirmed webhook, a useful rule is: after validating the source and reading the current order, create one confirmation intent for each eligible holder with a stable holder ID. A pending order, unknown holder, or disallowed message purpose creates no intent and records why.[1]
Work the contract with a small example. Order 482 first changes to confirmed; event E1 arrives twice, and event E2 later reports the same confirmed order. All three receipts can be logged, but they map to confirmation/order-482/holder-17/v1. A later approved venue change maps to venue-update/order-482/holder-17/v2, which is a new message, not a retry. If the buyer is not the holder, define which role receives each purpose; using the buyer's email merely because it is present on the event may send the wrong person the right template.[1]
Write a decision table beside the contract: eligible and new means claim a send intent; eligible and already claimed means resume or reconcile it; ineligible means record a no-send reason; unknown source state means defer and recheck. Put the current order revision and the template version in the record, but do not automatically put every template edit into the uniqueness key. Otherwise changing punctuation can make a webhook replay look like a new business notification. Decide explicitly when a corrected message is a new approved communication.[1]
Separate delivery deduplication from message deduplication
First, identify a repeated delivery. Keep the provider event ID, its source account or environment, and processing status in a durable event ledger. Stripe warns that the same event can arrive more than once and that two separate Event objects can represent the same object and event type. An event ID is useful for tracing a delivery, but it is not always the right key for the email a person should receive.[1][2]
Second, create a send-intent key from stable business fields: message purpose, source object ID, recipient ID and intentional revision or occurrence. For example, confirmation/order-482/holder-17/v1. Store it in a separate send ledger. Do not use the webhook attempt ID, current timestamp, a fresh UUID created on every retry, or only an email address. The same intended email must map to the same key; a genuinely new notice must map to a new key.[1][2]
When the source lacks a stable event ID, use its documented object ID and event type, then verify current object state before acting. Do not invent a hash of mutable payload text as a permanent identity. If a source has no stable identifier or replay contract, document that limitation and require a manual reconciliation path rather than promising exact deduplication.[1][2]
Treat the two ledgers as separate questions. The receipt ledger answers 'have we durably seen this provider event in this environment?' and supports tracing or replay. The send ledger answers 'has this recipient-purpose-object-revision combination already been authorized or attempted?' A receipt row may point to zero, one, or several send intents if a business event legitimately fans out to multiple recipients. Conversely, several receipt rows may point to one intent. This many-to-many mapping is why a single 'processed' boolean on an incoming request is a poor model for email effects.[1][2]
Make key construction deterministic and scoped. Include a source account or tenant if two sources can issue the same object ID; keep test and live environments apart; normalize only fields whose meaning your system owns. For example, lowercasing an email address is not a substitute for a durable person or subscription ID, and a changed address does not automatically mean a new entitlement to the same confirmation. Document how older keys will remain recognizable after a format migration, or an old replay may evade the new constraint. Store the key's component fields for audit rather than relying on an opaque digest alone.[1][2]
The delivery ledger also needs a processing result more precise than 'seen': verified, durably accepted, evaluated, no-send, intent-created, or needs-reconciliation are useful examples. If a process crashes after recording an event ID but before deciding the send, a later delivery must continue from the incomplete stage. Marking that event complete at receipt time can silently lose an email. The send ledger then determines whether a resumed worker creates a new intent, sees an existing one, or waits for an uncertain provider outcome.[1][2]
| Signal | Good use | Not sufficient for |
|---|---|---|
| Webhook event ID | Trace a repeated delivery | Deciding whether two events intend one email |
| Business object + message purpose + recipient + revision | Guard the intended send | Replacing current-state checks |
| Provider message ID | Reconcile an uncertain acceptance | Defining the business send intent |
Make the decision atomic before the email call
A read-then-insert check can race when two deliveries run together. Use a database uniqueness constraint or an atomic conditional write on the send-intent key. In one durable transaction, record the intended send and an outbox job; only the worker that owns that job may call the email provider. Persist the verified webhook or enqueue durable work before returning the source provider’s success response. If durable acceptance fails, follow that provider’s retry contract instead of acknowledging work that will disappear.[1][3][4]
The ledger needs states such as pending, sending, accepted, failed and uncertain, plus timestamps and provider message ID where available. A second delivery that sees pending or accepted should not create a new job; an event receipt without a committed send intent must resume processing, not be marked complete. A job confirmed rejected before acceptance may be retried under the same intent key. If the worker crashes while sending, the state can be uncertain: a network timeout does not prove the provider rejected the email. Put that case into reconciliation, not an automatic new-key send.[1][3][4]
Retain the key for the full plausible replay and manual-recovery window, according to the source contract and your business requirement. A 24-hour cache is not a universal guarantee. Stripe’s live-mode automatic retries can continue for up to three days, with manual resends longer. A durable record may therefore need a longer life than any downstream provider’s short idempotency window.[1][3][4]
A concrete handoff is: verify the webhook according to the source's contract; persist its accepted identity or a durable queue record; acknowledge promptly; evaluate the authoritative business state; then use one local transaction to claim the unique send key and write a pending outbox row. The response to the webhook must follow the source's documented timeout and retry behavior. Acknowledging only after durable intake avoids losing work, while doing the entire email send inside the request invites timeouts and overlapping retries. This is a design pattern, not a claim that every provider exposes the same acknowledgment rules.[1][3][4]
The unique claim must happen in the database, not in an in-memory lock. Suppose workers A and B both read 'not sent.' A inserts the intent and outbox row; B's insertion loses the uniqueness race, reads the committed row, and does not call the provider. If the transaction fails, neither the intent nor outbox should remain. If a queue dispatch occurs only after a database commit, use an outbox relay or equivalent durable mechanism so a crash between commit and queue publish does not strand the intent. An outbox relay itself can redeliver, so its consumer still needs the unique claim and safe state transitions.[1][3][4]
Give the worker an explicit state machine. PENDING is claimed work not yet attempted. SENDING records an active attempt and a lease or attempt token. ACCEPTED records evidence of provider acceptance and a provider message ID when available. REJECTED_PRE_ACCEPTANCE records a definite failure before acceptance and can be retried under policy. UNCERTAIN means the call may have been accepted but the response was lost. Keep attempt start, completion, reason, and the immutable request fingerprint. A stale SENDING lease is not automatically a safe new send: the worker may have crashed just after the provider accepted it. Move it to reconciliation before another external call.[1][3][4]
Consider three crash points. Before the local transaction commits, retrying evaluation can safely attempt the same unique claim. After commit but before the relay dispatches, the outbox row is still recoverable. After the provider call but before ACCEPTED is stored, local data cannot alone distinguish a lost response from a lost request. This last boundary is why the pattern narrows duplicate risk but cannot guarantee exactly one external provider acceptance. The recovery runbook must say how to query provider history, use a supported idempotency key, and who may authorize a resend when evidence remains ambiguous.[1][3][4]
Check what the email provider actually protects
Some send APIs accept an idempotency key. Resend documents that a repeated request with the same key is recognized for 24 hours and returns the same result for the same request; a changed payload with the same key is an error, and a concurrent matching request can return a retryable conflict rather than the original response. For an identical retry, use a provider key derived from the stable send intent and immutable request version when the route supports it; keep the payload identical. This is a second safeguard, not a replacement for your own ledger across longer replays or multiple sending systems.[2]
Other providers may not expose a send-idempotency feature for the route you use. Ask for the exact API or automation contract, not a generic vendor promise. Record the provider message or campaign ID and consult its send history when a call times out. If you cannot tell whether the provider accepted a send, escalate the uncertain state to a named owner before retrying. An application ledger alone cannot guarantee exactly one provider acceptance across a crash or lost response. Do not equate an API acceptance response with inbox delivery; those are different stages.[2]
A marketing automation might re-enter a contact on a tag change even though your webhook processor created only one contact update. Confirm that the journey itself permits only the desired entry, and check whether a manual campaign, another journey, or a transactional API call can send the same message. The send-intent ledger should represent the business decision across these routes where the systems can share it.[2]
Freeze each provider-request version within an intent: recipients, subject, template or content version, attachments or links, and any provider idempotency key. Save a fingerprint and a restricted reference to the payload so a retry does not silently change meaning. If an attempt is definitely rejected before acceptance, correct the request under the same business intent only with a recorded new provider-request version and a provider key allowed by that provider’s contract. If acceptance is uncertain or confirmed, hold or authorize a separate communication; never reuse an old provider key with changed content. Resend's documented changed-payload conflict illustrates why 'same key, new body' is not a safe repair, and other providers may behave differently.[2]
Classify outcomes before choosing a retry. A clear validation rejection before acceptance can return to a corrected pending state after the cause is fixed. A matching idempotent replay within a documented window may return the prior acceptance. A concurrent-key conflict calls for waiting and retrying the same request later, not a fresh key. A timeout or connection reset after dispatch is UNKNOWN: look for a provider message ID, event log, or supported key lookup before sending again. When the provider's key window has expired, a blind repeat may create another email even if the application still has one intent row.[2]
For example, at 10:00 the worker sends intent confirmation/order-482/holder-17/v1 and the connection drops. At 10:01 the local state is UNCERTAIN, not FAILED. At 10:05 the available provider evidence confirms one accepted message for that intent, so record ACCEPTED without another send. If there is no conclusive provider record, keep a named owner and deadline for investigation; an empty search result is not necessarily proof of rejection. After 24 hours, a Resend key's documented retention period has ended, so the local ledger and manual evidence matter even more.[2]
Handle late updates without suppressing real changes
Webhooks can arrive out of order. Stripe explicitly does not guarantee ordering. If a cancellation is processed before an earlier confirmation event, blindly replaying the old snapshot could send an obsolete welcome or confirmation. For state-dependent messages, fetch the latest authoritative object or compare an authoritative version before creating a send intent. A timestamp alone may not establish event order.[1]
Separate duplicate from correction. If an order is confirmed once, a replay is a duplicate. If a venue changes later, the venue-change message is a new purpose or revision. If an address is corrected after an accepted send, do not silently reuse the old intent key or silently mint a new one; define an explicit resend rule, owner and evidence. This prevents both accidental repeats and missed legitimate notices.[1]
Define which source state wins when events disagree. A registration-created event may arrive after a registration-cancelled event, or a payment-success event can precede an order record becoming readable through another service. For state-dependent email, use a fresh authoritative read, version number, or ordered change sequence where the source supplies one. If the current state is unresolved, defer the intent and schedule a bounded recheck instead of treating the older payload as truth. Record the state version used in the decision so the team can explain why an email was or was not sent.[1]
A cancellation does not automatically erase a previously accepted confirmation; it may require a separate cancellation notice. Similarly, an address correction after acceptance requires an explicit resend decision, because changing the recipient component may create a new key. Make the correction path name the authorized recipient, reason, prior provider ID, and new message purpose or revision. That prevents an operator from 'fixing' the issue by replaying the old webhook with a new key, while preserving a legitimate later notice that should not be suppressed.[1]
Run a failure matrix, then watch the live ledger
Use test recipients and a provider sandbox or authorized narrow segment. Deliver the same event twice, concurrently and after a simulated timeout; each case should produce one send intent and at most one provider acceptance. Then test two distinct events for the same object, a legitimate new message revision, an out-of-order cancellation, a send API timeout, and a crash after provider acceptance but before local confirmation. Record event IDs, send-intent keys, provider IDs and expected outcomes in the worksheet.[1][3][2]
Watch counts for received deliveries, duplicate deliveries, unique send intents, provider accepts, uncertain sends, retry age and manual resolutions. Investigate when deliveries rise but unique intents do not, or when two provider IDs appear under one intent. Keep personal addresses and payloads out of shared logs; use internal references with appropriate access. Re-run the matrix after changing trigger mappings, recipient logic, queue handling or send provider. Hold a launch if an uncertain-send path has no owner.[1][3][2]
Read the 12-case matrix as a set of invariants, not merely twelve green boxes. Cases A-D ask whether first delivery, exact replay, concurrent delivery and a second provider Event object converge on the intended send key. For each, record receipt rows, intent rows, outbox rows, provider attempts and provider IDs. A duplicate receipt is expected in some cases; a second send intent or second acceptance for the same business key is the defect. Case L deliberately crashes after receipt but before intent commit; recovery should resume the decision, rather than silently marking the event complete.[1][3][2]
Cases E-F cover a legitimate new revision and stale state. A new approved notice must get a new intent, while an out-of-order cancellation or obsolete confirmation must be decided against current authoritative state. Case G checks that failed durable receipt storage creates no intent and follows the source's failure and retry contract. Cases H-I cover the dangerous external boundary: timeout and crash just after provider acceptance. The expected outcome is UNCERTAIN plus evidence gathering, not an automatic PASS from an empty inbox or an automatic resend. Case J checks the explicit corrected-recipient path; K checks whether a platform automation independently re-enters the same message. Run these with controlled identifiers and a non-production or otherwise authorized narrow path.[1][3][2]
Make operations observable without storing sensitive payloads in shared logs. Count verified receipts by source, duplicate receipts, no-send decisions, unique intents, outbox age, provider attempts, ACCEPTED records, UNCERTAIN age, and manually resolved cases. Alert on an old PENDING row, a stale SENDING lease, an UNCERTAIN row without an owner, or multiple provider IDs against one intent. A rising duplicate-receipt count alone can reflect a source retry incident; the more important invariant is that unique business intents and external accepts do not multiply. Review samples across event types and environments so a test replay cannot be mistaken for live traffic.[1][3][2]
Before release, perform a recovery drill: stop the worker at each local boundary, restart it, and compare the ledger with provider history. Record who can pause sending, who can authorize an ambiguous resend, what evidence they need, and when to escalate to the source or mail provider. Do not mark the integration 'exactly once.' The defensible release statement is narrower: observed retries and tested crashes converge on one intended send under the tested conditions, with uncertain external outcomes held for reconciliation. Repeat the drill after changing key format, queue topology, provider route, template ownership or automation entry rules.[1][3][2]
Sources and further reading
- Receive Stripe events in your webhook endpointStripe Docs · Accessed
- Idempotency KeysResend Docs · Accessed
- Best practices for working with AWS Lambda Event FunctionsAWS Lambda Developer Guide · Accessed
- Transactional outbox patternAWS Prescriptive Guidance · Accessed