Skip to content
Engineering

How to prevent duplicate emails when an API request times out

Reproduce a lost response and understand the boundaries of duplicate prevention.

THE SHORT ANSWER

Persist one idempotency key and one payload per logical email before the first request. If the response is lost, reuse both. A timeout describes what your client observed; it does not prove the email service rejected the request.

Before you start #

For
Backend developers handling timeouts and retried jobs.
Bring
Basic transactions and HTTP. Node.js 22+; the optional database lab also needs PostgreSQL 17+, pg 8 and a disposable local _test database.
Scope
The first lab uses memory. The second exercises PostgreSQL persistence and locking with a simulated provider. Neither sends mail.

The failure happens between acceptance and acknowledgement #

Imagine a checkout commits order 42 and asks an email API to send its receipt. The API saves the message, but the network connection closes before your application receives the response. Your application sees failure; the email service has a valid job.

A retry with a brand-new key creates another logical send. Disabling retries avoids that duplicate but can lose receipts when the first request really never arrived. A stable operation identity lets you recover without guessing which failure occurred.

Idempotency is a contract with a scope and a lifetime. Check the provider’s key retention, account or endpoint scope, concurrent-request behavior, and payload-conflict response. A key is not a promise of global exactly-once delivery forever.

Create the identity with the business event #

Write the receipt outbox row in the same database transaction as the completed order. Give it a unique key such as receipt:order-42:v1. If the transaction rolls back, neither the order nor the receipt event should exist.

Persist the exact payload or immutable references that reproduce it. Rendering a template again on each retry can change the text, timestamp, or template version and create a conflict. A deliberate resend is a new business decision with a new identity, not a hidden retry.

Do not put email addresses or access tokens in idempotency keys. Keys often appear in logs. A stable opaque event ID or internal business identifier is enough.

Concurrent attemptRequired boundary
Two requests create the same receipt eventA database uniqueness constraint admits one logical outbox row.
Two workers see the pending rowAn atomic claim with an owner and lease limits concurrent processing.
A lease expires during a slow provider callA new worker must account for the unresolved call; a lease alone cannot prevent two submissions.
The old worker finishes after reassignmentCondition local updates on the current claim; reuse the provider idempotency key when its contract permits.
Outbox uniqueness · SQL patternsql
CREATE TABLE receipt_outbox (
  event_key text PRIMARY KEY,
  payload jsonb NOT NULL,
  state text NOT NULL DEFAULT 'pending',
  provider_message_id text,
  created_at timestamptz NOT NULL DEFAULT now()
);
-- Insert alongside the order transaction, before making network calls.
-- Use worker leases and bounded retry scheduling in production.

Exercise the outbox boundary in PostgreSQL #

The in-memory lab later in this article demonstrates request deduplication. This second lab uses real PostgreSQL transactions and row locks for one project and environment. It writes an order and its email intent together, rejects a changed payload, and holds one worker’s claim while five other connections try to take it.

The simulated provider then accepts one message without giving the worker an acknowledgement. Expiring the lease moves the row to uncertain. A late worker update fails its claim-version check, and a new database connection still sees the unresolved operation. The lab deliberately ends there: SQL cannot tell you whether a remote system accepted a request.

Use Node.js 22+, PostgreSQL 17+ and pg 8. Run in a separate directory with a disposable local database. The script accepts only numeric loopback hosts and database names ending in _test, creates a random schema, and removes that schema on normal exit. It makes no provider requests and sends no email. If the process is forcibly killed, its printed schema name identifies any leftover fixture.

Run the database lab · save outbox-lab.mjs beside package.jsonshell
npm init -y
npm install pg@8
createdb stampwing_outbox_test
# Replace YOUR_LOCAL_ROLE with your PostgreSQL role.
OUTBOX_LAB_DATABASE_URL='postgresql://YOUR_LOCAL_ROLE@127.0.0.1:5432/stampwing_outbox_test' \
  node outbox-lab.mjs

# Expected: checks: 8, simulatedProviderAcceptances: 1,
# finalState: "uncertain", sendsRealEmail: false

Download the complete PostgreSQL outbox lab →

PostgreSQL: row locking and SKIP LOCKED →

AWS: transactional outbox pattern and remaining duplicate risk →

Classify the result before choosing a retry #

Use bounded exponential backoff with jitter for retryable failures. Persist the next attempt time so a process restart does not reset the retry budget or make every worker retry simultaneously. A worker lease prevents two processes from independently treating the same outbox row as unclaimed.

Retry-After can contain a delay in seconds or an HTTP date. Use the documented server delay as a lower bound alongside your backoff. If it exceeds the remaining retry budget or content lifetime, stop or defer for review; do not shorten it just to fit a local cap. Persist the chosen next-attempt time, and keep attempts bounded even when the header is missing or invalid.

