
A small business sets up an automation: when someone fills in the contact form, a webhook fires, and a handler adds the lead to the CRM, sends them a welcome email and posts a message in the team's Slack channel. It works in testing. It works for the first week.
Then a lead complains that they got the welcome email three times. Slack shows the same lead three times. The CRM has two copies (the third request failed on a duplicate check someone added months ago, so nobody even noticed it).
Nobody changed the code. What changed was that the CRM got slow one afternoon. The handler took longer to finish than the form provider was willing to wait, so the provider decided the delivery had failed and sent it again. And again.
This series is about automations that keep working when the world around them misbehaves. Part 1 covers the first thing every automation touches: the webhook. The rule fits in one line: verify it, store it, acknowledge it, then do the work.
What the sender actually does
A webhook is just an HTTP POST from someone else's server to yours. What makes webhooks tricky is the sender's side of the deal, and it is roughly the same everywhere:
- It sends the event and waits a limited time for a response. The limit varies by provider and is often short.
- If you return a 2xx status in time, the delivery counts as a success.
- If you return anything else, or don't answer in time, it counts as a failure and the sender retries, usually several times with growing gaps.
- Retries mean the same event can arrive more than once. Even a successful delivery can be repeated, for example if your 200 response gets lost on the way back.
So your handler has two jobs that pull in opposite directions. It must answer fast, or you get retries. And it must not lose the event, because if you acknowledge it and then crash, the sender will never send it again.
The pattern that satisfies both is to split the handler in two.

