Email verification is often designed as a request-response feature: send a code, wait for the user, then mark the address as verified. In production, the email provider usually adds a webhook to that flow. That webhook can be retried, duplicated, delayed, or delivered out of order.
If the handler updates the user record directly every time, a late event can quietly undo a newer decision. The fix is not a bigger try/catch. It is a replay boundary: store each provider event, decide whether it is new, and apply only valid state transitions.
Why email webhooks need a replay boundary
Imagine a user requests two verification codes. The second code is current, but the provider delivers the first message's event after the second one. A naive Node.js handler may process both payloads and leave the account pointing at an expired challenge.
The same problem appears in test environments that use a free disposable email address or a fake inbox. The inbox is only the transport. Your application still needs a deterministic rule for which event wins.
A useful event identity usually combines the provider's event ID with your account or environment boundary. Never use the message subject as the deduplication key. Subjects are for people, and they can repeat.
Store the event before applying it
The first database operation should claim the event. A unique constraint makes retries safe even when two Node.js workers receive the same webhook at almost the same moment:
CREATE TABLE email_events (
provider_event_id text PRIMARY KEY,
user_id uuid NOT NULL,
challenge_id text NOT NULL,
event_type text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
payload jsonb NOT NULL
);
Then insert the event and stop when the key already exists:
const result = await db.query(
`INSERT INTO email_events
(provider_event_id, user_id, challenge_id, event_type, payload)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (provider_event_id) DO NOTHING`,
[event.id, userId, event.challengeId, event.type, event],
)
if (result.rowCount === 0) {
return { status: 200, body: "duplicate" }
}
Returning 200 for a known event matters. A provider that sees a 500 will retry, which creates load without adding information. The code are small, but this boundary removes a whole category of retry bugs.
For test fixtures, keep the same event ledger in local and CI environments. A label such as tempail or dummy e mail may appear in old fixture data, but it should never become a business rule.
Model verification state explicitly
The event ledger tells you that an event was seen. It does not tell you whether the event is allowed to change the current challenge. Put that rule in a small, typed function:
type Verification =
| { kind: "pending"; challengeId: string }
| { kind: "verified"; challengeId: string; verifiedAt: Date }
| { kind: "expired"; challengeId: string }
function applyEmailEvent(
current: Verification,
event: { challengeId: string; type: "DELIVERED" | "VERIFIED" | "EXPIRED" },
): Verification {
if (event.challengeId !== current.challengeId) return current
if (current.kind === "verified") return current
if (event.type === "VERIFIED") {
return { kind: "verified", challengeId: event.challengeId, verifiedAt: new Date() }
}
if (event.type === "EXPIRED") {
return { kind: "expired", challengeId: event.challengeId }
}
return current
}
The important check is the challenge ID. A valid event for an older request is still stale. This also keeps the React layer simple: it renders one current state instead of combining loading, verified, and error flags that can disagree.
Make the Node.js handler idempotent
Wrap the claim and state update in one transaction when the database supports it. The sequence should look like this:
- Validate the webhook signature.
- Parse the payload into a TypeScript type.
- Insert the provider event with a unique key.
- Lock or update the matching verification row.
- Apply only a legal transition for that challenge.
- Commit and return success.
Do not acknowledge an event before step 3 unless you have a durable queue in front of the application. Also, do not log the full payload by default. Email events can contain addresses, links, and verification data that has no place in routine logs.
If the provider does not supply a stable event ID, create a canonical fingerprint from immutable fields such as message ID, challenge ID, event type, and provider timestamp. Document the choice. A fingerprint made from the entire JSON blob is fragile because harmless field ordering changes can defeat deduplication.
Test duplicates and late delivery
The most valuable tests dispatch events, not just HTTP snapshots:
it("keeps the newest challenge verified after an old event arrives", async () => {
await deliver({ id: "new", challengeId: "c2", type: "VERIFIED" })
await deliver({ id: "old", challengeId: "c1", type: "VERIFIED" })
expect(await readVerification()).toMatchObject({
kind: "verified",
challengeId: "c2",
})
})
Add cases for the same event delivered twice, two workers claiming one event, an invalid signature, and an expiration that arrives after verification. Those cases catch more than a happy-path inbox test ever will. In CI, preserve request IDs and event IDs as trace-first evidence in CI, while redacting addresses and codes.
It is also worth testing the product policy around appeal paths for disposable email blocks. A webhook can be technically correct while the signup experience still traps legitimate users.
A practical rollout checklist
- Require a provider event ID, or document a stable fingerprint.
- Add a unique database constraint before enabling retries.
- Keep challenge IDs in every verification event.
- Make state transitions monotonic where the product allows it.
- Return success for duplicates after durable storage.
- Redact email addresses, links, and codes from normal logs.
- Run duplicate and out-of-order tests in every deployment pipeline.
This design is not limited to email. Payment webhooks, GitHub events, and background job callbacks all benefit from the same pattern: claim the message, validate its scope, and apply a transition that cannot be confused by replay.
Common questions
Should every webhook be processed asynchronously?
Not always. A small handler can claim and apply an event synchronously inside a short transaction. Use a queue when provider work is slow, when you need burst absorption, or when several consumers need the same event. The idempotency key still belongs at the first durable boundary.
Is an event ledger the same as an audit log?
No. The ledger answers whether a provider event was claimed. An audit log explains business decisions and may include a richer, privacy-reviewed record. They can share infrastructure, but they have different retention and access needs.
What if events arrive in the wrong order?
Compare the event's challenge ID and transition rules with the current row. Do not trust arrival order. If the provider exposes a sequence number, use it as an extra guard, but keep the server-side state check because sequence data can be missing or scoped differently.
Once the webhook has a replay boundary, email verification becomes much less mysterious. Retries are ordinary traffic, duplicate deliveries are harmless, and the UI gets a state it can actually explain.
Top comments (0)