Webhooks look simple. A provider sends an HTTP request, your application reads the JSON, checks the event type, updates a record, returns 200 OK and moves on. On the happy path that's easy to understand and easy to build.
It gets harder once the transport behaves like a real distributed system. The network can time out after your database transaction has already committed. The same event can arrive twice, sometimes at the same moment. An update can arrive before the event that was supposed to come first. Your application can update its own state and crash before sending the email. Or it can be down long enough that you're no longer sure what you missed. At that point a webhook endpoint isn't just a controller; it's a correctness problem across failure boundaries.
I ran into this while building Featherly, a marketplace app with Stripe billing and Connect payouts across several payment flows. It handled nine webhook event types, with signature verification and retry-safe idempotency. Parsing the payload wasn't the interesting part. The interesting part was how to end up with correct business state when the delivery mechanism is imperfect. The answer isn't just "use an idempotency key". It takes several layers: authentication, durable acceptance, duplicate suppression, idempotent state changes, asynchronous processing, careful handling of side effects, observability and reconciliation. What ties them together is that delivery attempts are unreliable, but your business rules shouldn't be.
Delivery attempts aren't business operations
The simplest mental model looks like this:
It quietly assumes the provider sends one request, you receive it, your code succeeds and the response gets back. Every arrow is a place where that can fail. Here's a common one, where the database commits but the acknowledgement is lost:
The provider thinks the first delivery failed, because it never got a response. Your application thinks it succeeded, because the database committed. Both are behaving correctly with the information they have, and that ambiguity is exactly why retries exist. Stripe's post on designing robust APIs with idempotency describes the same problem from the caller's side: an operation can succeed while the connection breaks before the result comes back.
So the useful model is that a provider may attempt delivery several times, and your system has to make those attempts add up to one correct outcome. Providers say as much. Shopify's webhook docs say ordering isn't guaranteed and recommend reconciliation jobs because deliveries can be missed, and their guide to verifying deliveries covers ignoring duplicates. GitHub's webhook best practices recommend using the X-GitHub-Delivery header and redelivering missed deliveries. The safe assumption is that any event may arrive once, several times, late, concurrently with a copy of itself, or after you've partly processed it.
Verify first
Before idempotency comes authenticity. A webhook endpoint is open to the internet, so anything built on an unverified event is on shaky ground; without signature verification, anyone who can reach the URL can try to fake events.
Stripe's webhook documentation explains that verification uses the raw request body, the Stripe-Signature header and your endpoint secret, and warns that if your framework changes the raw body, verification fails. In NestJS, you enable the raw body:
// main.ts
const app = await NestFactory.create(AppModule, {
rawBody: true,
});
await app.listen(3000);
and verify before doing anything else:
@Post("/webhooks/stripe")
async handleStripeWebhook(
@Req() req: RawBodyRequest<Request>,
@Headers("stripe-signature") signature: string,
) {
const event = this.stripe.webhooks.constructEvent(
req.rawBody!,
signature,
process.env.STRIPE_WEBHOOK_SECRET!,
);
// Only process the event after verification succeeds.
}
Don't parse the payload and trust its event ID, then check legitimacy later. Security should wrap the reliability mechanism, not follow it.
Accept durably, process later
One of the most useful changes is separating accepting an event from processing it. Stripe recommends returning a 2xx quickly, before any complex logic that might time out, and GitHub recommends responding within 10 seconds and doing longer work asynchronously.
The endpoint's job becomes deliberately small: verify the event, extract its ID, store it durably and acknowledge. A worker does the expensive part later. Less logic sits inside the provider's retry window, and your own system has a durable record to resume from.
NoteA fast acknowledgement only helps once the event is somewhere durable. Returning
200before you can recover the event swaps provider retries for the chance of silent loss.
For example, queue.add(event); return { received: true }; looks fine, but if that queue only lives in process memory and the app crashes, the provider believes you have the event and you've lost it. I don't acknowledge a webhook until it's somewhere my own recovery can find it: a database, a message broker or a managed queue. The technology matters less than the guarantee.
An inbox with a unique key
The obvious duplicate check is also easy to get wrong under concurrency:
const existing = await events.findOne({ eventId });
if (existing) {
return;
}
await events.insertOne({
eventId,
status: "pending",
});
Two copies of the same event can both run the lookup, both see nothing, and both insert. The check and the write are separate operations. What you need is for the database to enforce uniqueness:
await webhookEvents.createIndex({ provider: 1, eventId: 1 }, { unique: true });
Then attempt the insert and let the database decide which copy wins:
try {
await webhookEvents.insertOne({
provider: "stripe",
eventId: event.id,
eventType: event.type,
payload: event,
status: "pending",
receivedAt: new Date(),
});
} catch (error: any) {
if (error.code === 11000) {
// Already accepted this delivery.
return { received: true };
}
throw error;
}
Now uniqueness depends on the database, not on the timing of two requests. This table is often called an inbox, keyed on (provider, event_id). It gives you more than "I think I've seen this before"; it's a durable record that your system has taken responsibility for the event.
Deduplication isn't idempotency
Ignoring repeated copies of evt_123 solves one problem, but two different events can still affect the same thing. Event-ID deduplication stops the same delivery being processed twice; it doesn't make the business operation safe. Take this:
if (event.type === "invoice.payment_succeeded") {
await credits.increment(userId, 100);
}
If another event or retry path reaches that code with a different event ID, the customer gets credited twice. A sturdier design gives the business operation its own identity:
await creditLedger.updateOne(
{
operationKey: `invoice:${invoiceId}:credit`,
},
{
$setOnInsert: {
userId,
amount: 100,
source: invoiceId,
createdAt: new Date(),
},
},
{
upsert: true,
},
);
Now the rule is "one credit per invoice" rather than "one execution per webhook ID". That distinction is central: deduplicating deliveries protects against repeated messages; business idempotency protects the rules that matter. The first asks whether you've already accepted this event. The second asks whether running the operation again could change the result.
Out-of-order events
Ordering is the other source of uncertainty. Shopify's docs give the example of a products/update webhook arriving before the products/create. If your handler turns each event straight into an assignment, arrival order becomes business truth by accident:
switch (event.type) {
case "payment.failed":
order.status = "FAILED";
break;
case "payment.succeeded":
order.status = "PAID";
break;
}
If the provider created payment.failed at 12:00:01 and payment.succeeded at 12:00:05, but they arrive the other way round, this ends with FAILED even though the payment succeeded. You need to reason about state instead of trusting arrival order, and the right approach depends on the domain:
- Validate transitions. Write down which state changes are allowed, so an event proposes a transition rather than overwriting state. For example,
PAIDmight allow nothing further, whileFAILEDcan still move toPROCESSINGorPAID. - Compare versions or timestamps. If the provider gives you a trustworthy version or timestamp for the resource (Shopify suggests
X-Shopify-Triggered-Atorupdated_at), ignore anything older than what you already have. - Fetch the current state. For important transitions, treat the webhook as a notice that something changed, and ask the provider's API for the current state. It costs a network call, but it's simpler when a resource may have changed several times before you process the notice.
const allowedTransitions = {
PENDING: ["PROCESSING", "PAID", "FAILED"],
PROCESSING: ["PAID", "FAILED"],
PAID: [],
FAILED: ["PROCESSING", "PAID"],
};
As usual in distributed systems, stronger correctness costs something: latency, extra calls or more code.
Half-finished side effects
Now a handler does three things:
await orders.markPaid(orderId);
await email.sendReceipt(customer);
await analytics.trackPurchase(orderId);
If the process crashes after markPaid() and before sendReceipt(), retrying may safely repeat the database update if it's idempotent, but external effects are harder. The email might have gone out even though you never saw a success, and a retry could send it again. If the call moves money instead of sending email, the same ambiguity is much more serious.
This is the dual-write problem: you want the database and another system to change together, and there's no transaction that spans both. A common approach is an outbox. You commit the business update and a record saying "this external action must happen" in the same database transaction, and a separate dispatcher performs the action:
That doesn't create exactly-once delivery to the other system, but it moves the uncertainty to a place you can observe, retry and recover deliberately. If the destination supports idempotency keys, as Stripe does for mutating API requests, pass the outbox operation's ID as the key. I go into the outbox pattern in more depth in How Do You Commit a Database Change and Publish an Event Without Lying to Either System?.
It's tempting to say "this event must run exactly once", but HTTP can't give you that on its own. If acknowledgements can be lost, the sender can't know whether you finished, so it has to choose between not retrying (and risking lost work) or retrying (and risking duplicates). Reliable systems choose retries, because lost work is usually worse than duplicates the receiver can make safe. The practical goal is at-least-once delivery with effectively-once business behaviour.
Retries and reconciliation
Retries aren't free either. If 20,000 events fail because the database is overloaded and every worker retries immediately, the retries add more load to the thing that's already struggling, and recovery becomes a feedback loop. A disciplined retry policy has a maximum number of attempts, exponential backoff and jitter, which Stripe's idempotency post also recommends to avoid a thundering herd:
function retryDelay(attempt: number): number {
const base = Math.min(1000 * 2 ** attempt, 60_000);
const jitter = Math.random() * 1000;
return base + jitter;
}
Retries also shouldn't continue forever. Eventually an event should move to a state like FAILED_PERMANENTLY or NEEDS_RECONCILIATION, so the system can admit that automatic processing couldn't work out the right state. That's healthier than retrying something that will never succeed, and it gives operators a concrete list to look at. (I wrote more about how retries can make outages worse in When Do Retries Stop Improving Reliability and Start Amplifying an Outage?)
Even good webhook handling shouldn't assume the event stream is perfect, which is why Shopify recommends reconciliation jobs. For payments, a scheduled job can compare the provider's state with yours and repair or flag any drift:
This changes the model from "every event must work perfectly" to "events keep us current quickly, and reconciliation eventually fixes drift". Webhooks give freshness; reconciliation protects correctness. That's especially useful when being briefly stale is acceptable but silently staying wrong isn't.
Following an event through the system
An endpoint returning 200 can still be completely broken. Events can be landing in the inbox while workers have stopped. One event type can start failing after a code change. Duplicates can spike. The oldest pending webhook can be 40 minutes old while the endpoint looks perfectly healthy.
Structured logging keyed on the provider's event ID made a big difference in my own backend, because I could follow one event through every stage:
{
"provider": "stripe",
"eventId": "evt_123",
"eventType": "invoice.payment_succeeded",
"stage": "processing",
"attempt": 2,
"orderId": "ord_456",
"durationMs": 184,
"result": "success"
}
The metrics I'd want are received, duplicate, signature-failure, processing-failure and dead-lettered counts, processing latency, pending count, the age of the oldest pending event, and reconciliation drift. The most useful alert is often "oldest pending event older than 10 minutes" rather than "HTTP error rate above 5%". The second tells you about an endpoint; the first tells you whether the business workflow is actually moving.
Putting it together
A robust webhook setup might look like this:
Very little is left in the HTTP endpoint, on purpose: verify, store durably, acknowledge. The business workflow lives behind it, where it can be retried, observed and reconciled. Each mechanism handles one kind of correctness: signature verification for authenticity, the inbox for durable acceptance and duplicate deliveries, business idempotency for your rules, state transitions for ordering, the outbox for side effects, retries for transient failures, and failed-event states plus reconciliation for what automation can't resolve.
None of this is really about Stripe or NestJS. The design problem is deciding which properties must hold when execution is repeated, interrupted, delayed or reordered. For a marketplace, that might be: a payment never creates two bookings, an invoice never grants credit twice, a payout never runs twice for the same obligation, an accepted event survives a restart, and a delayed event never overwrites newer state. Once those are written down, a few questions find problems much faster than reading the happy path. What happens if this line runs twice? If the process dies right after this write? If the response disappears? If this event arrives tomorrow? If two copies run at once? And if the event never arrives, how would I know?
Key takeaways
- Treat webhooks as at-least-once and unordered. Delivery attempts aren't business operations.
- Verify the signature against the untouched raw body before trusting anything in the payload.
- Store the event durably under a database-enforced unique key before returning
2xx, then process it asynchronously. - Make business operations idempotent on their own keys (one credit per invoice), not just on webhook IDs.
- Handle ordering with explicit state transitions, trusted versions or a fresh fetch, and handle side effects with an outbox and idempotency keys.
- Retry with backoff and jitter up to a limit, keep failed events visible, reconcile against the provider, and alert on the oldest pending event.
References
- Stripe — Designing robust and predictable APIs with idempotency — ambiguous network failures, idempotency keys, and backoff with jitter.
- Stripe Docs — Receive Stripe events in your webhook endpoint — signature verification, the raw-body requirement, and returning
2xxquickly. - Stripe API Reference — Idempotent requests — how Stripe's idempotency keys make retried requests safe.
- Shopify Dev Docs — About webhooks — no ordering guarantees, using timestamps, and reconciliation jobs.
- Shopify Dev Docs — Verify webhook deliveries — HMAC verification and ignoring duplicates.
- GitHub Docs — Best practices for using webhooks — responding within 10 seconds, using the delivery ID, and redelivering missed events.
