Skip to content
All guides
Engineering10 min read

Never send an email twice: idempotent sending with Postgres and a job queue

A job queue delivers at least once. An email cannot be unsent. This is how day3 sits between those two facts: Postgres keeps a status row per email, workers claim rows atomically, and any failure where we cannot tell whether the mail left is final instead of retried.

The short version

  • Exactly-once delivery across a network is not on offer. What you can build is at most one attempt per ledger row, plus automatic recovery for everything provably unsent.
  • Postgres is the source of truth. Queue messages carry IDs only, so a retried or duplicated message re-reads state instead of replaying content.
  • Rows are claimed in one statement: UPDATE ... WHERE id IN (SELECT ... LIMIT n FOR UPDATE SKIP LOCKED). A retried job only sees rows still pending, and parallel lanes get disjoint slices.
  • Each row is stamped attempted_at immediately before the provider call. After a crash, the stamp separates "never tried" (safe to retry) from "may have left" (never retried).
  • SES errors are sorted by one question: did the request provably never reach SES? Only connection-phase failures and explicit refusals retry. Timeouts, resets and 5xx responses are terminal.
  • The cost: a crash or an ambiguous error can leave a recipient with zero emails instead of two. At most one recipient per lane per crash, and the row says so.

Queues retry. Emails can't be taken back.

day3 sends campaign, automation and transactional mail from a Node worker that drains a BullMQ queue in Redis. BullMQ, like most job queues, delivers at least once. A job that throws is retried with exponential backoff (5, 10, 20, 40 and 80 seconds, five attempts by default). A job whose worker stops renewing its lock is treated as stalled and handed out again. For most work that is what you want. For email it is a hazard, because the send is not idempotent: SES SendEmail takes no idempotency token, so calling it twice sends two emails.

So "exactly once" is not available end to end. If the process dies after SES accepted a message but before we wrote that down, nothing on our side can know for sure whether the email left. What we can promise is narrower: each email is attempted at most once, and every failure where we can prove nothing was sent recovers on its own.

The codebase states it as hard rule number one: a retried message must never duplicate an email send. A late email is recoverable. A duplicate password reset, or a newsletter that lands twice, is not.

Postgres holds the state, the queue holds IDs

Every email day3 intends to send is a row before it is a job. Campaign and automation sends live in campaign_recipients, one row per recipient, with a unique index on (campaign_id, email). Transactional mail lives in transactional_emails. The status column on those rows is the ledger: pending (or queued), then sending, then sent, failed or skipped.

Queue messages carry identifiers and nothing else. The worker validates each one against a Zod schema before dispatch, because job data crosses a trust boundary: an older producer, an operator replay, a hand-written message.

The two send messages, from src/queue/messages.ts (simplified)
z.object({
  type: z.literal("send_campaign_batch"),
  campaignId: id,
  accountId: id,
  batchSize: z.number(),
}),
z.object({ type: z.literal("send_transactional"), emailId: id, accountId: id }),

This is what makes a duplicate message harmless. A job never says "send this email to this address". It says "go and look at campaign X". If X is no longer in status sending, the handler logs the message as stale and returns. If it is, the handler asks Postgres which rows are still unsent, and works on those only.

Claiming rows: one UPDATE with SKIP LOCKED

A batch job does not read pending rows and then send them. It flips them to sending and gets them back in the same statement, so no other worker can slip in between the read and the claim.

The claim, as SQL (the code builds it with Drizzle)
UPDATE campaign_recipients
SET status = 'sending', locked_at = $now, attempted_at = NULL
WHERE id IN (
  SELECT id FROM campaign_recipients
  WHERE campaign_id = $campaign AND status = 'pending'
  LIMIT $n
  FOR UPDATE SKIP LOCKED
)
RETURNING *;

Three parts do the work:

  • The status filter. A retried job runs the same statement and can only see rows that are still pending. Rows an earlier attempt already sent, or is still sending, are invisible to it.
  • FOR UPDATE SKIP LOCKED. day3 fans a campaign out to 8 lanes by default, each a self-chaining batch job of 100 recipients. When two lanes claim at the same moment, the inner SELECT locks the rows it picks and the other lane skips them instead of waiting. Each lane gets a disjoint slice and nobody blocks.
  • RETURNING. The worker sends exactly the rows the database handed back, never a list it computed earlier.

There is no ORDER BY. Every recipient of a campaign is inserted with the same created_at, so ordering bought nothing and made Postgres sort the remaining pending rows on every claim.

Before claiming, the batch reserves monthly quota in one conditional statement that caps at the limit (LEAST(count + n, limit)). Two workers reading a nearly exhausted account split the remaining headroom instead of both taking it. Whatever slice the batch could not fill with real rows is released afterwards.

Stamping the attempt before the call

Claiming solves retries. It does not solve crashes. If the worker is killed with 100 rows in sending, which of them went out?

Without more information the safe answer is "any of them", and an earlier version of day3 acted on exactly that: a crash failed every claimed row, up to 8 lanes times 100 recipients. Now each lane sends serially and writes one more thing right before each provider call.

