# Email webhooks that survive retries and out-of-order events

Verify signed email webhooks, commit events before acknowledging them, deduplicate retries, and preserve out-of-order observations. Includes a receiver and replay fixture.

Author: Stampwing
Canonical: https://www.stampwing.com/guides/reliable-email-webhooks
Published: 2026-10-04
Reviewed: 2026-10-05
Category: Engineering

Build and exercise a durable event inbox with duplicate and tampering checks.

## Short answer

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#short-answer

Verify the signature against the original request bytes, persist each event under a unique source-and-event key, then acknowledge it. Process the stored inbox independently. Delivery callbacks can repeat or arrive out of order, so they should not blindly overwrite message state.

## Before you start

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#before-you-start

For: Backend developers building an email event receiver.

Bring: Node.js 22+, a disposable PostgreSQL database, pg, standardwebhooks and a local signing secret.

Scope: Use a dedicated test database for the replay exercise. The receiver stores events but does not apply business effects.

## Treat acknowledgement as a persistence boundary

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#contract

A webhook sender cannot know whether your application saved an event when the connection breaks. It may retry a notification you already processed. That is normal distributed-system behavior, not necessarily a provider defect.

Returning success before storage finishes risks losing the event. Waiting for every downstream action before responding makes the endpoint slow and fragile. A durable inbox gives you a smaller promise: the event is safely recorded, and application processing can resume later.

Use a unique combination of provider or endpoint identity and event ID. Two sources can choose overlapping identifiers. Do not deduplicate by message ID alone because one message can legitimately have several events.

Bind the source identity to your endpoint configuration and verified signing key, not to an untrusted source field in the payload. When you rotate that key, keep the logical source stable so a redelivery still matches the original deduplication record. Decide how long to retain event identities using the provider’s retry and replay windows; purging them can let an old replay run again.

## Verify the original payload before parsing business data

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#verify

Use the provider’s supported verification library and its exact signing format. Stampwing’s outgoing webhooks follow the Standard Webhooks pattern with webhook-id, webhook-timestamp, and webhook-signature headers. Verification includes the timestamp and unmodified body.

Do not parse and reserialize JSON before checking the signature. Whitespace and property order can change the signed bytes. Keep the server clock accurate, enforce body and request-time limits, and support the provider’s documented secret-rotation process.

The example uses standardwebhooks to handle signature verification and freshness checks. A valid signature establishes authenticity for the configured key; validate event shape and project/message references before applying business effects.

Verify before using the event

```javascript
import { Webhook } from "standardwebhooks";

const verifier = new Webhook(process.env.WEBHOOK_SECRET);
// rawBody is the unmodified UTF-8 request body.
const event = verifier.verify(rawBody, request.headers);
```

## Commit once, acknowledge duplicates consistently

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#inbox

Create the example inbox table in your application’s own database. Download the receiver, install pg and standardwebhooks, and configure your database connection and endpoint signing secret in the server environment.

The receiver limits the body, verifies the signature, and inserts the event with ON CONFLICT DO NOTHING. It returns 204 only after the database operation completes. If storage fails, it returns 503 so the sender can retry.

This receiver is a local integration example listening on loopback. Deploy behind an appropriately configured HTTPS ingress for a real endpoint, and add your operational monitoring and retention policy. The example does not process application effects or send email.

Install and start locally

```shell
npm install pg standardwebhooks
# Apply webhook-inbox.sql to your application database.
# Set DATABASE_URL and WEBHOOK_SECRET in your server environment.
node webhook-receiver.mjs
```

