Webhook Architecture for Commerce Integrations

Webhook Architecture for Commerce Integrations

A webhook endpoint written like a normal request handler can fail on a vendor retry or reorder. Verify, ack fast, dedupe, replay, and reconcile — vendors such as Stripe document duplicates and disorder.

A webhook endpoint that is written like a normal request handler can fail in production when a vendor retries, reorders, or replays a delivery — behavior that vendors such as Stripe document as possible, not an exception. A durable webhook architecture is five decisions made before the build: verify the signature (and the signed timestamp, where the vendor provides one) before you trust the payload, acknowledge fast and process asynchronously, dedupe and tolerate out-of-order events, persist raw events for replay with a dead-letter path, and reconcile against the vendor's pull API as the safety net. This article gives you that receive-verify-queue-process-reconcile flow and the small code it implies, with the commerce rule that a missed payment event must always reconcile.

Why webhook endpoints fail in production

A common webhook bug is treating the endpoint like an ordinary form handler: parse the body, do the work inline, return when it is done. That code can pass every test in development, where events arrive once, in order, from a trusted caller, and the handler is fast. None of those four assumptions hold in production, and each broken assumption is a separate outage waiting for the day the vendor has a bad hour.

Real delivery terms vary by vendor. Stripe and Shopify document that the same event might occasionally arrive more than once — Shopify names a network timeout or a retry as examples — and both retry failed deliveries, while GitHub does not redeliver failed deliveries automatically (as of Nov 2026). Stripe also does not guarantee that events arrive in the order they were generated. Deliveries can also arrive in bursts; Shopify describes queuing as a useful pattern for handling them and for ensuring you respond within five seconds. And your endpoint cannot tell on its own that a request really came from the vendor — anyone who learns the URL can POST to it. A handler that assumes exactly-once, ordered, fast, trusted delivery is correct only in the environment where you tested it.

Designing for real delivery behavior is a small, fixed set of decisions, and making them before the build is far cheaper than discovering each one through a production incident. The rest of this article is those decisions in the order the request actually flows through them: verify, ack, queue, process idempotently, and reconcile.

Verify before you trust

A webhook endpoint is a public URL that performs privileged work, so the first thing it does — before parsing, before any business logic — is prove the request is genuinely from the vendor. The mechanism Stripe, Shopify, and GitHub document is a signature: the vendor computes a hash-based message authentication code over the raw request body (Stripe also signs a timestamp with it) using a shared secret and sends it in a header; you recompute it and compare. RFC 2104 defines the HMAC construction, and all three use HMAC with SHA-256 (as of Nov 2026). Two implementation details are non-negotiable. Verify against the exact raw bytes of the body, not a re-serialized parse, because any reformatting changes the hash. And compare with a constant-time equality check, not string equality, so the comparison does not leak timing information that would help an attacker guess the expected signature.

Signature verification alone does not stop replay. A valid, correctly signed request captured off the wire is still valid if it is sent again later, so where the vendor signs a timestamp, you reject anything outside a short freshness window — Stripe's libraries default to 5 minutes (as of Nov 2026) — and where it does not, as with GitHub, you use the delivery ID to reject repeats. The timestamp must be part of the signed payload, not a separate unsigned header, or an attacker simply rewrites it. The rule that ties this together: on any mismatch — bad signature, stale timestamp, missing header — reject with a 4xx and do no work. Never return a 2xx for an event you could not verify, because a 2xx tells the vendor to stop retrying, and you have just acknowledged something you never validated.

Fast-ack and queue

The vendor is waiting for your HTTP response, and it has a short timeout. If your handler does the real work inline — write to the database, call other services, send mail — a slow dependency makes your response slow, the vendor's timeout fires, and a vendor that retries failed deliveries, as Stripe and Shopify do, sends again an event you are in the middle of processing. Now the same event can run twice concurrently, and the slow handler that caused the retry is also the one least likely to handle the duplicate safely. The slow-inline handler does not just risk a timeout; it can manufacture the duplicates that break everything downstream.

The fix is fast-ack: the endpoint does the minimum that cannot be deferred and returns immediately. The minimum is verify the signature, persist the raw event durably, and enqueue its identifier for asynchronous processing. Then return a 2xx — measured in milliseconds, not seconds. A worker picks the event off the queue and does the actual work outside the request path, where it can be slow, retry, and fail without the vendor watching the clock. This split is one of the highest-leverage decisions in webhook design: it turns "the vendor's retry timeout is now my correctness problem" into "the vendor got its acknowledgment, and processing is my own internal concern." A structured error body following RFC 9457 Problem Details is useful for the rejection path, but the success path is just a fast, empty 2xx.

Idempotent, order-tolerant processing

Because the same event can be delivered more than once, the worker can see it more than once, so processing must be idempotent. Vendors such as Stripe, Shopify, and GitHub give each event or delivery an identifier; dedupe on it, and check the vendor's documentation for duplicates that arrive under a new ID. Stripe, for example, notes that in some cases two separate Event objects are generated and sent, and says to identify those duplicates by the ID of the object in data.object along with event.type (as of Nov 2026). Before doing the work, record the event id; if it is already recorded as processed, acknowledge and stop. The persisted raw-event store from the fast-ack step doubles as this dedupe ledger — writing the event keyed by its id is both your durability guarantee and your "have I seen this" check. Idempotency here is not optional polish; it is what stands between a replayed backlog and the same order being fulfilled several times.