From src/queue/handlers/send-batch.ts (simplified)
const stamped = await db
  .update(campaignRecipients)
  .set({ attemptedAt: nowIso() })
  .where(and(
    eq(campaignRecipients.id, recipient.id),
    eq(campaignRecipients.status, "sending"),
  ))
  .returning({ id: campaignRecipients.id });

if (stamped.length === 0) continue; // no longer ours: do not send

const result = await emailProvider.send({ /* ... */ });

The guard on status = 'sending' matters as much as the stamp. If the batch stalled long enough for the recovery sweep to take the row, the update returns nothing and the email is not sent. The ledger and the mailbox can disagree, but never in the direction that produces a duplicate.

After a crash, a row in sending without attempted_at provably never reached SES. A row with it may have. Because each lane sends one recipient at a time, at most one row per lane can be in the second state.

Sorting SES errors: provably unsent, or maybe sent

One question decides what happens to every error: did this request provably never reach SES? Only a yes allows a retry.

The first place this shows up is the AWS SDK. Its default retry policy (three attempts) re-sends when a response is lost after SES accepted the message, and that duplicate would never appear in our ledger. So the SES client runs with maxAttempts: 1, a 3-second connection timeout and a 15-second request timeout. Retry policy lives in the send handler, where the ledger can see it.

Error classification, from src/email/ses.ts (simplified)
const UNSENT_NETWORK_CODES = new Set([
  "ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH",
]);

// No HTTP status and a never-connected code: the request never left this host.
if (httpStatus === undefined && UNSENT_NETWORK_CODES.has(code)) {
  return { status: "transient" };
}

switch (name) {
  case "TooManyRequestsException":
  case "LimitExceededException":
    return { status: "rate_limited" }; // SES refused before sending
  case "MessageRejected":
    return { status: "failed" };       // SES said no to this message
  default:
    // TimeoutError, ECONNRESET, any 5xx: the email may already be queued at SES.
    return { status: "failed" };
}
What each outcome does to the batch
OutcomeExampleWhat happens
transientDNS failure, connection refusedThis row and the rest of the batch go back to pending. The job throws and BullMQ retries it with backoff.
rate_limitedSES throttle, daily quota, sending pausedThe remainder goes back to pending, the campaign pauses with a machine-readable code, and the sweep resumes it.
failedTimeout, connection reset, 5xx, rejected messageTerminal for this one recipient. Never retried.

Failing recipients one by one would burn a whole audience if the cause is global, such as a missing configuration set. So a circuit breaker pauses the campaign after 10 consecutive identical failures and hands the untouched rows back to pending.

The sweep that cleans up after a crash

A cron sweep runs every 15 minutes. One of its jobs is rows stuck in sending whose locked_at is more than 15 minutes old. Live batches re-stamp locked_at every 5 minutes, so a slow batch is never mistaken for a dead one.

The stuck-row rule, from src/queue/cron.ts, as SQL
UPDATE campaign_recipients
SET status = 'failed', error = 'send attempt did not complete (stuck lock)'
WHERE status = 'sending' AND locked_at < $cutoff
  AND attempted_at IS NOT NULL;

UPDATE campaign_recipients
SET status = 'pending', locked_at = NULL, attempted_at = NULL
WHERE status = 'sending' AND locked_at < $cutoff
  AND attempted_at IS NULL;

The same sweep then finds a campaign with pending rows and nothing in flight, and fans it out again at full lane width. The quota held for every stuck row is released. The one attempted row per lane may in fact have been delivered, so the usage counter can under-count by that much per crash. We take that over charging twice.

Transactional mail follows the same rule. A row stuck in sending is failed. A row still queued with no live job is re-enqueued, which is safe because the handler's claim (queued to sending) turns a duplicate job into a no-op. A row still queued after 6 hours is failed loudly instead of delivered very late.

The failure modes, one by one

What each failure costs a recipient
FailureWhat the system doesWorst case
Worker killed mid-batch (OOM, reboot)After 15 minutes, unattempted rows return to pending and the campaign fans out again. The attempted row is failed.One recipient per lane gets nothing. Nobody gets two.
BullMQ retries a job that half ranThe retry claims only rows still pending.Nothing.
The same job is enqueued twiceBoth run the claim. SKIP LOCKED gives them disjoint rows, so they behave as two lanes. A job for a campaign no longer sending drops itself.Nothing.
Recipient generation runs twiceInserts use ON CONFLICT DO NOTHING against the unique (campaign_id, email) index, and only the run that flips the campaign to sending fans out lanes.Nothing.
Timeout after SES accepted the messageClassified as ambiguous. The row is failed and never retried.Zero emails, where one may actually have arrived.
Connection never establishedRows back to pending, job retried with backoff.A delay of seconds.
Deploy (SIGTERM)The batch stops between recipients and hands the remainder back to pending.A pause of a few seconds.
Redis restarts emptyEvery row is still in Postgres. The sweep re-enqueues stranded transactional rows and re-fans stalled campaigns.Up to 15 minutes late.

