
In Part 1 we split our webhook handler in two. The handler verifies, stores and returns 200 straight away. A worker does the slow work and retries when something fails. We also put a unique index on the provider's event ID, so a redelivered event doesn't get stored twice.
That fixes half of the triple-email bug. Here is the half it doesn't fix.
The worker picks up a new lead. It sends the welcome email: success. It posts to Slack: success. It calls the CRM: timeout. The worker marks the event as failed and schedules a retry. Two minutes later the retry runs handleLead from the top. Welcome email again. Slack again. This time the CRM works. The lead now has two welcome emails, and if the CRM is having a bad day, it could be five.
Retries are how automations recover from failures. But a retry runs the whole job again, including the parts that already worked. Unless every step is safe to repeat, retries turn one failure into a pile of duplicates.
The property you want is called idempotency: doing something twice has the same effect as doing it once. This part shows how to get it, step by step, and how to retry without making things worse.

Duplicates come from three places
It helps to know where repeats come from, because each needs a slightly different defence.
- The sender redelivers. Webhook providers deliver *at least once*. They retry on timeouts and errors, and sometimes resend events that were actually received fine. The unique index from Part 1 handles this.
- Your worker retries. A job fails halfway and runs again from the start. Steps that already succeeded run a second time. This is the main subject of this post.
- Two workers grab the same job. A worker is slow, a sweep decides it's stuck and resets it, and now two workers are processing the same event at once.
FOR UPDATE SKIP LOCKEDfrom Part 1 prevents the common case. Idempotent steps make the rare case harmless.
Record each side effect
The simplest reliable approach is to keep a record of which steps have already been done for each event, and skip them on a retry:
CREATE TABLE event_effects (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
event_id UUID NOT NULL, -- webhook_events.id
effect TEXT NOT NULL, -- 'welcome_email', 'slack_post', 'crm_upsert'
result JSONB, -- e.g. the email provider's message ID
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX idx_event_effects_event_id_effect_unique
ON event_effects (event_id, effect);Then wrap each step in a helper that checks the record first and writes it after:
async function once<T>(
eventId: string,
effect: string,
run: () => Promise<T>,
): Promise<T | "skipped"> {
const done = await db.query(
`SELECT 1 FROM event_effects WHERE event_id = $1 AND effect = $2`,
[eventId, effect],
);
if (done.rowCount) return "skipped";
const result = await run();
await db.query(
`INSERT INTO event_effects (event_id, effect, result) VALUES ($1, $2, $3)
ON CONFLICT (event_id, effect) DO NOTHING`,
[eventId, effect, JSON.stringify(result ?? null)],
);
return result;
}
async function handleLead(eventId: string, lead: Lead) {
await once(eventId, "crm_upsert", () => crm.upsertContact(lead));
await once(eventId, "welcome_email", () => email.send(welcomeEmail(lead)));
await once(eventId, "slack_post", () => slack.post(`New lead: ${lead.name} (${lead.email})`));
}Now the retry from the opening goes differently. Email: already recorded, skipped. Slack: already recorded, skipped. CRM: runs. One email, one Slack post, one contact.
(The worker from Part 1 called handleLead(row.payload). It now passes row.id as well, so each step can be keyed to the stored event.)
Notice the order of the steps changed too. The CRM upsert now runs first. If it fails, nothing customer-facing has happened yet, and the retry starts clean. Put the steps a person will notice (emails, messages, charges) last, after the steps that are most likely to fail.
The gap you can't fully close
Look closely at once. There is a window between run() succeeding and the INSERT recording it. If the process crashes in that window, the email has gone out but there's no record, so the retry sends it again.
You can make the window tiny, but you can't make it zero, because the email service and your database can't commit together. So you have to choose which way to fail:
- Record after (as above): at least once. A crash in the window means a rare duplicate. Right for welcome emails, Slack posts and CRM updates, where a duplicate is a mild annoyance.
- Record before: at most once. Insert the record first, then run. A crash in the window means the step never happens. Right for things where a duplicate is worse than nothing, like sending a payment or an SMS that costs money, *if* you also alert on missing results.
Make that choice deliberately for each step and write it down in the code. Most of the time, at least once plus a downstream idempotency key (next section) gets you as close to exactly once as you can get.
Use idempotency keys downstream
Many APIs that create things, especially payment APIs, accept an idempotency key: a unique string you send with the request, usually in an Idempotency-Key header. If they see the same key again, they return the original result instead of doing the work a second time. That closes the crash window from their side.
Build the key from things that identify *this* effect for *this* event, never from something random per attempt:
// Same event + same effect = same key, on every retry.
const key = `lead-${eventId}-welcome-email`;
await fetch("https://api.example-mail.test/v1/send", {
method: "POST",
headers: {
authorization: `Bearer ${process.env.MAIL_API_KEY}`,
"content-type": "application/json",
"idempotency-key": key,
},
body: JSON.stringify(welcomeEmail(lead)),
});// Wrong: a fresh key per attempt defeats the whole point.
headers: { "idempotency-key": randomUUID() }Check your provider's docs for whether they support idempotency keys, what the header is called, and how long they remember keys. Support varies a lot. Where it's missing, there's often a natural alternative: an "upsert by email" endpoint on the CRM is idempotent by design, while "create contact" isn't.
Prefer operations that are naturally idempotent
Some operations are safe to repeat by nature. When you have a choice, pick those:
- Set, don't add.
status = 'contacted'is idempotent.follow_ups = follow_ups + 1isn't. - Upsert, don't insert. "Create or update the contact with this email" can run any number of times. "Create a contact" makes a new one every time.
- Use a stable ID from the source. If you create a record in your own database, key it on the form submission ID, with a unique index, and use
ON CONFLICT DO NOTHINGorDO UPDATE. - Overwrite whole files and documents rather than appending to them.
The more of your steps are naturally idempotent, the less bookkeeping you need.
Retry the right failures, the right way
Idempotency makes retries safe. It doesn't make them a good idea for every failure. Retrying an error that will never succeed just wastes time and fills logs. Split errors into two groups:
- Retry: network errors and timeouts, HTTP 429 (rate limited), and 5xx server errors. These are often temporary.
- Don't retry: most other 4xx responses. A 400 "invalid email" will be invalid on the tenth attempt too. Mark the event failed with the error, and alert.
When you do retry, back off. If a service is struggling, a crowd of clients retrying instantly keeps it down. Exponential backoff spaces attempts out. Jitter, a random spread, stops all your retries landing at the same moment:

class RetryableError extends Error {}
const BASE_DELAY_MS = 500;
const MAX_DELAY_MS = 30_000;
const MAX_ATTEMPTS = 5;
// "Full jitter": wait a random time between 0 and the exponential cap.
const backoff = (attempt: number) =>
Math.random() * Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
async function withRetry<T>(fn: () => Promise<T>): Promise<T> {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
const retryable = err instanceof RetryableError || isNetworkError(err);
if (!retryable || attempt + 1 >= MAX_ATTEMPTS) throw err;
await new Promise((r) => setTimeout(r, backoff(attempt)));
}
}
}
async function callApi(url: string, init: RequestInit) {
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(10_000) });
if (res.status === 429 || res.status >= 500) {
throw new RetryableError(`${res.status} from ${url}`);
}
if (!res.ok) {
throw new Error(`${res.status} from ${url}: ${await res.text()}`);
}
return res.json();
}
const isNetworkError = (err: unknown) =>
err instanceof TypeError || (err instanceof DOMException && err.name === "TimeoutError");A few details matter here:
- Every call has a timeout. Without
AbortSignal.timeout, a hung connection can block the worker indefinitely, and a hung call never gets retried. - Honour
Retry-Afterwhen it's there. Many APIs tell you how long to wait on a 429. If they do, use that instead of your own backoff. - Keep in-process retries short.
withRetrycovers blips of a second or two. Longer outages are handled by the worker's own schedule from Part 1, which retries the whole event minutes or hours later. Don't stack long sleeps inside a single run. - Stop eventually. After the last attempt the error goes up to the worker, which records it and eventually marks the event
failed. A failed event that someone looks at is far better than one that retries forever.
Test it by running everything twice
You don't know a step is idempotent until you've watched it run twice. The cheapest, most valuable test for an automation is: process the same event twice and check that each side effect happened exactly once.
import { beforeEach, describe, expect, it, vi } from "vitest";
describe("handleLead", () => {
const sent: unknown[] = [];
beforeEach(async () => {
sent.length = 0;
await db.query("TRUNCATE event_effects");
vi.spyOn(email, "send").mockImplementation(async (msg) => {
sent.push(msg);
return { id: "msg_1" };
});
vi.spyOn(slack, "post").mockResolvedValue({ ok: true });
});
it("sends one welcome email when the same event is processed twice", async () => {
vi.spyOn(crm, "upsertContact").mockResolvedValue({ id: "c_1" });
await handleLead("evt-1", lead);
await handleLead("evt-1", lead);
expect(sent).toHaveLength(1);
expect(slack.post).toHaveBeenCalledTimes(1);
});
it("does not repeat the email when a retry follows a CRM failure", async () => {
vi.spyOn(crm, "upsertContact").mockResolvedValue({ id: "c_1" });
vi.spyOn(slack, "post")
.mockRejectedValueOnce(new Error("Slack down")) // first run fails after the email
.mockResolvedValueOnce({ ok: true });
await expect(handleLead("evt-2", lead)).rejects.toThrow("Slack down");
await handleLead("evt-2", lead); // the retry
expect(sent).toHaveLength(1); // email not repeated
expect(slack.post).toHaveBeenCalledTimes(2); // Slack retried until it worked
});
});The second test is the one that matters most. It reproduces the exact failure from the opening: a step fails partway, the job retries, and we check that the steps before the failure didn't run again. Add a test like it for every automation that has more than one side effect.
You can do the same end to end with the signed test script from Part 1: send the same event ID twice, then check your inbox, your Slack channel and your CRM.
Checklist
For every automation that does more than one thing:
- Dedupe incoming events with a unique index on the source's event ID (Part 1).
- Record each completed side effect per event, and skip recorded effects on retry.
- Put customer-visible steps (emails, messages, charges) last.
- Decide per step whether a crash should mean a rare duplicate or a rare miss.
- Send stable idempotency keys to APIs that support them. Never random per attempt.
- Prefer set over add, upsert over insert, stable IDs over generated ones.
- Retry timeouts, 429s and 5xx with exponential backoff and jitter. Don't retry other 4xx.
- Give every external call a timeout.
- Test by processing the same event twice, and by failing a middle step and retrying.
Next in this series: you will still have failures, so you need to find out about them before your customers do. Part 3 covers observability for automations: what to log, which numbers to watch, and how to build a small dead-letter view that tells you what's broken and lets you replay it in one click.