[Download the inbox SQL](https://www.stampwing.com/downloads/webhook-inbox.sql)

[Download the receiver](https://www.stampwing.com/downloads/webhook-receiver.mjs)

## Preserve the timeline instead of trusting arrival order

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#ordering

An accepted event may arrive before an earlier submitted event. A delayed delivery event may arrive after your own timeout warning. Keep both provider occurrence time and local receipt time so you can explain what happened.

Model observations by meaning. Delivery, complaints, and suppression changes are not interchangeable points on a single numeric progress scale. Derive a user-facing status with explicit precedence and keep the original events for diagnosis.

When processing the inbox, claim rows safely and commit local state changes together with the processed marker. For an external side effect, write another durable outbox entry in that transaction. A database transaction cannot atomically commit an unrelated remote request.

A validly signed event can still use an unknown schema or an unavailable message reference. Persist it for quarantine or reconciliation with a reason and alert, then decide how to acknowledge it under the provider’s contract. Do not repeatedly crash the worker on the same row or silently mark an unhandled event as applied. The downloadable receiver checks only a minimal envelope; your worker owns business validation.

| Arrival pattern | Expected behavior |
| --- | --- |
| Same event arrives twice | One inbox row, two successful acknowledgements. |
| Older event arrives later | Retain both observations; do not erase newer evidence. |
| Unknown message reference | Store or quarantine for reconciliation; do not attach to another project. |
| Worker crashes mid-processing | Resume from persisted state with an idempotent effect. |
| Database unavailable | Return a retryable failure; do not claim success. |

## Keep delivery evidence separate from permission to send again

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#recipient-projection

A recipient can receive a message and later complain. Replacing “delivered” with “complained” loses delivery history; ignoring the complaint because delivery is “terminal” loses a sending restriction. Keep the event log and derive separate delivery and suppression views for each recipient.

Here is one application policy for synthetic events. It is not a universal ordering of provider statuses. The provider adapter must map event types and recipient identities explicitly. A multi-recipient message can contain both successful and failed recipients; a message-level boolean cannot represent that.

| Arrival order | Delivery evidence retained | Future sending decision |
| --- | --- | --- |
| 1. delivery for recipient A | A’s receiving server accepted the message. | No complaint is known; still apply all other sending checks. |
| 2. complaint for A | Keep A’s acceptance and append the complaint. | Apply the complaint suppression policy. |
| 3. older send/submission event for A | Keep the earlier observation without erasing acceptance. | Do not clear the complaint. |
| 4. duplicate complaint event ID | Keep one logical complaint event. | No second business effect or extra counter increment. |
| 5. bounce for recipient B | Record B’s failure separately from A’s delivery. | Apply the relevant suppression rule to B. |

Note: When a signed duplicate ID arrives with different content, preserve the first event and record the inconsistency for investigation. The downloadable minimal receiver uses ON CONFLICT DO NOTHING and does not detect that mismatch; add a defined payload comparison before using it as a production receiver.

[SES: recipient-specific delivery, bounce and complaint event fields](https://docs.aws.amazon.com/ses/latest/dg/event-publishing-retrieving-sns-contents.html)

## Replay the same event, then alter its body

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#replay

The downloadable replay script signs a synthetic event with the same local secret, posts it twice, and verifies that a tampered copy is rejected. Run it after the receiver and query the inbox: there should be one row for fixture-delivery-42.

A replay is a synthetic protocol test. It does not establish real provider connectivity. For a complete application test, also exercise an unavailable database, an expired signature, two different events for the same message, and a worker crash after claiming an inbox row.

Replay fixture

```shell
node webhook-replay.mjs

# Inspect your application database:
# SELECT source, event_id, count(*)
# FROM email_webhook_inbox GROUP BY source, event_id;
```

[Download the signed replay fixture](https://www.stampwing.com/downloads/webhook-replay.mjs)

## Watch the inbox after the endpoint is healthy

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#operate

An endpoint returning 204 can coexist with a broken processing worker. Monitor the oldest unprocessed event, repeated processing errors, and reconciliation backlog separately from HTTP response rates.

Document how to replay a stored event safely, rotate a secret, and recover from a database outage. Include identifiers and timestamps in logs, but avoid logging full message bodies, signing secrets, or recipient data unnecessarily.

| Recovery action | What it repeats |
| --- | --- |
| Provider redelivery | The signed HTTP notification; verify its current delivery signature. |
| Reprocess a stored inbox row | Your local event handler; keep the original event identity and audit the action. |
| Resend the email | A separate business operation requiring its own authorization and send identity. |

## Know which layer needs the retry

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#webhook-recovery-matrix

A webhook retry repeats an event notification, not the original email. Keep those two retry loops separate in code and in operator controls. Measure the oldest unprocessed event as well as the endpoint’s HTTP success rate.

| Failure boundary | Recovery owner | Evidence to keep |
| --- | --- | --- |
| Signature or freshness check fails | Receiver rejects the request; investigate before any replay. | Reason, timestamp, and endpoint identity; no signing secret. |
| Database write fails | Sender retries the delivery after a non-success response. | Event ID and storage failure time. |
| Event stored, worker fails | Your inbox worker resumes the stored event. | Processing attempts and the last committed state. |
| Acknowledgement is lost | Sender may repeat an already-stored event. | The unique source + event ID used for deduplication. |

[Calculate a bounded webhook retry schedule](https://www.stampwing.com/tools/email-retry-calculator)

## Sources

Section link: https://www.stampwing.com/guides/reliable-email-webhooks#sources

- [Standard Webhooks specification](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md)
- [PostgreSQL: INSERT and ON CONFLICT](https://www.postgresql.org/docs/current/sql-insert.html)
- [SES: recipient-specific delivery, bounce and complaint event fields](https://docs.aws.amazon.com/ses/latest/dg/event-publishing-retrieving-sns-contents.html)

Example download: [Download the webhook receiver](https://www.stampwing.com/downloads/webhook-receiver.mjs)

## Related guides

- https://www.stampwing.com/guides/prevent-duplicate-emails
- https://www.stampwing.com/guides/test-transactional-email
- https://www.stampwing.com/guides/email-delivered-but-not-received
- https://www.stampwing.com/guides/stripe-webhook-order-confirmation
- https://www.stampwing.com/guides/migrate-email-provider

Editorial policy: https://www.stampwing.com/resources/editorial