The API path: an Idempotency-Key, claimed first

POST /v1/emails has one failure mode the worker does not: the client's own retry. A request times out on the client side, the client sends it again, and both copies arrive.

The Idempotency-Key header is handled with a claim too. Before the handler runs, a row goes into idempotency_keys under a unique index on account, endpoint and key. The loser of a race gets a 409 while the winner is in progress, and a replay of the stored response once it has finished. The same key with a different body is rejected. The email row and the completed claim are written in one transaction, so a crash leaves either no email (the retry runs again) or a stored response (the retry replays). Never an email the caller was told nothing about.

The row is committed before the job is enqueued. If Redis is unreachable at that moment, the caller still gets a 200 with status queued, and the sweep enqueues the job later. Delayed, never lost, never duplicated.

Pacing and the shared daily ceiling

Two more limits sit between the ledger and SES. Both push back through the paths that already exist instead of adding new ones.

  • Per-second rate. SES limits the AWS account to a number of sends per second. Every send goes through a GCRA limiter held in Redis and wrapped around the provider, so campaign lanes, transactional sends and form confirmations all draw from one budget. It targets 90% of the rate SES reports, re-read hourly because AWS raises it as reputation builds. If Redis does not answer within 2 seconds, it fails open and sends unpaced.
  • 24-hour ceiling. SES also caps the account per rolling 24 hours, and that cliff would stop every customer at once. A daily budget holds back the larger of 500 emails or 2% of the ceiling for transactional mail, and refuses campaign and automation sends that would eat into it. Transactional is never refused here, because someone is waiting for that signup confirmation.

The budget's refusal reuses the exact rate_limited result SES returns for its own daily limit. The send handler needs no new branch: the batch goes back to pending, the campaign pauses with daily_limit, and the sweep resumes it once there is real headroom. A refusal is always provably unsent, which is the only kind of outcome allowed to retry.

The trade-off, stated plainly

This design picks a side. When we cannot tell whether an email left, the recipient may get zero copies instead of two. That is a real cost. It is the right one for three reasons.

  • A duplicate cannot be repaired. Two password resets, two receipts or the same newsletter twice is visible to the recipient and to the mailbox provider. Duplicates draw complaints, and complaint rate is the number that gets a sender filtered.
  • A missing email can be. A failed row is visible. Over the API, GET /v1/emails/{id} returns failed and the caller can resend deliberately. In a campaign, the recipient list shows the reason "send attempt did not complete".
  • The cost is bounded. Ambiguous errors are rare, and a crash costs at most one recipient per lane: 8 at the default settings, against a claimed batch that could otherwise be 800.

The other honest caveat: failed can be wrong in the opposite direction. A row failed after a timeout may belong to an email SES did deliver. The status means "we will not retry this", not "this definitely did not arrive".

Where day3 fits

If you are building this yourself, the pattern is small: a status row per email, an atomic claim, a stamp before the side effect, and an error classifier that asks one question. If you would rather not, day3 is that pipeline with campaigns, automations and transactional mail on top, billed by emails sent from $1/mo. The API takes an Idempotency-Key on every send, and deliverability covers what happens after the email leaves.

Questions

Is exactly-once email delivery possible?
Not end to end. Sending an email is a call to a remote service, and if the response is lost you cannot know whether it was accepted. SES SendEmail takes no idempotency token. What you can guarantee is at most one attempt per email record, plus automatic retries for every failure where the request provably never arrived.
Does BullMQ guarantee a job runs only once?
No. BullMQ delivers at least once: failed jobs are retried, and a job whose worker stops renewing its lock is treated as stalled and run again. A custom job id can stop the same job being added twice, but it cannot stop a job running twice. Idempotency has to live in the handler, which is why day3 keys every send on a Postgres status row.
Why use FOR UPDATE SKIP LOCKED for a Postgres job queue?
It lets several workers claim work from the same table at once without blocking each other or picking the same rows. Each worker locks the rows its subquery selects, and the others skip locked rows instead of waiting. With a status filter in the same UPDATE, a claimed row can never be claimed again.
Why not retry a timeout from SES?
Because a timeout after the request was written tells you nothing about whether SES accepted it, and a retry would send a duplicate whenever it had. day3 only retries errors that prove the request never left, such as a refused connection or a DNS failure, and refusals where SES says it did not send, such as a throttle.
How many emails can a worker crash cost?
At most one recipient per send lane, because each lane sends serially and stamps every row right before its provider call. With the default 8 lanes that is 8 recipients, marked failed with the reason "send attempt did not complete". Every other claimed row returns to pending and goes out after the next sweep.
What does an Idempotency-Key do on POST /v1/emails?
It makes a client retry safe. The key is claimed in Postgres before the request is processed, so two requests with the same key produce one email. The second gets a 409 while the first is in progress, then a replay of the original response for 24 hours.

day3 handles all of this by default.

Authenticated domains, one-click unsubscribe, double opt-in, and automatic suppression. Billed by emails sent, from $1/month.