Architecture
Calls that must never fail the user
A confirmation email should not be able to undo a contest entry. Best-effort integrations, idempotency keys that make retries safe, and a compare-and-swap claim so two workers cannot send the same message twice.
A visitor enters a contest. The handler writes the entry, then sends a confirmation email, then adds them to the marketing pool. Three steps, one request, and the obvious implementation awaits all three and returns success.
Then the email provider has a bad afternoon. The entry is written, the email throws, the handler returns a 500, and the visitor sees an error and enters again. They are now in the draw twice, they believe they are in it zero times, and the thing that broke was the least important step of the three.
This is about the two mechanisms that stop that: deciding which calls are allowed to fail, and making the ones that retry safe to retry.
Order by importance, and let the tail fail
The entry is the thing the visitor came to do. Everything after it is bookkeeping, and bookkeeping must not be able to undo the primary action:
const registration = await prisma.contestRegistration.create({ /* ... */ })
// Emails are best effort: the entry is already saved, and a failure is
// recorded on the row for the admin to chase.
try {
await sendRegistrationEmail(contest, registration)
} catch (err) {
req.log.error({ err }, "contest confirmation email failed")
}
// Same treatment for the marketing pool: an entry that is already in the
// draw must not be undone by a deduplication problem.
try {
await addToMarketingPool(registration)
} catch (err) {
req.log.error({ err }, "marketing pool sync failed")
}The shape is simple: do the important thing first and unconditionally, then attempt the rest inside catches that log and continue.
Two things make this legitimate rather than lazy. The failure is logged with enough context to find the affected record, so the outcome is a chaseable gap rather than a silent one. And the ordering is deliberate: anything whose failure should abort the request has to run before the primary write, not after it.
For every external call in a request handler, ask: if this fails, should the user's action be undone? For confirmation emails, analytics, CRM syncs and webhooks, the answer is almost always no, and awaiting them in the critical path says yes.
This is a lighter alternative to a transactional outbox, and it is worth being clear about the trade. An outbox writes the intent to send in the same transaction as the entry and lets a worker deliver it, which guarantees the email is eventually sent. Swallowing the error guarantees only that the entry survives. For a confirmation email that a human can resend from the admin panel, that is a reasonable place to stop. For anything where the follow-up action is load-bearing, it is not, and you want the outbox.
Anything that retries needs an idempotency key
The campaign sender is the harder case. It delivers to thousands of recipients over hours, across restarts and deploys, and it must not send anyone the same message twice.
The core difficulty is that a network failure is ambiguous. A timeout after the provider accepted the message is indistinguishable, from your side, from a timeout before it did. Retry and you might duplicate. Do not retry and you might drop. There is no way to tell which, so the answer is to make the question irrelevant:
await sendEmail({
// ...
headers: {
"List-Unsubscribe": `<${oneClickUrl(lead.unsubscribeToken, campaign.id)}>`,
"List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
},
// Stable across restarts, so the reclaim above cannot double-send.
idempotencyKey: `mc-${campaign.id}-${next.id}`,
})The key is derived from what the message is, campaign plus recipient, rather than from when it was attempted. A random UUID generated per attempt would be useless: the retry would carry a different key and the provider would treat it as a new message.
That is the whole idea and it is easy to get subtly wrong. The key must be a function of the intent, so that every attempt at the same intent produces the same key, forever, including after a restart that lost all in-memory state.
One thing the key does not do: it makes retries safe, not correct. If the provider deduplicates on it, you avoid the duplicate; you still do not know whether the original was delivered. That is why the record's status is the source of truth locally, and the key only protects the provider side.
Claiming work with a conditional update
Before sending, a worker has to take ownership of a recipient in a way that another worker cannot also take. The naive version reads a queued row and then updates it, which is the same read-then-write race as any other check-then-act.
Instead the claim is a single conditional update, and the number of rows it touched is the answer:
const claim = await prisma.marketingCampaignRecipient.updateMany({
where: { /* id, and status: "queued" */ },
data: { status: "sending", claimedAt: new Date(), attempts: { increment: 1 } },
})
// If this did not match exactly one row, something else took the slot.Because the predicate includes the status the worker expects to find, only one of two concurrent claims can match. The loser sees zero rows updated and moves on. This is compare-and-swap, expressed in SQL, and it needs no locks, no external coordination and no queue system.
The same pattern guards the daily counter rollover, which is a nice illustration of how general it is:
// Roll the daily counter over. Conditional on the old value so two ticks
// cannot both reset it.
await prisma.marketingCampaign.updateMany({
where: { id: campaign.id, sendDay: campaign.sendDay },
data: { sendDay: dayKey, sentToday: 0 },
})Without the old value in the predicate, two workers crossing midnight together would both reset the counter, and the campaign would send twice its daily cap. Including it means the second update matches nothing.
Claimed work has to be reclaimable
A row marked sending belongs to a worker. If that worker is killed mid-send, by a deploy, an out-of-memory kill, or a host disappearing, the row stays sending forever and that recipient is never contacted. Every claim-based queue needs a way out of this:
const RECLAIM_AFTER_MS = 5 * 60_000
const result = await prisma.marketingCampaignRecipient.updateMany({
where: { status: "sending", claimedAt: { lt: new Date(Date.now() - RECLAIM_AFTER_MS) } },
data: { status: "queued", claimedAt: null },
})
if (result.count > 0) {
// Safe to retry: the send carries a stable idempotency key, so a message
// the provider already accepted is not sent twice.
log?.warn({ count: result.count }, "reclaimed stuck campaign recipients")
}This is where the two mechanisms meet. Reclaiming stuck work means re-sending things that may already have been sent, which would be unacceptable for marketing email. It is acceptable here precisely because the idempotency key makes a duplicate attempt harmless. Neither mechanism is safe alone; together they are.
The timeout has to exceed the longest legitimate send by a wide margin. Set it too low and you reclaim work that is still in flight, which turns a slow provider into a storm of duplicate attempts. Five minutes for a call that normally takes under a second is not paranoid.
Not every failure deserves the same response
Blanket exponential backoff treats every error the same way, and errors are not the same.
An invalid address will never succeed, so retrying it three times wastes attempts and delays the queue. A quota exhaustion will succeed later, and is not this recipient's fault. Charging it a retry punishes the wrong record:
// A spent quota is not this address's fault. Put it back untouched and wait,
// rather than burning its retries on something that cannot succeed yet.
if (QUOTA.has(code)) {
await prisma.$transaction([
prisma.marketingCampaignRecipient.update({
where: { id: recipientId },
data: { status: "queued", claimedAt: null, attempts: attempts - 1, lastError: message },
}),
prisma.marketingCampaign.update({
where: { id: campaign.id },
data: { sentToday: { decrement: 1 } },
}),
])
return 15 * 60_000
}
const permanent = PERMANENT.has(code) || attempts >= RETRY_DELAYS_MS.length
const delay = RETRY_DELAYS_MS[Math.min(attempts, RETRY_DELAYS_MS.length) - 1]Three behaviours from one handler. A quota error decrements the attempt count, so the recipient is returned exactly as it was found, and also decrements the campaign's daily counter, because a send that did not happen must not consume the cap. A permanent error fails the row immediately with the reason recorded. Everything else is retried on a schedule until the attempts run out.
Both the decrement and the counter adjustment happen in one transaction, because a crash between them would leave the campaign believing it had sent something it had not.
And every terminal state records lastError. A queue where failures are invisible is a queue nobody trusts, and the first question about any stuck campaign is which ones failed and why.
The dry run that lies consistently
One small design decision worth stealing. A dry run marks recipients sent exactly as a real send does, rather than taking a separate path.
That means the state machine, the claiming, the pacing and the counters are all exercised identically. A test that skips the bookkeeping tests only the part you were least worried about, and the bugs in a queue like this are all in the bookkeeping.
What to take from this
- Do the user's action first and unconditionally. Anything after it goes in a catch that logs and continues.
- Log best-effort failures with enough context to find the record, so the gap is chaseable rather than silent.
- Reach for an outbox when the follow-up action is load-bearing. Swallowing the error only protects the primary write.
- Derive idempotency keys from what the message is, never from when it was attempted.
- Claim work with a conditional update whose predicate includes the expected current state, and check the row count.
- Use the same compare-and-swap for counter rollovers, or two workers will both reset them.
- Reclaim work stuck in an in-flight state, with a timeout far longer than the longest legitimate operation.
- Only reclaim if the operation is idempotent. The two mechanisms are safe together and neither is safe alone.
- Classify errors. Quota, permanent and transient failures deserve three different responses.
- Record the last error on every terminal state.
- Make dry runs follow the identical code path, so the bookkeeping is what gets tested.
The single idea underneath is that distributed work has no way to distinguish did not happen from happened but I did not hear about it. You cannot resolve that ambiguity, so you build systems where it does not matter: safe to retry, safe to resume, and honest about what failed. The platform this runs inside is written up in the Synerggy Events case study.