tutorials
Idempotent email sending so users never get duplicate receipts
November 27, 2026

A user double-clicks "Place order." Your queue redelivers a message after a lost ack. A cron job runs twice because the first run timed out. Each of these sends the same receipt again, and the customer gets two. This is the idempotency problem, and the queue will not solve it for you.
Duplicate transactional email is one of those bugs that never shows up in dev and always shows up the week you get traffic. It is rarely a bug in the email code. It is a bug in the assumption that the thing which triggers the email happens exactly once. It does not. Buttons get double-clicked, requests get retried, queues redeliver, and operators replay. Every one of those paths can fire your send a second time.
The fix is idempotency: make sending the same logical email twice produce one delivery. Let's build that by hand over Cloudflare Queues, honestly, including the parts that are easy to get subtly wrong. Then, at the end, the shortcut if you would rather not own a dedupe ledger.
What makes an email send idempotent?
A send is idempotent when issuing it twice with the same idempotency key results in exactly one delivery. The key is a stable identifier for the logical email, derived from the event that caused it, and you check that key against durable storage before you dispatch. If you have seen the key, you do not send again; you return the original result.
Three ingredients, all required:
- A stable key. Derived from the triggering event plus the email's purpose, so every retry of the same event carries the same key.
order:8421:receipt, not a fresh UUID per attempt. - A durable record. A row keyed by that idempotency key, written before or as part of the send, so a second attempt can see that the first happened.
- An atomic claim. A way to check-and-record in one step, so two concurrent attempts cannot both decide they are first.
Miss any one and you have a deduplication that works in the demo and fails under a race. The most common mistake is the first one, so start there.
Why must the idempotency key be derived, not random?
Because a random key generated at send time changes on every attempt, so it can never collide, so it can never dedupe. This sounds obvious and yet it is the single most frequent way idempotency is implemented and silently does nothing.
The key has to be a deterministic function of the event. Two attempts to send the same receipt must compute the same key:
// WRONG: a new key every attempt; deduplicates nothing
const key = crypto.randomUUID();
// RIGHT: same event -> same key, on every retry
function idempotencyKey(event: { type: string; orderId: number }) {
return `${event.type}:${event.orderId}:receipt`;
}
If a single event can legitimately send the same purpose more than once (a monthly invoice for the same subscription, say), fold the discriminator into the key: invoice:sub_42:2026-06. The rule is simple: the key encodes "which email is this," not "which attempt is this."
Generate the key at the boundary where the event first enters your system (the request handler, the cron tick) and carry it through the queue. Do not let the consumer invent it, because the consumer runs once per delivery and you want the same key across deliveries.
How do I store dedupe state in D1?
Use a table whose primary key is the idempotency key, so the database enforces uniqueness for you. The unique constraint is the whole mechanism: it is what makes "have I seen this key" a single atomic operation instead of a read-then-write race.
CREATE TABLE IF NOT EXISTS email_dedupe (
idempotency_key TEXT PRIMARY KEY,
status TEXT NOT NULL, -- 'claimed' | 'sent'
message_id TEXT, -- provider id once sent
created_at INTEGER NOT NULL
);
Two states matter. claimed means an attempt is in flight; sent means delivery succeeded and the provider gave us a message id. You do not strictly need a failed state: a transient failure just leaves the row claimable again (more on that below). The created_at column is for expiry, which we will use to keep the table from growing without bound.
This is the same idea covered in designing a D1 schema for an email stack; the dedupe table is one more small, boring table that earns its keep the first time a queue redelivers.
How do I claim a key atomically in the consumer?
Use INSERT OR IGNORE on the dedupe table and check whether a row was actually inserted. If you inserted it, you won the race and you are responsible for sending. If you did not, someone else already claimed (and presumably sent) this key, so you skip.
D1 / SQLite gives you exactly the primitive you need:
// Returns true if THIS attempt claimed the key (i.e. we should send).
async function claimKey(env: Env, key: string): Promise<boolean> {
const res = await env.DB.prepare(
`INSERT OR IGNORE INTO email_dedupe (idempotency_key, status, created_at)
VALUES (?1, 'claimed', ?2)`
)
.bind(key, Date.now())
.run();
// meta.changes is 1 when a row was inserted, 0 when the key already existed.
return res.meta.changes === 1;
}
The whole correctness argument rests on INSERT OR IGNORE being atomic: two consumers racing on the same key cannot both get changes === 1. One inserts, the other is ignored. No read-modify-write window, no SELECT then INSERT that two attempts can interleave.
Now the consumer reads top to bottom. Note the ordering: claim, then send, then mark sent.
export default {
async queue(batch: MessageBatch<SendJob>, env: Env): Promise<void> {
for (const msg of batch.messages) {
const { key, email } = msg.body;
// 1. Try to claim. If we don't, a prior delivery already handled this.
const won = await claimKey(env, key);
if (!won) {
const row = await env.DB.prepare(
`SELECT status FROM email_dedupe WHERE idempotency_key = ?1`
).bind(key).first<{ status: string }>();
if (row?.status === "sent") {
msg.ack(); // already delivered; nothing to do
continue;
}
// status is 'claimed' but not yet 'sent': another attempt is mid-flight.
// Don't double-send. Retry shortly so we converge once it settles.
msg.retry({ delaySeconds: 15 });
continue;
}
// 2. We own this key. Send.
try {
const messageId = await dispatch(email, env);
// 3. Record success so future deliveries short-circuit.
await env.DB.prepare(
`UPDATE email_dedupe SET status = 'sent', message_id = ?2
WHERE idempotency_key = ?1`
).bind(key, messageId).run();
msg.ack();
} catch (err) {
// Transient failure: release the claim so a retry can re-attempt.
await env.DB.prepare(
`DELETE FROM email_dedupe WHERE idempotency_key = ?1 AND status = 'claimed'`
).bind(key).run();
msg.retry({ delaySeconds: 30 });
}
}
},
};
Read the failure path carefully, because it is where naive implementations leak. If the send throws, we delete the claimed row (and only if it is still claimed, so we never clobber a row another attempt promoted to sent). That releases the key so the queue's retry can legitimately try again. If we instead left a permanent claimed row on failure, every retry would see "already claimed" and skip, and the email would never go out: a self-inflicted black hole.
The producer side is unremarkable. Compute the key at the edge and put it on the message:
// In your request handler / cron, NOT in the consumer.
await env.SEND_QUEUE.send({
key: idempotencyKey({ type: "order", orderId }),
email: { to, subject, html },
});
Why isn't at-least-once delivery enough on its own?
Because at-least-once means the queue may deliver a message more than once, by design, and the classic duplicate is invisible to the queue. Picture this sequence:
- The consumer claims the key, sends the email, the recipient receives it.
- Before
msg.ack()is recorded, the consumer's isolate is evicted, or the batch times out, or the network blips. - The queue never saw the ack, so it redelivers the message.
- A fresh consumer picks it up.
Without dedupe, step 4 sends the receipt a second time. With the table, step 4 calls claimKey, gets changes === 0 because the row is already sent, and acks without sending. The duplicate delivery from the queue becomes a single delivery to the user. That gap between "the side effect happened" and "the ack was recorded" is exactly why exactly-once delivery is impossible and idempotency is mandatory. The queue does the hard part of not losing messages; you do the hard part of not duplicating side effects. The retry and dead-letter mechanics underneath this are covered in sending email reliably with Cloudflare Queues, and the Cloudflare Queues patterns for reliable email sending collects the dedupe, batching, and backoff shapes in one place. Idempotency is also one of the items on the transactional email best practices developers skip.
How do I keep the dedupe table from growing forever?
Expire old rows on a schedule, because an idempotency record only needs to outlive the window in which a duplicate could plausibly arrive. That window is your queue's maximum retry age plus any manual replay you might do. After that, an old event will never be redelivered, so its row is dead weight.
A Cron Trigger that runs daily is plenty:
// wrangler.jsonc: { "triggers": { "crons": ["0 4 * * *"] } }
export default {
async scheduled(_event: ScheduledController, env: Env): Promise<void> {
const cutoff = Date.now() - 14 * 24 * 60 * 60 * 1000; // 14 days
await env.DB.prepare(
`DELETE FROM email_dedupe WHERE created_at < ?1`
).bind(cutoff).run();
},
};
Pick the retention to comfortably exceed your longest realistic replay. Two weeks is a sane default; if you replay quarter-old events during incident recovery, keep the rows that long instead. The cost of an extra row is negligible; the cost of expiring one too early is a duplicate. See scheduling work with Cron Triggers for the wiring, and the ways Cloudflare Cron Triggers can run your email for the other jobs a cron earns its keep on.
What does this look like end to end?
The honest checklist, because the failure modes are all in the seams:
- Key is derived from the event, computed once at the edge, carried through the queue. Random per-attempt keys deduplicate nothing.
- Claim is atomic via
INSERT OR IGNOREand achangescheck. NoSELECTthenINSERT. - Order is claim, send, mark sent. Marking sent before the send means a crash mid-send leaves a row that blocks the real delivery.
- Transient failures release the claim so retries can re-attempt; permanent successes are never overwritten.
- The queue acks on success and on confirmed duplicate, and retries only transient errors.
- Rows expire past the retry-plus-replay window.
Get those six right and a double-click, a redelivery, and a double-run all produce exactly one email. That is the entire job.
Can I skip building the dedupe ledger?
Yes. If you send through Tinbox, idempotency is already in the send endpoint, so you do not own a dedupe table at all. Pass an idempotency_key in the request body and a repeat of the same key returns the original outcome with each recipient marked duplicate instead of dispatching again:
const res = await fetch("https://mail.example.com/api/send/emails", {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${env.TINBOX_KEY}`, // tbx_...
},
body: JSON.stringify({
from: "receipts@example.com",
to: "buyer@acme.test",
subject: "Your receipt",
html: "<p>Thanks for your order.</p>",
idempotency_key: "order:8421:receipt",
}),
});
const out = await res.json();
// First call: recipients: [{ email: "buyer@acme.test", status: "sent" }]
// Retry: recipients: [{ email: "buyer@acme.test", status: "duplicate" }]
The @tinbox/sdk client sends idempotency_key in the JSON request body. The dedupe ledger, the suppression check, and the per-recipient outcome all live inside a Worker on your own Cloudflare account against your own D1, so there is no second vendor in the path and no per-email price on top of this safety net. The send recipe itself is in sending your first email with the tinbox/cf library, and the broader sender story is in why transactional email shouldn't be metered per message.
That said: the hand-rolled version above is not throwaway work. Even on Tinbox you want the event that triggers the send to carry a stable key, and understanding why turns "we get occasional duplicate emails" from a mystery into a one-line fix.
Deploy this yourself: npx tinbox init <domain>, then send with an idempotency_key and watch the second attempt come back as duplicate. The send API and its idempotency behavior are documented in the Tinbox docs under sending.
Frequently asked questions
What is an idempotency key for email sending?
An idempotency key is a stable identifier you attach to a logical email so that sending the same key twice produces one delivery, not two. It should be derived from the event that caused the email (order id, invoice id, signup id) plus the email's purpose, not generated fresh per attempt, so every retry of the same event carries the same key.
How do I prevent duplicate emails when a queue retries?
Record the idempotency key in a database with a unique constraint before you dispatch, inside the consumer. On each delivery attempt, try to claim the key with an atomic insert. If the insert succeeds you are the first to handle it, so send. If it conflicts, a previous attempt already sent, so acknowledge the message and skip. This makes retries safe even when the original attempt's ack was lost.
Why isn't a queue's at-least-once delivery enough to avoid duplicates?
Cloudflare Queues, like most queues, guarantee at-least-once delivery, not exactly-once. A consumer can finish a send and then crash before its ack lands, so the message is redelivered and sent again. Idempotency is the application-level fix: the queue may deliver twice, but your dedupe check ensures the email goes out once.
Should the idempotency key be random or derived?
Derived. A random UUID generated at send time changes on every retry, so it can never dedupe anything. The key must be a deterministic function of the triggering event, for example order:8421:receipt, so that two attempts to send the same receipt collide on the same key.
How long should I keep idempotency records?
Keep them at least as long as the maximum window in which a duplicate could plausibly arrive, which is the queue's max retry age plus any manual replay window. A few days to a couple of weeks is typical. You can expire older rows on a cron, since an event from a month ago will not be retried.
Does Tinbox require me to build my own dedupe table?
No. The /api/send/emails endpoint accepts an idempotency_key in the body. A repeat of the same key returns the original send's outcome with each recipient marked duplicate instead of dispatching again, so queue retries and cron reruns are safe without your own ledger.