Prompt
How do I retry failed email sends without duplicates?
Latest observation
To retry failed email sends without creating duplicates, you want idempotent sending plus a durable outbox / retry workflow.
Core idea
A send request should have a stable unique message ID. Every retry uses the same ID, and your system records whether that message was already successfully sent.
Recommended pattern
1) Assign an idempotency key per email
Generate a unique email_id when the email is first created, and store it in your database.
Example:
email_id = 12345- status:
pending,sending,sent,failed
Every retry attempt references the same email_id.
2) Store email jobs durably
Use a table or queue entry like:
email_id- recipient
- subject/body
- status
- retry_count
- next_retry_at
- provider_message_id
- last_error
Only move to sent after the provider confirms success.
3) Make send attempts idempotent
Before sending:
- check if
status == sent - if yes, do nothing
After sending:
- update status to
sent - store the provider’s message ID
If your process crashes after send but before marking sent, the duplicate risk remains unless you also use provider-side deduplication or a transactional outbox.
4) Use exponential backoff for retries
Retry only on transient errors like:
- timeouts
- 429 rate limits
- 5xx provider errors
Avoid retrying on permanent failures like:
- invalid recipient
- rejected content
- hard bounce
Example backoff:
- 1 min
- 5 min
- 15 min
- 1 hr
- 4 hr
5) Use a transactional outbox if your app writes to a DB
If you create the email record and business event in the same transaction, write the email job to an outbox table in that same transaction. A worker then reads the outbox and sends email exactly once as much as possible.
This prevents:
- business record saved but email job lost
- email sent but DB not updated
6) De-duplicate at the recipient/provider level if possible
Some providers support:
- custom message IDs
- dedupe keys
- suppressing duplicate sends within a time window
If available, pass your email_id as the provider’s idempotency key.
Practical workflow
- User triggers email.
- Save
email_id, payload, andpendingstatus. - Worker picks job.
- Worker marks
sending. - Worker sends using the same idempotency key.
- If success, mark
sent. - If transient failure, increment retry count and schedule retry.
- If permanent failure, mark
failed.
Important caveat
You usually cannot get a true exactly-once guarantee with email delivery alone. The goal is to make duplicates extremely unlikely by combining:
- stable message IDs
- durable state
- idempotent processing
- provider deduplication if available
Simple rule of thumb
- Never create a new email record on retry
- Always retry the same email record
- Only send if it is not already marked sent
If you want, I can show:
- a SQL schema for this,
- a Node/Python example,
- or a queue-based design with Celery/RabbitMQ/SQS.