tutorials
Idempotent email sending: stop retries from delivering duplicate mail
September 11, 2026

Your receipt email works perfectly until the day a queue redelivers a message, a client retries a timed-out request, or a webhook fires twice. Now the customer has two copies of the same invoice and a support ticket. The send was never the bug; the missing dedup layer was.
Transactional email lives downstream of unreliable things. Queues deliver at-least-once. HTTP clients retry on timeout. Webhooks get re-sent. Every one of those is correct behavior, and every one of them will run your send path more than once for a single real-world event. If your send path has no memory, "more than once" means "more than one email."
This is a tutorial on making sends idempotent: same logical request in, exactly one email out, no matter how many times the path executes. We will build the dedup layer by hand on Cloudflare D1, walk into the race condition the naive version has, fix it atomically, and handle the hard case (a crash between sending and recording). Then the shortcut, if you would rather not own this code.
Why does the same transactional email get sent twice?
Because at-least-once delivery and client retries re-run your send path, and a path with no dedup state produces one email per run. The duplicate is almost never your code calling send() twice on purpose. It is the same call happening twice because something upstream could not tell whether the first attempt finished.
The three common sources:
- Queue redelivery. You enqueue a send, the consumer calls the provider successfully, then the consumer crashes (or the deploy rolls) before it acks. The queue does the correct thing and redelivers. Your consumer sends again. (This is the exact partial-success window discussed in the Cloudflare Queues email pipeline guide.)
- Client retries. A browser or service posts to your
/checkoutendpoint, the request takes too long, the client times out and retries. The first request actually succeeded and sent the receipt; the retry sends a second one. - Duplicate webhooks. A payment provider's
charge.succeededwebhook is delivered twice (their docs will tell you to expect this). Each delivery triggers your "send receipt" handler.
None of these is fixable by being more careful in the send function. They are fixable only by giving the send path a durable memory of what it has already done, keyed on an idempotency key. Idempotency is one of the habits in the transactional email best practices developers skip, and it sits next to the queue-level safeguards in the Cloudflare Queues patterns for reliable sending.
What makes a good idempotency key for email?
A good idempotency key is derived from the business event the email represents, so it is identical across every retry of that event and unique across different events. The key is the whole game. Get it wrong and the rest of the machinery is decoration.
The wrong key is a fresh random value generated at send time:
// WRONG: a new key every call defeats dedup entirely
const key = crypto.randomUUID();
await sendOnce(key, message);
When the queue redelivers, your consumer runs again, generates a different UUID, and the dedup table sees a brand-new key. You deduped nothing. Random-at-send-time keys only help if the same message object (carrying the same key) is what gets redelivered, which is true for queue bodies but not for client retries or webhooks that reconstruct the request.
The right key is stable and derived from the event:
// RIGHT: same event always yields the same key
function idempotencyKey(event: {
kind: string; // "receipt", "password-reset", "welcome"
entityId: string; // order id, user id
nonce?: string; // optional, for genuinely repeatable events
}): string {
return [event.kind, event.entityId, event.nonce].filter(Boolean).join(":");
}
idempotencyKey({ kind: "receipt", entityId: "order_1234" });
// => "receipt:order_1234"
Two rules:
- Identical across retries.
receipt:order_1234must come out the same whether it is the first attempt or the fifth redelivery. That means it cannot contain a timestamp, a random value, or anything that changes between attempts. - Unique across distinct sends. If a user can legitimately receive the same kind of email more than once (a password reset they requested twice, a re-sent receipt), encode what makes them distinct (
nonce, request id) so the two legitimate sends get two different keys. A genuinely repeatable email needs a per-request nonce that you persist with the triggering action, not one minted at send time.
How do I build a dedup table in D1?
Create a table whose idempotency key is unique, and let the database enforce "only one row per key." This is the durable memory the send path was missing.
-- migrations/0001_sent_emails.sql
CREATE TABLE sent_emails (
idempotency_key TEXT PRIMARY KEY, -- unique by construction
status TEXT NOT NULL, -- 'claimed' | 'sent' | 'failed'
provider_id TEXT, -- the delivery provider's message id
to_addr TEXT NOT NULL,
created_at INTEGER NOT NULL, -- epoch ms, for retention cleanup
sent_at INTEGER
);
The PRIMARY KEY on idempotency_key is doing the load-bearing work. It is a unique constraint, so the database physically cannot hold two rows for receipt:order_1234. The rest is bookkeeping: status tracks the lifecycle, provider_id correlates with the provider's dashboard and webhooks, created_at drives retention cleanup.
Now the naive send function. Read this one, because it has a bug we walk into on purpose:
// NAIVE: looks idempotent, has a race condition
async function sendIdempotent(env: Env, key: string, msg: EmailMessage) {
// 1. Have we sent this already?
const existing = await env.DB
.prepare("SELECT status, provider_id FROM sent_emails WHERE idempotency_key = ?")
.bind(key)
.first<{ status: string; provider_id: string | null }>();
if (existing) {
return { deduped: true, providerId: existing.provider_id };
}
// 2. Mark it and send.
const res = await callProvider(env, msg, key);
await env.DB
.prepare(
"INSERT INTO sent_emails (idempotency_key, status, provider_id, to_addr, created_at, sent_at) VALUES (?, 'sent', ?, ?, ?, ?)",
)
.bind(key, res.id, msg.to, Date.now(), Date.now())
.run();
return { deduped: false, providerId: res.id };
}
In a single-threaded test this passes. Send once, the row is absent, you send and insert. Send again, the SELECT finds the row, you dedupe. Looks done. It is not.
Where is the race condition in the dedup check?
The race is the window between the SELECT and the INSERT. Two retries that arrive close together can both run the SELECT, both see no row, and both proceed to send. The check and the claim are two separate operations, and anything can happen between them.
Picture the queue redelivering a message at almost the same moment a client retry hits, both carrying receipt:order_1234:
time consumer A consumer B
---- ---------------------------- ----------------------------
t0 SELECT key -> (none)
t1 SELECT key -> (none) <- both see nothing
t2 callProvider() -> email #1
t3 callProvider() -> email #2 <- duplicate sent
t4 INSERT key
t5 INSERT key -> ???
Two emails went out before either row was written. The SELECT-then-INSERT pattern cannot be made safe by reordering or adding more checks: the two statements are not atomic, so a concurrent caller can always slip between them. This is not a Cloudflare quirk. It is the classic check-then-act race, and it shows up the instant two copies of your send path run concurrently, which is precisely what retries guarantee.
How do I make the dedup atomic?
Collapse the check and the claim into a single atomic statement: INSERT ... ON CONFLICT DO NOTHING. Exactly one concurrent writer wins the row. Only the winner is permitted to call the provider. The losers learn they lost and dedupe.
async function sendIdempotent(env: Env, key: string, msg: EmailMessage) {
// CLAIM atomically. Exactly one caller can win this row.
const claim = await env.DB
.prepare(
`INSERT INTO sent_emails (idempotency_key, status, to_addr, created_at)
VALUES (?, 'claimed', ?, ?)
ON CONFLICT(idempotency_key) DO NOTHING`,
)
.bind(key, msg.to, Date.now())
.run();
// D1 reports how many rows changed. 1 = we claimed it; 0 = someone else has it.
const weWon = claim.meta.changes === 1;
if (!weWon) {
// Lost the race (or this is a later retry). Return the prior result.
const prior = await env.DB
.prepare("SELECT status, provider_id FROM sent_emails WHERE idempotency_key = ?")
.bind(key)
.first<{ status: string; provider_id: string | null }>();
return { deduped: true, status: prior?.status, providerId: prior?.provider_id };
}
// We own the send. Call the provider, passing the SAME key as its idempotency header.
const res = await callProvider(env, msg, key);
await env.DB
.prepare(
"UPDATE sent_emails SET status = 'sent', provider_id = ?, sent_at = ? WHERE idempotency_key = ?",
)
.bind(res.id, Date.now(), key)
.run();
return { deduped: false, providerId: res.id };
}
Re-run the same timeline and the race is gone:
time consumer A consumer B
---- -------------------------------- --------------------------------
t0 INSERT ... ON CONFLICT -> 1 row INSERT ... ON CONFLICT -> 0 rows
t1 weWon = true weWon = false -> deduped, no send
t2 callProvider() -> email #1
t3 UPDATE status='sent'
One row, one winner, one email. Consumer B never calls the provider. The database's unique constraint is the synchronization primitive; you are not reinventing a lock, you are letting the row be the lock.
Two details that matter:
claim.meta.changesis how D1 (and SQLite) tells you whether theINSERTactually wrote a row.1means you won;0meansON CONFLICT DO NOTHINGswallowed a duplicate. Branch on it.- Pass
keyto the provider too. The same string goes into the provider'sIdempotency-Keyheader insidecallProvider. That is your second line of defense for the one window the row can't cover, which is next.
async function callProvider(env: Env, msg: EmailMessage, key: string) {
const res = await fetch("https://api.delivery.example/v1/send", {
method: "POST",
headers: {
authorization: `Bearer ${env.API_KEY}`,
"idempotency-key": key, // provider dedupes within its own window
},
body: JSON.stringify(msg),
});
if (!res.ok) throw new Error(`provider ${res.status}: ${await res.text()}`);
return (await res.json()) as { id: string };
}
What about a crash between sending and recording?
This is the one window the row alone cannot close: you won the claim, you called the provider, the email went out, and then your Worker died before the UPDATE status='sent' landed. The row is stuck at status='claimed'. A retry arrives, sees the existing row, and dedupes (good) but also has no provider_id to return, and you cannot be fully sure the email actually shipped.
You cannot make the provider call and the database write a single atomic transaction; they are two different systems. So you reconcile instead. Three things together make this safe:
- The provider idempotency header. Because
callProvidersentIdempotency-Key: receipt:order_1234, re-sending after a crash is a no-op at the provider within its dedup window (commonly 24 hours). So even if a retry re-attempts the send, the customer does not get a second email. The header covers exactly the gap your row cannot. - A claim timeout. Treat a row stuck at
status='claimed'for longer than your max single-attempt time as reclaimable. A retry that finds a stale claim is allowed to re-attempt the send, relying on (1) to prevent a duplicate, then write the result. - Reconcile from the provider, not from guesswork. If you need certainty about whether the original email shipped, query the provider for that idempotency key or message id rather than assuming.
const CLAIM_TIMEOUT_MS = 60_000; // longer than any single send attempt
if (!weWon) {
const prior = await env.DB
.prepare("SELECT status, provider_id, created_at FROM sent_emails WHERE idempotency_key = ?")
.bind(key)
.first<{ status: string; provider_id: string | null; created_at: number }>();
const stale =
prior?.status === "claimed" && Date.now() - prior.created_at > CLAIM_TIMEOUT_MS;
if (stale) {
// Original attempt likely crashed mid-flight. Safe to re-send:
// the provider's Idempotency-Key makes a real duplicate impossible.
const res = await callProvider(env, msg, key);
await env.DB
.prepare("UPDATE sent_emails SET status = 'sent', provider_id = ?, sent_at = ? WHERE idempotency_key = ?")
.bind(res.id, Date.now(), key)
.run();
return { deduped: false, recovered: true, providerId: res.id };
}
return { deduped: true, status: prior?.status, providerId: prior?.provider_id };
}
The layered design is the point: the unique row stops the common concurrent-retry case with zero provider calls, and the provider header backstops the rare crash-in-the-gap case. Neither alone is sufficient; together they give you exactly-once delivery on top of at-least-once execution.
Common failure modes (and what they mean)
The same receipt still arrived twice
Your idempotency key is not stable across retries. Check that it is derived from the business event (receipt:order_1234), not from crypto.randomUUID() or a timestamp generated at send time. Log the key on every attempt and confirm both attempts print the identical string.
UNIQUE constraint failed: sent_emails.idempotency_key
You are still using INSERT (or SELECT-then-INSERT) instead of INSERT ... ON CONFLICT DO NOTHING. The constraint is firing because two writers reached the plain INSERT. Switch to the conflict-tolerant form and branch on meta.changes.
A retry returns deduped:true but providerId is null
The original attempt won the claim and crashed before the UPDATE. The row is stuck at status='claimed'. Add the claim-timeout reconciliation so a stale claim can be re-attempted under the provider's idempotency header.
Legitimate re-sends are being suppressed
Your key is too coarse. A user who requests two password resets gets one key (password-reset:user_88) and the second is deduped away. Add a per-request nonce you persist with the triggering action so the two legitimate sends get two distinct keys.
The shortcut: idempotent sends without owning the dedup layer
Everything above is the correct architecture, and it is also real code you now own forever: a key derivation you have to keep stable, a dedup table, an atomic claim, a crash-recovery path, and a retention job. If you would rather not maintain that, this is exactly what Tinbox builds into the send path it deploys on your own Cloudflare account.
npx tinbox init yourdomain.com
Tinbox's send() accepts an idempotency key, records it in your D1 with the atomic claim, passes it through to the provider call, and handles the claimed-but-crashed reconciliation. You pass a stable key; a retry is a no-op.
import { tinbox } from "tinbox/cf";
export default {
async fetch(req: Request, env: Env): Promise<Response> {
await tinbox(env).send({
to: "user@example.com",
from: "billing@yourdomain.com",
subject: "Your receipt",
html: "<p>Thanks for your order.</p>",
idempotencyKey: "receipt:order_1234", // stable, derived from the event
});
return new Response("queued", { status: 202 });
},
};
Call it five times with the same idempotencyKey and exactly one email is delivered, on infrastructure you control with no per-email pricing on top. The dedup row lives in your D1 (see how the schema is laid out), so you can audit it yourself. Because Cloudflare Workers cannot open outbound port 25 for direct-to-MX SMTP, the actual delivery happens over HTTPS in the consumer Tinbox deploys; the idempotency key rides along on that call. For the broader reliability picture, the queue, retry, and dead-letter pipeline and rate limiting at the edge are the two pieces that sit next to this one.
Deploy this yourself: npx tinbox init yourdomain.com. The idempotency key contract and the dedup table layout are documented in the Tinbox docs.
Frequently asked questions
What is idempotent email sending?
Idempotent email sending means that the same logical send request, issued more than once, results in exactly one email being delivered. You achieve it by attaching a stable idempotency key (derived from the business event, like 'order-1234-receipt') to each send and deduplicating on that key in durable storage before calling the delivery provider. A retried or redelivered request finds the existing key and becomes a no-op.
Why does my transactional email get sent twice?
Duplicate sends almost always come from retries and at-least-once delivery, not from your code calling send twice on purpose. A queue redelivers a message after the consumer crashed between sending and acking; a client retries a timed-out POST; a webhook is delivered more than once. Any of these re-runs your send path. Without a dedup key recorded before the provider call, each re-run produces another email.
What should I use as an idempotency key for email?
Use a stable key derived from the business event the email represents, such as 'receipt:order_1234' or 'password-reset:user_88:nonce_abc'. Do not use crypto.randomUUID() generated at send time, because a retry generates a new UUID and defeats dedup. The key must be identical across every retry of the same logical send and unique across different logical sends.
Where is the race condition in a dedup layer?
The race is between checking whether a key exists and recording it. If you SELECT for the key, see nothing, then INSERT and send, two concurrent retries can both pass the SELECT and both send. The fix is an atomic INSERT with a unique constraint (INSERT ... ON CONFLICT DO NOTHING): exactly one writer wins the row, and only the winner is allowed to call the provider.
Does the delivery provider's idempotency key make my send idempotent?
Only partially. A provider-side Idempotency-Key header dedupes at the provider for a limited window (often 24 hours) and only protects the final HTTPS call. It does not stop your own code from doing duplicate database writes, duplicate billing, or duplicate work before the send. You want both: your own dedup record for the business event, and the provider header as a second line of defense.
How long should I keep idempotency keys?
Keep them at least as long as your longest retry and redelivery window, plus a margin. For queue-driven sends with backoff capped at minutes and max_retries in the single digits, hours is enough; for client-initiated sends that users might re-trigger, days is safer. A periodic cleanup deleting keys older than your retention window keeps the table small without reintroducing duplicates.