The handler does three quick things: check the request is genuine, save the event, return 200. It never calls the CRM, the email service or Slack.
The worker picks up saved events and does the real work. If the CRM is slow, the worker is slow, and that's fine: nobody is waiting on an HTTP response. If the CRM is down, the worker retries later. The sender saw a 200 long ago and has moved on.
Step 1: verify the signature
Your webhook URL is public. Anyone who finds it can POST to it. If your handler trusts whatever arrives, anyone can create fake leads, trigger emails to arbitrary addresses, or worse.
Most providers sign each request. They compute an HMAC (a keyed hash) of the request body using a secret only you and they know, and send the result in a header. You recompute it and compare. If it matches, the request came from someone holding the secret, and the body wasn't changed in transit.
The exact header names and format differ between providers, so always check your provider's docs. A common shape is a timestamp plus a signature, with the signature computed over timestamp.body:
X-Signature: t=1760698800,v1=5f2b8c1e9a...Here is a verifier for that shape, in a Next.js route handler:
// app/api/webhooks/forms/route.ts
import { createHmac, timingSafeEqual } from "node:crypto";
const TOLERANCE_SECONDS = 300;
function verifySignature(rawBody: string, header: string | null, secret: string) {
if (!header) return false;
const parts = Object.fromEntries(
header.split(",").map((kv) => kv.split("=", 2) as [string, string]),
);
const timestamp = Number(parts.t);
const signature = parts.v1;
if (!timestamp || !signature) return false;
// Reject old requests so a captured request can't be replayed later.
const age = Math.abs(Date.now() / 1000 - timestamp);
if (age > TOLERANCE_SECONDS) return false;
const expected = createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex");
const a = Buffer.from(expected, "hex");
const b = Buffer.from(signature, "hex");
// timingSafeEqual throws on different lengths, so check first.
return a.length === b.length && timingSafeEqual(a, b);
}
export async function POST(request: Request) {
const secret = process.env.FORMS_WEBHOOK_SECRET;
if (!secret) {
console.error("FORMS_WEBHOOK_SECRET is not set");
return new Response("Server misconfigured", { status: 500 });
}
const rawBody = await request.text(); // raw text, NOT request.json()
if (!verifySignature(rawBody, request.headers.get("x-signature"), secret)) {
return new Response("Invalid signature", { status: 401 });
}
const event = JSON.parse(rawBody);
// ...store it (step 2), then return 200 (step 3)
}There are three bugs here that we see again and again. Each one either breaks verification for every request or quietly makes it useless.
Bug: verifying the parsed body
// Wrong: re-serialised JSON is not the same bytes the sender signed
const body = await request.json();
const expected = sign(JSON.stringify(body));The signature covers the exact bytes the sender sent. JSON.parse followed by JSON.stringify can change whitespace, key order, number formatting and Unicode escapes. The result *usually* matches in your tests and then fails for some real payloads. Always read the raw body as text, verify that, and only then parse it.
The same trap exists in frameworks that parse the body for you before your code runs. In Express, for example, a global express.json() middleware means the raw body is already gone by the time your route sees it. Use a raw body parser on webhook routes.
Bug: comparing with ===
// Wrong: leaks timing information
if (expected === signature) { ... }A normal string comparison stops at the first different character, so a wrong guess that starts with the right characters takes slightly longer to reject. With enough requests, an attacker can use that timing to work out a valid signature. timingSafeEqual always takes the same time. It needs two buffers of the same length, which is why the code above checks the lengths first.
Bug: no timestamp check
Without the timestamp check, anyone who captures one genuine request (from a log file, a proxy, a misconfigured debugging tool) can replay it forever, and it will verify every time. The tolerance window limits that to a few minutes. If verification fails for every request in production but works locally, check the server's clock before anything else.
Step 2: store the event before you answer
Once the request is verified, write it somewhere durable before responding. A database table works well, and it doubles as your audit log:
CREATE TABLE webhook_events (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
source TEXT NOT NULL, -- 'forms', 'stripe', ...
event_id TEXT NOT NULL, -- the provider's own ID for this event
payload JSONB NOT NULL,
status TEXT NOT NULL DEFAULT 'pending', -- pending | processing | done | failed
attempts INT NOT NULL DEFAULT 0,
last_error TEXT,
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX idx_webhook_events_source_event_id_unique
ON webhook_events (source, event_id);
CREATE INDEX idx_webhook_events_pending
ON webhook_events (next_attempt_at) WHERE status = 'pending';The unique index on (source, event_id) is doing quiet but important work. When the sender retries an event you already stored, the insert does nothing. That is the first line of defence against the triple-email bug, and Part 2 of this series builds on it.
In the handler:
const inserted = await db.query(
`INSERT INTO webhook_events (source, event_id, payload)
VALUES ('forms', $1, $2)
ON CONFLICT (source, event_id) DO NOTHING
RETURNING id`,
[event.id, rawBody],
);
if (inserted.rowCount === 0) {
// Seen it before. Still say 200, or the sender keeps retrying.
return new Response("Already received", { status: 200 });
}Use the provider's event ID if it sends one. If it doesn't, derive one from the content: a hash of the raw body is a reasonable fallback, as long as the provider doesn't put a fresh timestamp into every retry. If it does, hash only the fields that identify the event, such as the submission ID.
Step 3: acknowledge immediately
return new Response("OK", { status: 200 });
}That's the whole of step 3. Everything after this point happens in the worker.
A few rules about status codes, because getting them wrong causes retry storms:
- Return 2xx once the event is safely stored, including for duplicates you have already stored.
- Return 401 for bad signatures. The sender may retry these too, but you never want to accept them.
- Return 4xx for payloads you will never be able to process, such as an event type you don't handle. Some teams return 200 for unknown event types instead, so the sender doesn't keep retrying something that will never succeed. Either is fine. Pick one deliberately.
- Return 5xx only for genuine temporary failures on your side, such as the database being unreachable. That's exactly when you *want* the sender to retry.
Step 4: do the work in a worker
The worker is a loop that claims pending events, processes them and records the result. You can run it on a schedule (a cron job every minute), as a long-running process, or let a managed queue drive it. The shape is the same. Here is a version that runs against the table above:
const BATCH_SIZE = 20;
const MAX_ATTEMPTS = 8;
export async function processPendingEvents() {
// Claim a batch. SKIP LOCKED lets several workers run without grabbing the same rows.
const { rows } = await db.query(
`UPDATE webhook_events SET status = 'processing', attempts = attempts + 1, updated_at = NOW()
WHERE id IN (
SELECT id FROM webhook_events
WHERE status = 'pending' AND next_attempt_at <= NOW()
ORDER BY next_attempt_at
LIMIT $1
FOR UPDATE SKIP LOCKED
)
RETURNING id, payload, attempts`,
[BATCH_SIZE],
);
for (const row of rows) {
try {
await handleLead(row.payload); // CRM, email, Slack
await db.query(
`UPDATE webhook_events SET status = 'done', last_error = NULL, updated_at = NOW() WHERE id = $1`,
[row.id],
);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const giveUp = row.attempts >= MAX_ATTEMPTS;
await db.query(
`UPDATE webhook_events
SET status = $2, last_error = $3,
next_attempt_at = NOW() + make_interval(secs => $4), updated_at = NOW()
WHERE id = $1`,
[row.id, giveUp ? "failed" : "pending", message, retryDelaySeconds(row.attempts)],
);
console.error(`Event ${row.id} attempt ${row.attempts} failed: ${message}`);
}
}
}
// 30s, 60s, 120s ... capped at one hour.
const retryDelaySeconds = (attempt: number) => Math.min(3600, 30 * 2 ** (attempt - 1));Things worth noticing:
- One bad event doesn't block the rest. Each event has its own try/catch. Event 3 failing doesn't stop events 4 to 20.
- Failures are recorded with the error.
last_errorturns "the automation stopped working" into "the CRM returned 422: email is invalid for 4 events since Tuesday". - Retries back off. If the CRM is down, you don't hammer it every second. Part 2 goes deeper into backoff and which errors are worth retrying at all.
- There's a dead end. After
MAX_ATTEMPTS, the event is markedfailedand stops retrying. You need to know when that happens. A daily check onstatus = 'failed'that posts to your team channel is enough to start with. - Stuck events need a sweep. If the worker crashes halfway through a batch, those rows stay in
processingforever. A periodic query that resets rows stuck inprocessingfor more than, say, 15 minutes back topendingcovers it.
The worker alone doesn't fix the triple email. If handleLead sends the email and then the CRM call fails, the retry will send the email again. Making each side effect safe to repeat is the subject of Part 2.
Debugging webhooks locally
You can't fix what you can't reproduce, and webhooks are awkward to reproduce because someone else sends them. Two habits help.
Log the headers and a hash of the body for every request, especially rejected ones. When verification fails in production, the first question is always "did the request look like we expected?" Don't log the full body if it contains personal data. Log enough to correlate.
import { createHash } from "node:crypto";
console.info("webhook", {
path: new URL(request.url).pathname,
signature: request.headers.get("x-signature")?.slice(0, 24),
length: rawBody.length,
sha256: createHash("sha256").update(rawBody).digest("hex").slice(0, 16),
});Keep a script that sends a correctly signed test event to any URL. Then you can test your handler locally, on a preview deploy, and in production, with the exact signing scheme, without waiting for a real form submission:
// scripts/send-test-webhook.ts
// usage: FORMS_WEBHOOK_SECRET=... npx tsx scripts/send-test-webhook.ts http://localhost:3000/api/webhooks/forms
import { createHmac, randomUUID } from "node:crypto";
const url = process.argv[2];
const secret = process.env.FORMS_WEBHOOK_SECRET ?? "";
const body = JSON.stringify({
id: `evt_test_${randomUUID()}`,
type: "form.submitted",
data: { name: "Test Lead", email: "test@example.com", message: "Hello" },
});
const t = Math.floor(Date.now() / 1000);
const v1 = createHmac("sha256", secret).update(`${t}.${body}`).digest("hex");
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json", "x-signature": `t=${t},v1=${v1}` },
body,
});
console.log(res.status, await res.text());Run it twice with the same event ID and you have tested your duplicate handling too. Change one character of the body after signing and you have tested that tampered requests get a 401.
Checklist
For every webhook endpoint:
- Read the raw body as text. Verify the signature on those exact bytes before parsing.
- Compare signatures with
timingSafeEqualand check the timestamp. - Store the event with a unique index on the provider's event ID.
- Return 200 as soon as it's stored, including for duplicates.
- Do the slow work in a worker, never in the handler.
- Record attempts and errors per event, back off between retries, and stop after a limit.
- Get told about failed events. Don't find out from a customer.
- Keep a script that sends signed test events.
Next in this series: the sender *will* deliver some events twice, and your worker *will* retry some events after a partial failure. Part 2 is about idempotency: making every step safe to run more than once, so retries fix problems instead of creating them.


