
In Part 1 we split the webhook handler from the worker and stored every event in a webhook_events table. In Part 2 we made every step safe to run twice, so retries fix problems instead of creating duplicates.
Your automation will still fail. An API changes a field name. A token expires on a Saturday. Someone renames a Slack channel. The question isn't whether it breaks, but who notices first: you, or a customer asking why nobody replied to their enquiry last Thursday.
This part is about noticing first. We'll add logs you can actually search, a handful of numbers that tell you whether the automation is healthy, alerts that fire when those numbers go wrong, and a small dead-letter view that shows what's broken and lets you replay it in one click.
None of this needs a monitoring product. Everything below runs on the table you already have.
Three ways an automation breaks
It helps to name the failure modes, because each one needs a different signal.
- Loud failures. A step throws, the worker records the error, retries, and eventually marks the event
failed. This is the easy case. The information is already in your table. You just need to look at it. - Silent stalls. Nothing fails, because nothing runs. The worker's cron job was removed in a deploy. The sender stopped delivering because someone rotated the webhook secret. The queue fills up, or stays empty, and no error is ever written anywhere.
- Wrong but successful. Every step returns 200, but the result is wrong. The CRM accepts a contact with an empty company name because the form field was renamed. The email goes out with "Hi undefined". The table says
done.
Most teams only watch for the first kind, if they watch at all. The second and third kinds are the ones that run for weeks before anyone notices.

