An order confirmation can reach Amazon SES even when your application sees a timeout. Retry blindly, and the customer may receive two confirmations for one order. This transactional email idempotency example shows how to prevent duplicate application jobs and make an explicit decision when the provider outcome is uncertain.
Use a stable key derived from the business event, store it behind a database uniqueness constraint, and commit the email job with the order update. A worker sends committed jobs and records each outcome. If a provider call times out, keep the result unknown until you reconcile it or choose a documented retry policy; a database key alone cannot prevent a second provider send.
Define the event and its idempotency key
Idempotency means repeating the same request for one logical event does not create another logical send record. If order ORD-4821 is confirmed twice because a client retries, both requests should resolve to the same confirmation job—not create separate jobs.
That protects your application’s processing, not inbox delivery. Your database, email provider, and recipient’s mail system are separate systems; no single database transaction controls all of them. Networks can fail after a provider accepts a message, and a provider acceptance response does not prove delivery to an inbox. Treat exactly-once email delivery as an aspiration, not a guarantee.
Choose a key from stable business identity and message purpose. For example:
account:42:order:ORD-4821:confirmation:v1
Use that same value for every retry of this confirmation. A new random UUID on each attempt makes each retry look like a new event, defeating deduplication. Scope the key to the entity that owns the identifier: if order IDs are only unique within an account, include the account ID too.
Decide what constitutes a new message before choosing the key. Changing a recipient or template while retrying should not silently create a second event; keep the original event identity and define whether its stored payload can be updated. A deliberate resend or a new order event may need a distinct identity. The important distinction is business meaning—not whether the HTTP request body changed.
Persist the send request before calling the provider
Write the business change and email job in one database transaction. The unique constraint is the race-safe guard: if two requests try to create the same confirmation concurrently, the database accepts only one row with that key.
Here is a compact PostgreSQL table for the email outbox. In a real system, the order update and this insert belong in the same transaction.
CREATE TABLE email_outbox (
id bigserial PRIMARY KEY,
account_id bigint NOT NULL,
idempotency_key text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending',
attempts integer NOT NULL DEFAULT 0,
provider_message_id text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (account_id, idempotency_key)
);
Insert the order event and job together:
BEGIN;
UPDATE orders
SET status = 'confirmed'
WHERE id = 'ORD-4821' AND account_id = 42;
INSERT INTO email_outbox
(account_id, idempotency_key, event_type, payload)
VALUES
(42, 'account:42:order:ORD-4821:confirmation:v1',
'order_confirmation',
'{"order_id":"ORD-4821","to":"buyer@example.com"}'::jsonb)
ON CONFLICT (account_id, idempotency_key) DO NOTHING;
COMMIT;
On conflict, load the existing job and return its state rather than creating another. Store enough immutable event data to render the intended message later; otherwise a retry after an application deploy might produce different content for the same event. Avoid holding a database transaction open while making the network call.
Dispatch the transactional outbox with retries
A worker claims pending rows, commits the claim, then calls the provider. In PostgreSQL, workers can select available rows with FOR UPDATE SKIP LOCKED so two workers do not claim the same pending row at once. Record an attempt and a lease or in-flight state before sending; a process can crash between any two steps.
A simplified worker looks like this:
job = claim_one_pending_job_and_commit()
if no job: return
record_attempt(job.id)
try:
response = email_provider.send(job.payload)
save_status(job.id, "accepted",
provider_message_id = response.message_id)
catch definite_invalid_request as error:
save_status(job.id, "failed", error_code = error.code)
catch timeout_or_uncertain_error:
save_status(job.id, "unknown")
catch transient_error:
schedule_retry_with_backoff_and_jitter(job.id)
Use bounded retries for errors you have classified as transient, and stop for validation failures that need a corrected request. Backoff with jitter reduces synchronized retry bursts. Set an attempt limit appropriate to your service, then route exhausted jobs to reconciliation or operator review instead of retrying forever.
A claim prevents ordinary concurrent pickup, but it does not make the provider call atomic with the database. If a worker’s lease expires while it is sending, another worker could take over. Do not interpret an expired lease as proof that the first call failed; recover the job into an uncertain state and apply the same ambiguity policy described below.
Handle a timeout after the provider may have accepted
The hard case is a timeout after the provider accepted the request but before your application saved the response. Your database still says the result is unknown. Retrying might deliver the confirmation twice; refusing to retry might leave the customer without it. The database uniqueness constraint prevents a second logical job, but it cannot deduplicate a second external send by itself.
There are three possible protections, depending on the provider and your system:
- Provider idempotency: If the provider documents a client key for the send operation, pass the same stable key on every retry and follow its stated scope and retention rules.
- Reconciliation: Correlate provider events or available records with your event key before deciding whether to retry. This can resolve some uncertain outcomes, but do not assume every provider exposes a complete lookup for every send.
- At-least-once policy: If you cannot resolve the outcome, retry after a defined interval and accept that a duplicate is possible. Record the decision and make the message understandable if it arrives twice.
Never convert a timeout directly into failed just because your application received no success response. Preserve the attempt time and correlation data, mark the job unknown, and let a recovery process resolve or escalate it. A key policy is part of correctness: quietly retrying an ambiguous send is a business decision with customer-facing consequences.
Apply the pattern to Amazon SES
Amazon SES makes the distinction between application deduplication and provider behavior especially important. The documented SES API v1 SendEmail request and API v2 SendEmail request have no client-supplied idempotency-key field. SES documents that retrying a request can send a second email with a different message ID, and that an error can rarely occur even though SES accepted the email (SES sending process). Do not treat repeating the same request as provider-side deduplication.
When SES returns success, save the returned message ID against the outbox row. That ID identifies a message SES accepted; it does not establish that the message reached the recipient’s mail server or inbox. SES also supports sending-event publishing through configuration sets, and email tags can help correlate events with your application record. Attach a stable event tag, then apply the event information your configured setup makes available to the matching outbox row.
We build Volanea on Amazon SES, and the same application-level rule applies when a team uses an email platform rather than calling SES directly: keep the order-event key and outbox in the system that owns the order. For implementation details around making a provider request, see our email API send guide. Neither a successful API call nor an outbox record should be confused with proof of inbox delivery.
Set retention, observability, and resend rules
Retain an idempotency record for at least as long as your application can replay the event, retry the job, or receive a delayed duplicate request. There is no universal retention duration: order workflows, replay procedures, and audit requirements differ. If you delete a key while an old event can still be replayed, that replay can create a new send.
Make status changes explicit. A useful lifecycle is pending → in_flight → accepted, with unknown, retry_scheduled, and failed paths for uncertain or unsuccessful attempts. Track delivery separately from provider acceptance when event data is available. Keep the original event key and payload consistent across attempts; if an operator intentionally sends a replacement, record that as an audited action with its own reason.
Log the event key, outbox row ID, attempt number, provider message ID when available, outcome category, and timestamps. Do not log full message bodies, verification codes, or unnecessary personal data. Alert on growing outbox backlog, repeated attempts, repeated key conflicts that may indicate a caller bug, and jobs that exhaust retries. Idempotency also does not settle whether a message is properly handled under GDPR or CAN-SPAM; keep privacy, consent, and message-purpose controls separate from duplicate prevention.
FAQ
Should an order confirmation and password reset share an idempotency key?
No. They represent different events and should use different key namespaces, even if they belong to the same user. For example, order:ORD-4821:confirmation:v1 identifies one order confirmation, while a reset key should identify the specific reset event. Reusing a key across purposes could cause one message to suppress another.
Should support use the original key when manually resending an email?
A retry of the same queued event should use its original key. A deliberate support resend is a separate operational action: record who initiated it, why, and which event it relates to. Give it a distinct resend identity so it does not overwrite the original outcome or get mistaken for an automatic retry.
Does an SES message ID mean the recipient received the email?
No. The message ID means SES accepted the message, not that it reached the inbox. Keep provider acceptance and delivery as different states in your application. Where you configure SES event publishing, use the available event data to update delivery status; do not infer delivery merely from a successful SendEmail response.
Start free with 1,000 emails a month: https://app.volanea.com/signup