An at-least-once queue plus a forward-only status column gives you effectively-once delivery — and the reason you still need that even when your provider has a whole delivery team.
The Problem
Your signup handler is short, readable, and wrong in a way that only shows up on a bad day.
import { render } from "react-email"; import VerifyMail from "@/mail/templates/verify-mail"; export async function POST({ request }: { request: Request }) { const body = await request.json(); const user = await createUser(body); await resend.emails.send({ from: "Ledger <hello@ledger.dev>", to: user.email, subject: "Verify your email", html: await render(<VerifyMail verifyUrl={makeUrl(user)} />), }); return Response.json({ id: user.id }); } Most days this works. Then Resend has a slow minute, the call takes four seconds, the Worker's request budget runs out, and the user sees a 500 after their row was already committed. They retry, and now two verification emails exist. On another day the provider accepts the mail and the response is lost in transit; your code throws, the user retries, and they get the same email twice. On launch day, an import of four thousand users fires four thousand sends inside four hundred requests, and the provider starts answering 429.
Three fixes come to mind, and each one moves the problem.
- Wrap the send in
try/catchand log it. The user still waits for the provider, the request still dies on timeout, and a logged failure is not a sent email.
try { await resend.emails.send(payload); } catch (error) { console.error("send failed", error); } - Retry the send three times in the handler. Every retry multiplies the chance of a duplicate, because a timeout tells you nothing about whether the provider accepted the message. You have turned one unreliable call into three.
for (let attempt = 0; attempt < 3; attempt++) { try { return await resend.emails.send(payload); } catch { // swallow and try again } } - Fire and forget with
waitUntil. The response returns fast, but nothing records what was attempted. A deploy mid-flight, a crash, or an exhausted subrequest budget loses the mail silently, and there is no row to reconcile later.
ctx.waitUntil(resend.emails.send(payload)); You need the send to survive a dead request without ever producing two copies, and a queue gives you the first half while making the second half worse unless something durable remembers what already happened.
The shape of the fix is a row written before the send, a message that carries only its id, and a consumer that refuses to move backwards:
// 1. Commit the receipt: address, content, and a fresh id. const email = await insertEmail(db, { to, subject, html, text }); // 2. Queue only the id. Never the content. await env.EMAIL_QUEUE.send({ version: 1, emailId: email.id, queuedAt: Date.now(), }); The Mental Model
Think of a post office with a numbered receipt book.
- Identity: the D1 row is the receipt. It exists before the letter leaves, carries the address and content, and gets a unique number the moment it is written. The queue message holds only that number.
- Update timing: the queue is the clerk's tray.
ack()means the letter left the building;retry()means it goes back in the tray. The tray can hand you the same slip twice — that is the queue's contract, not a bug. - Read timing: the consumer reads the receipt's status before sending, and the status only moves forward. A slip that comes back after the letter is already delivered finds
deliveredand does nothing.
Two consequences. First, the provider is never the source of truth about your intent; your ledger is. Second, every improvement to reliability has to be a stronger status rule, not a longer try/catch.
A queue guarantees the work arrives; only the ledger decides whether it runs.
How to Use It
This builds on the D1 + Drizzle workflow where one schema drives local, staging, and production, and only Wrangler applies migrations. If any of that is new, read Drizzle D1 Workflow: Local Migrations That Match Prod first; this article assumes the binding, the client, and the migration ledger are already in place.
Imports below use @/, which maps to src/. Swap in whatever alias your project uses, or switch to relative paths.
pnpm add drizzle-orm resend worker-mailer zod pnpm add -D drizzle-kit wrangler @libsql/client tsx src/ ├── db/ │ ├── client.ts │ └── schema.ts ├── mail/ │ ├── status.ts │ ├── types.ts │ ├── transport.ts │ ├── enqueue.ts │ ├── mail-service.tsx │ └── consumer.ts └── worker.tsx drizzle.config.ts docker-compose.yml wrangler.jsonc wrangler.jsonc — the binding, the producer, and the consumer in one file:
{ "compatibility_date": "2026-11-17", "compatibility_flags": ["nodejs_compat"], "main": "src/worker.tsx", "d1_databases": [ { "binding": "DB", "database_name": "db-local", "database_id": "00000000-0000-0000-0000-000000000000", "migrations_dir": "migrations", "migrations_table": "d1_migrations", }, ], "queues": { "producers": [{ "binding": "EMAIL_QUEUE", "queue": "mail-queue" }], "consumers": [ { "queue": "mail-queue", "max_batch_size": 10, "max_batch_timeout": 1, "max_retries": 5, "max_concurrency": 5, "dead_letter_queue": "mail-dlq", }, ], }, } The dead-letter queue is where a message lands after its last retry. Without it, a poison message disappears after max_retries and you cannot tell a duplicate from a lost mail.
src/db/schema.ts — the receipt:
import { sql } from "drizzle-orm"; import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; export const EmailTable = sqliteTable( "emails", { id: text("id") .primaryKey() .$defaultFn(() => crypto.randomUUID()) .notNull(), direction: text("direction", { enum: ["outbound", "inbound"] }) .notNull() .default("outbound"), status: text("status", { enum: [ "queued", "sending", "sent", "delivery_delayed", "delivered", "received", "bounced", "complained", "suppressed", "failed", ], }) .notNull() .default("queued"), from: text("from_address").notNull(), to: text("to_address").notNull(), subject: text("subject").notNull(), html: text("html_body"), text: text("text_body"), providerId: text("provider_id"), providerMessageId: text("provider_message_id"), attempts: integer("attempts").notNull().default(0), lastError: text("last_error"), createdAt: integer("created_at", { mode: "timestamp_ms" }) .notNull() .default(sql`(unixepoch() * 1000)`), }, (table) => [ index("email_status_idx").on(table.status), index("email_provider_id_idx").on(table.providerId), ] ); export type EmailRow = typeof EmailTable.$inferSelect; providerId is the provider's own id (Resend's re_...). It has no unique constraint here because worker-mailer returns a random UUID that is not a provider id; keep the guard on status, and treat providerId as an index for webhook lookups.
src/db/client.ts — the binding, never a URL:
import { type AnyD1Database, drizzle } from "drizzle-orm/d1"; import * as schema from "./schema"; export type Database = ReturnType<typeof createDb>; export function createDb(binding: AnyD1Database) { return drizzle(binding, { schema }); } src/mail/status.ts — one ranking, both the queue and the webhook use it:
export type EmailStatus = | "queued" | "sending" | "sent" | "delivery_delayed" | "delivered" | "received" | "bounced" | "complained" | "suppressed" | "failed"; export const STATUS_RANK: Record<EmailStatus, number> = { queued: 0, sending: 1, sent: 2, delivery_delayed: 3, delivered: 4, received: 4, bounced: 5, complained: 5, suppressed: 5, failed: 5, }; export function statusesAtOrAbove(status: EmailStatus): EmailStatus[] { const rank = STATUS_RANK[status]; return (Object.keys(STATUS_RANK) as EmailStatus[]).filter( (candidate) => STATUS_RANK[candidate] >= rank ); } src/mail/types.ts — a small, closed envelope:
import { z } from "zod"; export const mailJobSchema = z.object({ version: z.literal(1).default(1), emailId: z.uuid(), queuedAt: z.number().int().nonnegative(), }); export type MailJob = z.infer<typeof mailJobSchema>; export interface OutgoingMail { from: string; to: string; subject: string; html?: string; text?: string; } export interface SendOptions { /** Stable across retries so the provider can deduplicate. */ idempotencyKey?: string; } export interface Transport { send: (mail: OutgoingMail, options?: SendOptions) => Promise<string>; } The envelope has no HTML in it. Queue messages have a size ceiling and every byte is retained until ack, so the content stays in D1 and the message stays small.
src/mail/transport.ts — Resend when a key exists, SMTP otherwise:
import { Resend, type CreateEmailOptions } from "resend"; import { WorkerMailer } from "worker-mailer"; import type { OutgoingMail, Transport } from "./types"; export interface TransportEnv { RESEND_API_KEY?: string; RESEND_BASE_URL?: string; SMTP_HOST?: string; SMTP_PORT?: string; SMTP_USERNAME?: string; SMTP_PASSWORD?: string; } export function createTransport(env: TransportEnv): Transport { const apiKey = env.RESEND_API_KEY?.trim(); if (apiKey) { const resend = new Resend( apiKey, env.RESEND_BASE_URL ? { baseUrl: env.RESEND_BASE_URL } : undefined ); return { async send(mail, options) { // Resend's type requires at least one body, so narrow before building // the payload instead of passing the loose transport shape through. const body = mail.html ? { html: mail.html, text: mail.text } : { text: mail.text ?? "" }; const payload: CreateEmailOptions = { from: mail.from, to: mail.to, subject: mail.subject, ...body, }; const { data, error } = await resend.emails.send(payload, { idempotencyKey: options?.idempotencyKey, }); if (!data) throw new Error(error.message); return data.id; }, }; } const { SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD } = env; if (!SMTP_HOST || !SMTP_PORT || !SMTP_USERNAME || !SMTP_PASSWORD) { throw new Error("Set RESEND_API_KEY or all four SMTP_* variables."); } const options = { host: SMTP_HOST, port: Number(SMTP_PORT), secure: Number(SMTP_PORT) === 465, credentials: { username: SMTP_USERNAME, password: SMTP_PASSWORD }, }; return { async send(mail) { // SMTP has no idempotency key; retries past this point can duplicate. const mailer = await WorkerMailer.connect(options); try { await mailer.send(mail); return crypto.randomUUID(); } finally { await mailer.close(); } }, }; } worker-mailer opens an outbound TCP socket with cloudflare:sockets, which is why nodejs_compat is on and why it only runs inside a Worker, not in a browser bundle. Two consequences follow. It mints its own Message-ID, so the UUID this transport returns is a local handle, not the header a reply will quote — inbound threading only works end to end on the Resend path. And plain SMTP has no delivery webhook, so the row stops at sent: delivered and bounced stay unknown unless you route DSN bounces into a mailbox you parse.
src/mail/enqueue.ts — write the receipt, then the slip:
import { eq } from "drizzle-orm"; import { createDb } from "@/db/client"; import { EmailTable } from "@/db/schema"; import type { OutgoingMail } from "./types"; export interface Env { DB: D1Database; EMAIL_QUEUE: Queue; } export async function enqueueMail( env: Env, mail: OutgoingMail ): Promise<{ emailId: string }> { const db = createDb(env.DB); const [row] = await db .insert(EmailTable) .values({ direction: "outbound", status: "queued", from: mail.from, to: mail.to, subject: mail.subject, html: mail.html, text: mail.text, }) .returning({ id: EmailTable.id }); if (!row) throw new Error("Failed to persist email"); try { await env.EMAIL_QUEUE.send({ version: 1, emailId: row.id, queuedAt: Date.now(), }); } catch (error) { await db .update(EmailTable) .set({ status: "failed", lastError: String(error) }) .where(eq(EmailTable.id, row.id)); throw error; } return { emailId: row.id }; } src/mail/consumer.ts — the only place that sends:
import { and, eq, notInArray, sql } from "drizzle-orm"; import { createDb } from "@/db/client"; import { EmailTable } from<...


