At a Glance
| Pattern | Problem It Solves | Trade-offs | Used By / Seen In |
|---|---|---|---|
| Idempotency keys / event IDs | Prevents duplicate side effects when the same event is delivered more than once | Needs a persistent dedup store (DB row or cache key) with a defined retention window | Stripe events, the Standard Webhooks spec, most payment and billing webhooks |
| HMAC signature verification | Confirms a request actually came from the sender and wasn’t altered in transit | Requires careful raw-body handling and a plan for secret rotation | Stripe (Stripe-Signature), GitHub, Standard Webhooks spec |
| Exponential backoff with jitter | Spreads retries over time instead of a synchronized “retry storm” hitting a recovering endpoint at once | Delivery can be delayed for hours or days before a dead letter; the cap needs tuning | Stripe (retries over up to three days), most queue/retry libraries, AWS reliability guidance |
| At-least-once delivery model | Avoids silently dropping events when a receiver is briefly unreachable | Duplicates are expected, not rare, and must be designed for rather than “fixed” | Stripe, Svix, Hookdeck, the Standard Webhooks spec |
| Explicit ordering fields (sequence numbers, versions, timestamps) | Lets receivers detect and correctly handle out-of-order delivery | Adds payload complexity; most providers still don’t guarantee order by default | Stripe (explicitly unordered by default); some infra providers offer opt-in ordered delivery |
| Dead-letter / manual replay | Gives a recovery path when an endpoint is down longer than the automatic retry window | Needs monitoring and an operational process, or failures go unnoticed | Stripe dashboard “Resend” and CLI resend, Svix, Hookdeck |
The Verdict
Idempotent webhook handling is less about any single clever trick and more about accepting a physical reality: over an unreliable network, a sender can never be fully certain a receiver got a message, so retries and duplicates are inevitable rather than exceptional. The patterns here — stable event IDs, HMAC verification, backoff with jitter, and designing for at-least-once delivery instead of fighting it — are now standard practice among API providers that take event delivery seriously. Skip them, and duplicate charges, double-fulfilled orders, or silently missed events are a matter of when, not if.
The Problem: Why “Just Send a POST Request” Doesn’t Scale
Webhooks look simple: your service does something, it POSTs a JSON payload to a URL you registered, and the receiver reacts. In practice, HTTP between two independent systems is unreliable in ways that break naive implementations within weeks of going live — not because of rare edge cases, but as a matter of basic network behavior. A request can succeed in generating the event, time out before its HTTP response reaches the sender, get retried, and now the same business event has been delivered twice. Requests can be delayed, re-sent by an overly eager retry loop, or arrive out of order relative to a related event sent moments earlier. The sending platform usually has no reliable way to know whether the receiver actually finished processing its last attempt, so it has to guess conservatively — and that guess almost always favors re-sending rather than risking silent loss.
None of this is a bug in any particular webhook provider. It’s a property of using HTTP as a message bus between systems that don’t share a transaction. The engineering question isn’t “how do we stop duplicates and out-of-order delivery from ever happening” — it’s “how do we build a receiver that behaves correctly when they happen anyway.”
How It Works: The Core Patterns
Idempotency Keys and Event IDs
Every well-designed webhook payload carries a stable, unique identifier for the event itself, distinct from the ID of the resource it describes. Stripe’s events carry an id that stays constant across every delivery attempt for that event, even though other request metadata can change between attempts. Stripe’s own documentation is explicit that receivers should log processed event IDs and skip anything already seen, and specifically warns against using timestamps to detect duplicates, since distinct events can share the same second-level timestamp.
The pattern that actually holds up under concurrency is to let the data store enforce uniqueness, rather than checking for an existing record and then inserting one as two separate steps — that two-step check has a race condition under concurrent retries. A unique constraint on the event-ID column, with the insert itself acting as the deduplication gate, closes that race: two simultaneous deliveries of the same event will produce exactly one successful insert, and the loser can safely treat its own failure as “already handled” rather than re-running side effects.
HMAC Signature Verification
A webhook endpoint is a public URL, so without verification, anyone who finds it can POST a fabricated payload and trigger your business logic. Providers address this by signing each payload with an HMAC: Stripe’s Stripe-Signature header carries a timestamp and one or more signatures computed with HMAC-SHA256 over the string formed by the timestamp, a period, and the raw request body, using a per-endpoint secret only the two parties hold. The receiver recomputes the same HMAC and compares it using a constant-time comparison, so a timing attack can’t leak information about a partial match.
Two details matter enough to call out on their own. First, the comparison has to run against the exact raw request bytes — any framework middleware that reformats or re-serializes the JSON body before your handler sees it will silently break verification, because the recomputed signature won’t match what was actually signed. Second, the timestamp inside the signed payload exists specifically to block replay attacks: Stripe’s own libraries default to rejecting anything more than five minutes old, which is a sensible default to copy even outside Stripe’s own ecosystem.
Retries, Backoff, and Jitter
When a delivery attempt fails or times out, the sender has to decide when to try again. A naive fixed-interval retry does two things badly: it keeps hammering an endpoint that’s down for a known reason, and if many events or many senders hit the same brief outage, their retries can synchronize and arrive in a wave right as the endpoint recovers, re-triggering the same outage. AWS’s engineering writeup on timeouts and retries describes this as a “retry storm,” and the standard mitigation is exponential backoff combined with randomized jitter: each retry waits roughly twice as long as the previous one, with enough randomness added that simultaneous failures don’t resynchronize onto a shared schedule.
Stripe’s documented behavior, specifically, is retries spread with exponential backoff over as long as three days in live mode before the platform stops automatically and leaves the event available for manual resend. That exact window is provider-specific — treat it as an example, not a universal number — and it still means a known-down endpoint needs a human to notice and act before the automatic window closes, since nothing guarantees recovery happens inside it.
Ordering Is Not Guaranteed
It’s tempting to assume events arrive in the order they were generated, and a fair share of webhook-related production incidents trace back to code that quietly assumed exactly that. Stripe states plainly that it does not guarantee delivery order — creating a subscription, for example, can generate a subscription-created event, an invoice-created event, and an invoice-paid event that arrive out of sequence, and retries can reorder things further. The practical fix is to stop relying on arrival order altogether: carry a monotonic field in the payload (a sequence number, a version counter, or an updated_at field on the underlying object) and have the receiver skip or re-fetch when an event describes a state older than what’s already recorded. A handful of infrastructure providers, including Svix, now offer opt-in ordered delivery for use cases that genuinely can’t tolerate reordering — but that remains the exception, not the default, across the ecosystem.
A Minimal Idempotent Webhook Handler
The example below shows the two patterns working together in a Node/Express handler: HMAC verification with replay protection, followed by idempotent processing enforced through a database unique constraint rather than a separate “check if seen” query. It assumes a Postgres-backed db.query helper and a table defined as processed_events(event_id TEXT PRIMARY KEY, received_at TIMESTAMPTZ); adapt the error-code check if you’re using a different database.
const crypto = require('crypto');
function verifySignature(rawBody, sigHeader, secret, toleranceSeconds = 300) {
const parts = Object.fromEntries(
sigHeader.split(',').map((kv) => kv.split('='))
);
const timestamp = parts.t;
const expectedSig = crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${rawBody}`, 'utf8')
.digest('hex');
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (age > toleranceSeconds) {
throw new Error('Timestamp outside tolerance - possible replay');
}
const valid = crypto.timingSafeEqual(
Buffer.from(expectedSig, 'hex'),
Buffer.from(parts.v1, 'hex')
);
if (!valid) {
throw new Error('Signature mismatch');
}
}
// Assumes a Postgres-backed db.query helper and a table:
// processed_events(event_id TEXT PRIMARY KEY, received_at TIMESTAMPTZ)
app.post('/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
const rawBody = req.body.toString('utf8');
const sigHeader = req.headers['x-signature'];
try {
verifySignature(rawBody, sigHeader, process.env.WEBHOOK_SECRET);
} catch (err) {
return res.status(400).send('Invalid signature');
}
const event = JSON.parse(rawBody);
try {
// The unique constraint on event_id is what actually enforces
// idempotency - two concurrent deliveries of the same event
// can only produce one successful insert.
await db.query(
'INSERT INTO processed_events (event_id, received_at) VALUES ($1, now())',
[event.id]
);
} catch (err) {
if (err.code === '23505') {
// unique_violation: already processed, ack without re-running side effects
return res.status(200).send('duplicate, already processed');
}
throw err;
}
await handleEvent(event);
res.status(200).send('ok');
});
The Upside: What You Get Right
- No double-charged customers or double-shipped orders when a provider retries a delivery
- Endpoint downtime from deploys, restarts, or brief outages doesn’t silently lose events
- Forged requests are rejected before they ever reach business logic
- A processed-events log doubles as an audit trail that makes debugging disputes far easier
- Processing can move onto a queue or background worker without changing the correctness guarantees
The Pitfalls: Where Teams Get This Wrong
- Treating the dedup store as an afterthought, when it’s itself infrastructure that needs a retention policy, cleanup, and its own uptime
- Confusing “returned a 200” with “processed successfully,” and acknowledging before the work actually completes
- Signature verification breaking silently when a framework or proxy re-encodes the request body before the handler sees it
- Assuming the automatic retry window is unlimited, when most providers cap it at days, not weeks, before manual intervention is required
- Assuming ordering “because it worked in testing” against a low-traffic sandbox that never actually exercised concurrent events
Who Needs to Care (and Who Can Relax a Little)
This matters most for anything where a duplicated or lost event has a real-world consequence: payments, subscription billing, inventory or order state, user provisioning, and any workflow that fires a downstream action — an email, a shipment, a refund — that can’t be cleanly undone. It matters less for read-only notifications that just invalidate a cache or refresh a dashboard, where processing the same event twice is harmless and losing one for a few minutes is tolerable. Teams building on managed webhook infrastructure rather than raw HTTP endpoints get a lot of the delivery-side reliability handled for them, but idempotent processing on the receiving end is still the receiver’s responsibility no matter who sends the webhook.
Bottom Line
Reliable webhook delivery isn’t a feature you bolt on afterward — it’s an acknowledgment that at-least-once delivery, not exactly-once, is the honest contract any HTTP-based event system can offer. Build the receiver assuming duplicates and reordering will happen, verify every payload’s signature before trusting it, and let retries with backoff and jitter do their job instead of fighting them, and most of the failure modes that make webhooks infamous simply stop happening.
FAQ
What’s the actual difference between at-least-once and exactly-once delivery?
At-least-once means the sender guarantees every event is delivered one or more times and resolves any doubt in favor of resending; exactly-once would mean every event is delivered precisely once, with no loss and no duplicates. Svix’s own documentation states plainly that exactly-once isn’t achievable across two systems connected by HTTP, because a sender that times out waiting for a response has no way to know whether the request was lost or only the response was. The practical substitute is at-least-once delivery combined with idempotent processing on the receiver, which produces exactly-once effects even though the transport itself only guarantees at-least-once delivery.
How long should I keep processed event IDs around?
Long enough to cover the sender’s maximum retry window plus a safety margin. If a provider retries for up to three days, a dedup table with only 24 hours of retention will let a late retry slip through as an unintended duplicate. Many teams keep records for 30 days or longer and archive or expire them separately, since the storage cost of an indexed event-ID table is small compared to the cost of a duplicate side effect.
Do I need a message queue to handle webhooks correctly?
Not strictly — the idempotency guarantee comes from the unique-constraint pattern, not from any particular queuing infrastructure. But a queue, or at least an async job system, is worth having for a separate reason: webhook senders expect a fast 2xx response, and real processing (calling other APIs, sending notifications) can take longer than that, so acknowledging receipt immediately and processing asynchronously keeps you inside the sender’s timeout window.
Can I just trust the sender’s IP address instead of verifying signatures?
IP allowlisting is a reasonable extra layer — Stripe recommends it alongside signature verification, not instead of it — but it isn’t sufficient on its own. IP ranges change over time and don’t prove a specific payload wasn’t altered in transit. Signature verification is the mechanism that actually proves a given payload came from someone holding the shared secret and wasn’t tampered with.
What should happen to events that keep failing after every retry?
They need a dead-letter path, not silent disappearance. Mature providers surface an exhausted event for manual resend — Stripe’s dashboard includes a resend action usable for up to 15 days after the event, and its CLI supports resending for up to 30 days — and a production integration should monitor failed-delivery counts so a persistently broken endpoint gets human attention before the retry window closes, not after.
Discover more from Software Online Review
Subscribe to get the latest posts sent to your email.