ResultAction
Accepted with a message IDSave the ID and watch delivery events. Do not submit another message.
Network timeout / connection resetTreat as unresolved. Reconcile or retry the same key and unchanged payload.
429 rate limitRespect Retry-After and your attempt budget. Preserve the key.
Validation or authentication rejectionCorrect the underlying problem. Do not repeatedly retry unchanged invalid input.
Idempotency conflictStop and compare the original payload with the retry.
Key expired or unknown retentionReconcile the original send before creating a new operation.

Check whether idempotency reaches the actual send operation #

An idempotent application endpoint does not make every downstream transport idempotent. Amazon SES v2 SendEmail’s documented request has no client idempotency token. Do not infer that replaying SendEmail is safe just because your own API accepts an Idempotency-Key header.

Before retrying an ambiguous submission, identify the provider operation, the retry behavior inside its SDK, and the evidence available for reconciliation. If the provider cannot deduplicate or establish the outcome, keep the operation unresolved and make the duplicate-versus-omission decision explicit. “Retry until success” silently chooses the risk of duplicate mail.

Crash pointWhat remains knownRecovery
Before the business transaction commitsNo committed email intent exists.Retry the business operation under its stable identity.
After commit, before claimingA pending outbox record exists.A worker may claim it.
After claiming, before a confirmed provider responseThe provider outcome may be unknown.Use the provider’s documented deduplication or reconcile; otherwise quarantine.
After storing the provider message IDSubmission has a recorded acknowledgement.Follow delivery events; do not call SendEmail again.

SES v2 SendEmail: complete request contract →

Run a lost-response experiment without sending mail #

The downloadable Node.js lab accepts a simulated message, deliberately loses the response, and retries with the same key. It also checks a changed-payload conflict and ten matching concurrent calls. It uses an in-memory ledger, so it is a teaching fixture rather than a production idempotency service.

Download the file and run it with Node.js 22 or later. It imports only Node built-ins, uses no credentials, and does not contact a provider.

Run locallyshell
node idempotency-lab.mjs

# Expected: tests: 4, queued: 1, mode: "demo", sendsRealEmail: false

Idempotent submission is only one boundary #

Your application may generate the same business event twice before it reaches the email API. Your webhook endpoint may receive the same notification more than once after delivery. Each boundary needs its own identity and deduplication rule.

Keep an append-only delivery timeline rather than allowing any late event to overwrite the current state. A delayed submitted event should not erase later evidence of server acceptance. Complaints and bounces are distinct events with their own handling, not merely lower or higher numbers in one status ladder.

For an uncertain provider submission, a service may need reconciliation before dispatching again. Do not claim exactly-once delivery simply because the application endpoint accepts idempotency keys.

IntentIdentity decision
Recover the same request after a timeoutReuse its key and unchanged payload within the supported window.
Send another copy after a confirmed outcomeAuthorize a distinct resend and link it to the original operation.
Issue a new reset tokenCreate a new reset operation and apply your older-token policy.
Receive the same delivery callback againDeduplicate the webhook event; do not create an email send.

Build a durable webhook inbox →

Keep these failures in your regression suite #

For each test, assert both the number of logical messages and the stored state. A successful HTTP response alone cannot prove that a retry policy avoided duplicates.

  • The application commits an event and crashes before the first API call.
  • The provider accepts a message and the response is lost.
  • Two workers claim or retry the same logical event concurrently.
  • A retry accidentally renders a different template version.
  • A process restarts during backoff or after the provider’s key-retention window.
  • Duplicate or out-of-order delivery callbacks arrive after recovery.

Fit retries inside the message’s useful lifetime #

Consider a synthetic password reset whose token expires 10 minutes after the original request. Start with a 30-second delay, double it after each retry, cap delays at one hour, and use no jitter for this example. The fifth retry would already fall outside the token lifetime even if every request completed instantly.

Backoff controls timing; it does not deduplicate a request. Preserve the original key and payload while the operation is valid. Before each retry, compare the current time with the content expiry and the provider’s idempotency retention window. Account for request duration, queue wait, and time needed for the recipient to act.

RetryCumulative waitingWithin a 10-minute lifetime?
130 secondsYes, before adding request duration.
21 minute 30 secondsYes, before adding request duration.
33 minutes 30 secondsYes, before adding request duration.
47 minutes 30 secondsYes, if request duration leaves enough time.
515 minutes 30 secondsNo. Stop this operation rather than send expired content.

Compare fixed backoff and full jitter →

Sources and further reading

Written for Stampwing with AI assistance and checked against the linked documentation. Examples are educational; simulated results are labelled. How these resources are maintained.