Step 1: log every attempt, the same way
When something goes wrong, the first question is always "what happened to *this* event?" If your logs are a mix of console.log("done") and stack traces, you can't answer it.
Write one structured line per step, per attempt, always with the same fields. The event ID is the thread that ties them together:
type StepLog = {
eventId: string;
source: string;
attempt: number;
step: string; // 'crm_upsert', 'welcome_email', ...
outcome: "ok" | "skipped" | "error";
ms: number;
error?: string;
};
function logStep(entry: StepLog) {
// One JSON object per line: every log platform can filter and count these.
console.log(JSON.stringify({ at: new Date().toISOString(), kind: "automation_step", ...entry }));
}Then extend the once helper from Part 2 so every step reports itself:
async function once<T>(ctx: { eventId: string; source: string; attempt: number }, effect: string, run: () => Promise<T>) {
const started = Date.now();
const done = await db.query(
`SELECT 1 FROM event_effects WHERE event_id = $1 AND effect = $2`,
[ctx.eventId, effect],
);
if (done.rowCount) {
logStep({ ...ctx, step: effect, outcome: "skipped", ms: 0 });
return "skipped";
}
try {
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`,
[ctx.eventId, effect, JSON.stringify(result ?? null)],
);
logStep({ ...ctx, step: effect, outcome: "ok", ms: Date.now() - started });
return result;
} catch (err) {
const error = err instanceof Error ? err.message : String(err);
logStep({ ...ctx, step: effect, outcome: "error", ms: Date.now() - started, error });
throw err;
}
}Now a search for one event ID gives you its whole story: which steps ran on which attempt, which were skipped on the retry, how long each took and exactly what the failing one said.
A few rules keep these logs useful:
- Don't log personal data you don't need. Log the event ID and the step, not the customer's message. If you need the payload, it's already in
webhook_events, behind your database's access control. - Log
skippedtoo. When someone asks "did the retry send the email again?", askippedline is the proof that it didn't. - Keep error messages specific. "CRM returned 422: company is required" is a fix. "Request failed" is a mystery. When you throw, include the status and the start of the response body.
Step 2: five numbers that tell you it's healthy
Logs answer "what happened to this event?" Numbers answer "is anything wrong right now?" You only need five, and they all come from SQL you can run today.
1. Events received in the last hour. This catches the silent stall at the front door.
SELECT count(*) AS received_last_hour
FROM webhook_events
WHERE source = 'forms' AND created_at > NOW() - INTERVAL '1 hour';Zero isn't always a problem. Nobody fills in your contact form at 3am. But zero for a whole working day, when you normally get ten a day, almost always means the sender has stopped delivering.
2. Backlog, and the age of the oldest pending event. This catches a worker that isn't running or can't keep up.
SELECT count(*) AS pending,
EXTRACT(EPOCH FROM NOW() - min(created_at)) / 60 AS oldest_pending_minutes
FROM webhook_events
WHERE status IN ('pending', 'processing');Watch the age more than the count. Twenty pending events that are all ten seconds old is a busy minute. One pending event that's three hours old is a broken worker.
3. Failure rate. Of the attempts in the last hour, how many failed? This is easiest from the step logs if your log platform can count them. From the table alone, a close enough version is:
SELECT count(*) FILTER (WHERE last_error IS NOT NULL) AS with_errors,
count(*) AS total
FROM webhook_events
WHERE updated_at > NOW() - INTERVAL '1 hour';A few errors that clear on retry are normal. That's what retries are for. A rate that jumps from near zero to half means something downstream has changed.
4. Failed events. Events that used up all their attempts and stopped. These are your dead letters, and every one is a customer or a record that didn't get handled.
SELECT count(*) AS failed FROM webhook_events WHERE status = 'failed';5. Worker heartbeat. The worker writes a timestamp every time it runs, even when there's nothing to do. If the timestamp gets old, the worker has stopped, and none of the other numbers will tell you, because a stopped worker writes nothing.
CREATE TABLE heartbeats (
name TEXT PRIMARY KEY, -- 'forms-worker'
beat_at TIMESTAMPTZ NOT NULL
);export async function processPendingEvents() {
await db.query(
`INSERT INTO heartbeats (name, beat_at) VALUES ('forms-worker', NOW())
ON CONFLICT (name) DO UPDATE SET beat_at = EXCLUDED.beat_at`,
);
// ...claim and process a batch, as in Part 1
}Write the heartbeat at the start of the run, not the end. If a run hangs halfway, you want the stale heartbeat to show it.
Step 3: alerts that someone will read
Numbers on a page nobody opens don't help. Run a small check every five minutes that compares the numbers to limits and posts to your team channel when one is crossed.
const LIMITS = {
oldestPendingMinutes: 30,
heartbeatMinutes: 10,
failureRate: 0.25,
quietHoursWithoutEvents: 8,
};
type Problem = { key: string; message: string };
export async function checkAutomationHealth(): Promise<Problem[]> {
const problems: Problem[] = [];
const { rows: [q] } = await db.query(
`SELECT EXTRACT(EPOCH FROM NOW() - min(created_at)) / 60 AS oldest
FROM webhook_events WHERE status IN ('pending', 'processing')`,
);
if (q.oldest > LIMITS.oldestPendingMinutes) {
problems.push({ key: "backlog", message: `Oldest pending event is ${Math.round(q.oldest)} minutes old.` });
}
const { rows: [hb] } = await db.query(
`SELECT EXTRACT(EPOCH FROM NOW() - beat_at) / 60 AS age FROM heartbeats WHERE name = 'forms-worker'`,
);
if (!hb || hb.age > LIMITS.heartbeatMinutes) {
problems.push({ key: "heartbeat", message: "The forms worker hasn't run in the last 10 minutes." });
}
const { rows: [f] } = await db.query(
`SELECT count(*) FILTER (WHERE last_error IS NOT NULL)::float / NULLIF(count(*), 0) AS rate,
count(*) AS total
FROM webhook_events WHERE updated_at > NOW() - INTERVAL '1 hour'`,
);
if (f.total >= 5 && f.rate > LIMITS.failureRate) {
problems.push({ key: "failure-rate", message: `${Math.round(f.rate * 100)}% of events hit an error in the last hour.` });
}
const { rows: [d] } = await db.query(`SELECT count(*)::int AS failed FROM webhook_events WHERE status = 'failed'`);
if (d.failed > 0) {
problems.push({ key: "dead-letters", message: `${d.failed} event(s) failed for good. Open the dead-letter view.` });
}
const { rows: [r] } = await db.query(
`SELECT max(created_at) AS last FROM webhook_events WHERE source = 'forms'`,
);
const quietHours = r.last ? (Date.now() - new Date(r.last).getTime()) / 3_600_000 : Infinity;
if (isWorkingHours(new Date()) && quietHours > LIMITS.quietHoursWithoutEvents) {
problems.push({ key: "no-events", message: `No form events for ${Math.round(quietHours)} hours. Check the sender.` });
}
return problems;
}The limits are examples. Set yours from a week of normal traffic, the same way you'd measure a baseline before automating anything. And keep them in config rather than scattered through the code, so changing one doesn't need a hunt.
Don't spam the channel
An alert that fires every five minutes for the same problem gets muted by lunchtime, and then it's worse than no alert. Two small rules stop that:
- Alert on change. Post when a problem appears, and post again when it clears. Not on every check in between.
- Remind, slowly. If a problem is still there after a few hours, post one reminder. Then stay quiet.
// alert_state: one row per problem key that is currently open.
// CREATE TABLE alert_state (key TEXT PRIMARY KEY, opened_at TIMESTAMPTZ NOT NULL, reminded_at TIMESTAMPTZ);
const REMIND_AFTER_HOURS = 4;
export async function runHealthCheck() {
const problems = await checkAutomationHealth();
const { rows: open } = await db.query(`SELECT key, opened_at, reminded_at FROM alert_state`);
const openKeys = new Set(open.map((r) => r.key));
const nowKeys = new Set(problems.map((p) => p.key));
for (const p of problems) {
if (!openKeys.has(p.key)) {
await db.query(`INSERT INTO alert_state (key, opened_at) VALUES ($1, NOW())`, [p.key]);
await slack.post(`:red_circle: ${p.message}`);
}
}
for (const r of open) {
if (!nowKeys.has(r.key)) {
await db.query(`DELETE FROM alert_state WHERE key = $1`, [r.key]);
await slack.post(`:large_green_circle: Resolved: ${r.key}`);
continue;
}
const since = new Date(r.reminded_at ?? r.opened_at).getTime();
if (Date.now() - since > REMIND_AFTER_HOURS * 3_600_000) {
await db.query(`UPDATE alert_state SET reminded_at = NOW() WHERE key = $1`, [r.key]);
await slack.post(`:hourglass: Still open: ${problems.find((p) => p.key === r.key)?.message}`);
}
}
}One more thing: the health check must not run inside the worker it's checking. If the worker's cron job disappears, the check disappears with it, and you'll get silence instead of an alert. Run it as its own scheduled job.
Catching "wrong but successful"
The numbers above can't see a result that's wrong but accepted. For that, add cheap checks on what you send before you send it:
function assertLeadLooksRight(lead: Lead) {
const missing = (["name", "email", "company"] as const).filter((k) => !lead[k]?.trim());
if (missing.length) {
// Not retryable: the data won't fix itself. Fail the event so a person looks at it.
throw new Error(`Lead is missing ${missing.join(", ")}. Did a form field get renamed?`);
}
}It feels backwards to make an automation fail on purpose. But an event in the dead-letter view saying "Lead is missing company. Did a form field get renamed?" is found the same day. A hundred CRM records with a blank company are found at the end of the quarter.
Step 4: a dead-letter view
A dead letter is an event the automation gave up on. Our failed status already is a dead-letter queue: the rows are there, with the payload, the attempt count and the last error. What's missing is a way to see them without opening a database client.
The view needs to answer three questions at a glance: what's broken, how many events does it affect, and can I retry them now?

Group by error, not by event
Forty failed events are usually two problems, not forty. Group them by error message so you see the problems. Normalise the message first, so IDs and numbers inside it don't split one problem into forty groups:
SELECT regexp_replace(last_error, '[0-9a-f-]{8,}|\d+', '#', 'g') AS problem,
count(*) AS events,
min(updated_at) AS first_seen,
max(updated_at) AS last_seen,
array_agg(id ORDER BY updated_at DESC) AS ids
FROM webhook_events
WHERE status = 'failed'
GROUP BY problem
ORDER BY events DESC;Here's a small admin page for it in Next.js, with a server component for the list and server actions for the buttons:
// app/admin/dead-letters/page.tsx
import { replayEvents, discardEvents } from "./actions";
import { requireAdmin } from "@/lib/auth";
export default async function DeadLetters() {
await requireAdmin();
const { rows: groups } = await db.query(DEAD_LETTER_GROUPS_SQL);
if (groups.length === 0) return <p>No failed events. Nothing to do.</p>;
return (
<main>
<h1>Failed events</h1>
{groups.map((g) => (
<section key={g.problem}>
<h2>{g.problem}</h2>
<p>
{g.events} event(s), first {g.first_seen.toLocaleString()}, last {g.last_seen.toLocaleString()}
</p>
<form action={replayEvents.bind(null, g.ids)}>
<button>Replay all</button>
</form>
<form action={discardEvents.bind(null, g.ids)}>
<button>Discard</button>
</form>
</section>
))}
</main>
);
}Two things matter more than the layout. Put it behind your admin login, because the payloads hold customer data and the buttons trigger real emails. And show the full error and the payload for one event on a detail page, because that's what you'll read when you're working out the fix.
Step 5: replay
Replay means putting a failed event back in the queue so the worker tries again. Thanks to Part 2, that's safe: the effects table remembers which steps already succeeded, so a replay only finishes what was left.
// app/admin/dead-letters/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { requireAdmin } from "@/lib/auth";
export async function replayEvents(ids: string[]) {
const admin = await requireAdmin();
await db.query(
`UPDATE webhook_events
SET status = 'pending', attempts = 0, next_attempt_at = NOW(), updated_at = NOW()
WHERE id = ANY($1) AND status = 'failed'`,
[ids],
);
console.log(JSON.stringify({ kind: "dead_letter_replay", by: admin.email, count: ids.length }));
revalidatePath("/admin/dead-letters");
}
export async function discardEvents(ids: string[]) {
const admin = await requireAdmin();
await db.query(
`UPDATE webhook_events
SET status = 'discarded', last_error = last_error || ' [discarded by ' || $2 || ']', updated_at = NOW()
WHERE id = ANY($1) AND status = 'failed'`,
[ids, admin.email],
);
revalidatePath("/admin/dead-letters");
}Notice what these don't do:
- Replay doesn't call the steps directly. It hands the event back to the worker, so it goes through the same claiming, logging, backoff and effect records as everything else. One code path, not two.
- Discard doesn't delete. The event stays, with a note of who discarded it. When someone asks in a month what happened to a lead, the answer is still there.
- Both check
status = 'failed'. A double-click, or two people pressing the button at once, can't reset an event that's already being processed.
The order that works
When a group of events fails, the instinct is to press Replay straight away. Resist it, unless the error was clearly temporary, like the CRM being down for an hour. Otherwise, the order is:
- Read one event. The error, the payload, the step logs for its ID.
- Fix the cause. Deploy the code fix, renew the token, update the field mapping.
- Replay one event and watch its logs.
- Replay the rest of the group.
Replaying before fixing just turns 40 failed events into 40 failed events with eight more attempts each.
And don't edit the stored payload to make a replay pass. The payload is a record of what the sender actually sent. If the data is wrong, fix how your code reads it, or fix the record downstream by hand, and discard the event with a note.
Test the parts that only run when things go wrong
Alerting and replay code runs rarely, which means it breaks quietly. Two tests cover most of it:
import { describe, expect, it } from "vitest";
describe("dead letters", () => {
it("replay only repeats the steps that didn't finish", async () => {
const id = await insertFailedEvent({ completedEffects: ["crm_upsert", "welcome_email"] });
await replayEvents([id]);
await processPendingEvents();
expect(email.send).not.toHaveBeenCalled(); // already done before the failure
expect(slack.post).toHaveBeenCalledTimes(1); // the step that failed
expect(await statusOf(id)).toBe("done");
});
it("raises one alert for a stopped worker, and clears it", async () => {
await setHeartbeat("forms-worker", minutesAgo(30));
await runHealthCheck();
await runHealthCheck();
expect(slackMessages()).toHaveLength(1); // no repeat on the second check
await setHeartbeat("forms-worker", minutesAgo(0));
await runHealthCheck();
expect(slackMessages().at(-1)).toMatch(/Resolved: heartbeat/);
});
});Then do one fire drill in production: stop the worker for fifteen minutes and check that the heartbeat alert arrives where you expect, and that the resolved message follows when you start it again. An alert you've never seen fire is an alert you're hoping works.
Checklist
For every automation that runs without a person watching:
- Log one structured line per step per attempt, with the event ID, step, outcome, duration and error.
- Log skipped steps too, so you can prove a retry didn't repeat them.
- Watch five numbers: events received, backlog age, failure rate, failed events, worker heartbeat.
- Alert on change, remind slowly, and run the health check apart from the worker.
- Check the data you send, and fail on purpose when it's clearly wrong.
- Keep failed events as dead letters. Group them by normalised error.
- Replay through the worker, never around it. Discard with a note, never delete.
- Read one, fix the cause, replay one, then replay the rest.
- Test replay and alerts, and do one fire drill.
Next in this series: not every automation starts with a webhook. Part 4 covers scheduled automations: cron jobs that silently miss runs, run twice, or fall over halfway through a big batch, and how to backfill safely when they do.