Because events can arrive out of order, processing must tolerate a later event arriving before an earlier one. For example, a payment event can arrive before the order event it belongs to. The defensive design is a state machine over your own records, driven by event type rather than arrival order: an event that references state you do not have yet does not error and does not get dropped — it is parked and resolved when the prerequisite arrives, or its absence is filled by reconciliation. Encoding "what does this event mean for this entity's state, regardless of when it arrived" into an explicit state machine is what makes out-of-order delivery a non-issue instead of a class of corruption bugs. Assuming order is a common way for a webhook integration to silently produce wrong data while every individual handler looks correct.

Replay, dead-letter, reconciliation

Persist every raw event before you process it, and keep it. The raw store is what makes replay possible: a bug fixed, a downstream dependency recovered, a handler corrected — you reprocess from the stored events instead of reconstructing what happened from logs or asking the vendor to resend. It is also your audit trail when finance asks why an order is in the state it is in. Storing the raw body keyed by event id converts a class of "we lost those events" incidents into a replay command.

Some events cannot be processed no matter how many times you retry: a permanently malformed payload, an event for an entity that was deleted, a bug that needs a code change. Those go to a dead-letter store after bounded retries, rather than blocking the queue behind a poison event or vanishing silently. The dead-letter store is inspectable and replayable, so a poison event becomes a triage item, not a hidden data-loss event. And because delivery can be duplicated and is still not guaranteed — a webhook can be missed entirely if your endpoint was down during its only delivery window and the vendor exhausts its retries — webhooks alone are never a sufficient source of truth. The safety net is periodic reconciliation: on a schedule, pull the vendor's authoritative state through its API and compare it to yours, then repair the differences. For commerce this is not optional. A missed payment event that webhooks never delivered must still be caught, because an order that was paid but never marked paid is a customer who paid and did not get what they bought. The webhook is the fast path; the pull-API reconciliation is the guarantee.

The webhook design summary

The deliverable is one flow you implement once and every event passes through: receive, verify, persist, ack, queue, process idempotently, and reconcile out of band. The endpoint itself stays small — its only jobs are to prove the request is genuine and to get out of the vendor's way fast:

typescript
import { createHmac, timingSafeEqual } from 'node:crypto'

const REPLAY_WINDOW_MS = 5 * 60_000

// Verify signature AND timestamp against the raw bytes, before any logic.
function verify(rawBody: Buffer, header: string, secret: string): boolean {
  const [tsField, sigField] = header.split(',')
  if (!tsField || !sigField) return false // missing or malformed header -> 4xx
  const timestamp = Number(tsField.split('=')[1])
  const provided = Buffer.from(sigField.split('=')[1] ?? '', 'hex')

  // Reject stale deliveries: a captured request must not replay later.
  if (Math.abs(Date.now() - timestamp * 1000) > REPLAY_WINDOW_MS) return false

  const expected = createHmac('sha256', secret)
    .update(`${timestamp}.`)
    .update(rawBody)
    .digest()
  // Constant-time compare of the signature bytes.
  return provided.length === expected.length && timingSafeEqual(provided, expected)
}

// Fast-ack: verify, persist raw (idempotent on event id), enqueue, return 2xx.
// Assumes raw-body middleware, e.g. express.json({ verify: (req, res, buf) => { req.rawBody = buf } }).
app.post('/webhooks/vendor', async (req, res) => {
  if (!verify(req.rawBody, req.header('X-Signature') ?? '', WEBHOOK_SECRET)) {
    return res.status(400).end() // never 2xx an unverified event
  }
  const event = JSON.parse(req.rawBody.toString()) // event id location varies by vendor (body field or a delivery-ID header)
  await rawEvents.putIfAbsent(event.id, req.rawBody) // durable + dedupe ledger
  await queue.enqueue(event.id)                       // process out of band
  res.status(202).end()                               // ack in milliseconds
})

Everything hard happens behind that queue, in a worker that can be slow, retry, dead-letter, and reorder safely, and that treats the vendor's pull API as the final word. The five decisions are the architecture: verify before trust, ack fast, dedupe and tolerate disorder, persist for replay with a dead-letter path, and reconcile. The commerce non-negotiable sits on top of all of them — a missed payment event must always reconcile, because the cost of getting that one wrong is not a refreshed page, it is a dispute and a customer who no longer trusts the storefront.

Diagnostic checklist for the next planning cycle

  • Verify the signature against the raw request bytes with a constant-time comparison, before any parsing
  • Where the vendor signs a timestamp, reject deliveries outside a short freshness window, and never 2xx an unverified event
  • Split the endpoint into fast-ack plus an asynchronous worker — persist, enqueue, return in milliseconds
  • Dedupe by the vendor's event or delivery ID (plus any duplicate rule the vendor documents) and design processing as a state machine that tolerates out-of-order arrival
  • Persist every raw event and build a replay path and a dead-letter store for poison events
  • Schedule pull-API reconciliation as the safety net, and make a missed payment event impossible to lose silently
Project Inquiry