Tech #023•35 min read•15 October 2026 , Thursday

Payment Webhooks Lie. Your Billing Shouldn't.

A payment gateway may send you the same message twice, in the wrong order, too early, too late, or not at all. Here is how to handle payment updates safely, so your system stays correct no matter how the message arrives.

Rajnish Kumar
Rajnish Kumar

Editor-in-Chief & Founder

Payment Webhooks Lie. Your Billing Shouldn't. — Tech dispatch hero image

#01First, What Is a Payment Gateway?

When a customer pays on a website or in an app, the website itself almost never talks to the bank. That job belongs to a Payment Gateway: a service like Stripe, Razorpay, PayPal, or Braintree that sits between your business and the world of banks, card networks, and UPI. Your app tells the gateway "charge this customer this amount." The gateway collects the card or UPI details securely, talks to the customer's bank, handles fraud checks and security steps like a one-time password, and finally moves the money into your account. You get to accept payments without storing card numbers or connecting to dozens of banks yourself.

The important thing to understand is that a payment is not a single instant event. Some steps finish in a second. Others take much longer. A customer may need to approve the payment in their banking app. A bank transfer may take hours or days to clear. A card payment can succeed today and be disputed by the customer next month. A subscription renews on the 1st of every month while the customer is asleep and nobody is on your website at all. In all of these cases, the final answer isn't known at the moment your app asks for the payment. It arrives later.

So the gateway needs a way to tell your system "something just happened" whenever it happens, not only when your code asks. Your app could keep asking the gateway every few seconds, "has anything changed yet?", but for thousands of payments that would be slow and wasteful. That's the problem webhooks solve.

The list below shows the kinds of news a payment gateway typically needs to deliver to you after the original request is long finished.

Your app starts a payment in one moment. The gateway finishes it in many moments, and has to tell you about each one.

  • Payment succeeded: the bank confirmed, and the money is on its way to you.
  • Payment failed: the card was declined, or the customer never completed approval.
  • Subscription renewed: the monthly or yearly charge went through without the customer doing anything.
  • Refund processed: money went back to the customer.
  • Dispute opened: the customer asked their bank to reverse a charge.

#02What a Webhook Really Is

Most of the time, your code calls other systems. You ask an API for something, and it answers. A Webhook turns that around. When something happens on the other side, like a payment succeeding, a subscription renewing, or a refund being issued, the other system calls you. It sends an HTTP POST request to a URL you registered, with a small JSON message describing what happened.

That sounds simple, and the first version of a webhook handler usually is. Read the JSON, find the order, mark it paid, return 200. It works in testing. It works in the demo. Then, a few weeks into production, a customer is marked as paid twice, a refund is applied before the payment it refunds, or a payment arrives for an order that was cancelled last month. None of these are rare bugs. They are the normal behavior of webhooks, and the first version of the handler simply didn't plan for them.

A useful way to picture a webhook is a courier delivering an important letter to your office. The courier has one job: make sure you got it. If nobody signs for it, the courier comes back tomorrow with the same letter. If the office is busy and the receptionist takes too long, the courier leaves and tries again later. If there are three letters, they may arrive in any order, because they went through different sorting centers. And on a bad day, a letter may simply get lost. You don't control the courier. You only control what happens at your front desk when a letter arrives.

That's the shift this article is about. The question is not "how do I process a webhook?" It is "how do I build a front desk that does the right thing no matter how many times, in what order, or how late the same letter arrives?" This article uses payments as the main example, because that's where getting it wrong costs real money. But everything here applies to any webhook: Git hosting events, e-commerce orders, CRM updates, or messages from your own internal services.

Concretely, a payment webhook is just an HTTP POST request with a JSON body and a few headers. A simplified example of what lands on your server is shown below. Notice three things in it, because each one becomes important later: the event's own ID, the type of event, and the ID of the payment it's about.

A webhook isn't a function call. It's a letter, and the post office makes no promises about how many copies you'll get.

json
POST /webhooks/payments
Content-Type: application/json
Stripe-Signature: t=1760510400,v1=5257a869e7ec...
{
"id": "evt_1Q2w3E",
"type": "invoice.paid",
"created": 1760510400,
"data": {
"object": {
"id": "in_9Xy8Wv",
"amount_paid": 4900,
"currency": "usd",
"metadata": { "order_ref": "ord_10482" }
}
}
}

#03At-Least-Once Is the Contract

Why do webhooks arrive more than once? Because the sender can't know for sure that you received them. Imagine the gateway sends a webhook, and your server processes it and replies "200 OK." But the reply gets lost on the way back, or arrives one second after the gateway stopped waiting. From the gateway's side, this looks exactly like a failure. So it sends the same event again. The gateway has two choices: risk sending twice, or risk never delivering at all. For payments, never delivering is worse. So every serious provider chooses to send again.

This promise has a name: At-Least-Once Delivery. The sender guarantees that you'll get each event at least once, as long as your endpoint eventually works. It does not guarantee you'll get it only once. A promise of "exactly once" across a network is, for practical purposes, impossible, because no sender can tell the difference between "the receiver didn't get it" and "the receiver got it but the reply was lost." What you can build is something better in practice: at-least-once delivery plus a receiver that gives the same result no matter how many times it sees the same event. That property is Idempotency, and it is the core of everything that follows.

The providers say this plainly in their documentation. Stripe's webhook guide says "Webhook endpoints might occasionally receive the same event more than once." Razorpay's webhook FAQ explains that if your server accepts an event but doesn't respond within 5 seconds, the attempt is treated as failed and the event is sent again. The Standard Webhooks specification, an open format several API companies now follow, recommends that senders retry "following a retry schedule spanning multiple days, with an exponential backoff." means each retry waits longer than the last, so a struggling server isn't flooded.

The retry rules differ a lot between providers, and the differences matter for your design. The table below compares a few well-documented ones. Notice the last row in particular: not every provider retries at all.

Exactly-once delivery is a myth. Exactly-once effect is a design choice you make on your side.

ProviderTimeout per attemptAutomatic retriesUnique ID for dedupe
StripeMust reply quickly with 2xx before heavy workUp to three days with exponential backoff in live mode; three times over a few hours in sandboxEvent ID
Razorpay5 secondsFor 24 hours with exponential backoff, then the webhook is disabledx-razorpay-event-id header
GitHub10 secondsNone. GitHub says it "does not automatically redeliver failed deliveries"X-GitHub-Delivery header
Standard Webhooks specNot fixedRecommends a schedule spanning multiple days with backoffwebhook-id header, same across retries

#04The Five Ways a Webhook Lies

If you design for "one event, delivered once, in order, on time," you are designing for a world that doesn't exist. In practice, webhook delivery breaks that ideal in exactly five ways. Almost every webhook bug in a billing system falls into one of them. The rest of this article walks through each one in turn, but it helps to see all five side by side first, summarized below.

The word "lies" is a little unfair to the gateway. It isn't doing anything wrong. Each of these behaviors is a sensible result of how networks and distributed systems work. But from the point of view of a handler that assumed a perfect world, each one feels like being lied to: the event said "paid," and yet it's the second time; the event said "refunded," and yet the payment hasn't arrived; the event said "renewed," and yet it belongs to a subscription you closed in March.

Before any of the five, there is a front door. A webhook endpoint is a public URL, and anyone on the internet can send it a POST request. So the very first job is to check that the letter is genuine, and the second is to accept it quickly so the courier doesn't come back. We'll cover both of those first, then each of the five lies.

A good handler doesn't trust the delivery. It trusts its own rules for what each delivery is allowed to change.

LieWhat actually happensThe control
1. DuplicateThe same event arrives two or more timesRemember what you've processed; make every change safe to repeat
2. Out of orderA later event arrives before an earlier oneAllow only valid state changes; don't trust arrival order or timestamps
3. EarlyA payment arrives before your bill or order existsRecord the money anyway and match it later; never drop it
4. LateAn event arrives for an old cycle or an old subscriptionRoute by a reference you control; never reopen a finished record
5. NeverThe event is lost and never arrivesReconcile regularly against the provider's own records

#05The Front Door: Is This Really From the Gateway?

Your webhook URL is public. If your handler marks orders as paid whenever it receives a well-formed "payment succeeded" message, then anyone who discovers the URL can mark their own order as paid with a single curl command. Stripe's documentation is blunt about this: "Without verification, an attacker could send fake webhook events to your endpoint to trigger actions like fulfilling orders, granting account access or modifying records."

The standard protection is a signature. When you register a webhook, the provider gives you a secret that only the two of you know. For every delivery, the provider computes an , a kind of fingerprint made by mixing the secret with the exact bytes of the message, and puts it in a header. Your server computes the same fingerprint using the same secret and the bytes it received. If the two match, the message really came from the provider and wasn't changed on the way. Stripe uses HMAC with SHA-256 and sends the result in a Stripe-Signature header. The Standard Webhooks spec signs the message ID, the timestamp, and the body together, in the form msg_id.timestamp.payload.

Three details trip people up. First, you must verify against the raw body, exactly as it arrived. Many web frameworks parse JSON automatically, and if you re-serialize that parsed object, spacing or key order can change, and the signature won't match. Stripe warns that "Any manipulation to the raw body of the request causes the verification to fail." Second, compare signatures with a Constant-Time Comparison. A normal string comparison stops at the first different character, and an attacker can, in principle, measure that tiny time difference to guess a signature byte by byte. Stripe's guide tells you to use a constant-time comparison for exactly this reason.

Third, a valid signature isn't enough on its own. An attacker who captures one real, signed webhook could send it again later. That's a Replay Attack. The defense is a timestamp that is included in the signed content, so it can't be changed without breaking the signature. Your server rejects messages whose timestamp is too old. Stripe's libraries use a default tolerance of 5 minutes, and Stripe warns not to set the tolerance to 0, because that "disables the recency check entirely." Many providers also publish the IP addresses they send from, and allowing only those addresses at your firewall adds a second, independent layer.

The example below shows signature verification in Node.js, in the Stripe style. In production, prefer the provider's official library, which handles all of this for you. Seeing it written out once makes it clear what the library is actually checking.

A webhook without a verified signature isn't a message from your gateway. It's a message from anyone who knows your URL.

typescript
import { createHmac, timingSafeEqual } from "node:crypto";
const TOLERANCE_SECONDS = 5 * 60;
// rawBody must be the exact bytes received, NOT JSON.stringify(req.body)
function verifySignature(rawBody: Buffer, header: string, secret: string): boolean {
// Header looks like: t=1492774577,v1=5257a8...,v0=6ffbb5...
const parts = Object.fromEntries(header.split(",").map((kv) => kv.split("=") as [string, string]));
const timestamp = Number(parts.t);
const received = parts.v1;
if (!timestamp || !received) return false;
// Replay protection: the timestamp is inside the signed content, so it can't be faked
const age = Math.abs(Date.now() / 1000 - timestamp);
if (age > TOLERANCE_SECONDS) return false;
const expected = createHmac("sha256", secret)
.update(`${timestamp}.${rawBody.toString("utf8")}`)
.digest("hex");
const a = Buffer.from(expected, "hex");
const b = Buffer.from(received, "hex");
return a.length === b.length && timingSafeEqual(a, b); // constant-time comparison
}

#06Answer First, Work Later

Here is a surprising fact: a large share of duplicate webhooks are caused by the receiver itself. Every provider gives you only a few seconds to reply. GitHub says your server "should respond with a 2XX response within 10 seconds." Razorpay's limit is 5 seconds. If your handler verifies the signature, looks up the order, updates three tables, calls the accounting system, and sends a receipt email before it replies, it will sometimes take longer than that. The provider gives up, marks the delivery as failed, and sends the same event again later, while your first attempt is still running. Now you have two copies of the same work happening at once.

The fix is to separate receiving from processing. Stripe's guide puts it directly: your endpoint "must quickly return a successful status code (2xx) before any complex logic that could cause a timeout." It also recommends processing events "with an asynchronous queue," and gives a very relevant example: a large spike in deliveries "during the beginning of the month when all subscriptions renew" can overwhelm a handler that does everything in the request.

The most reliable way to do this is an inbox table, sometimes called the Inbox Pattern. The handler does only three things: verify the signature, save the raw event into an inbox table, and return 200. A separate background worker reads the inbox and does the real processing. The key detail is the order of the second and third steps. Save first, then reply. If you reply before the event is safely stored, and your server crashes a moment later, the event is gone, and the provider will never send it again, because you told it everything was fine.

The inbox table also gives you the first layer of duplicate protection for free. Give it a Unique Constraint on the provider's event ID. When the same event arrives a second time, the insert simply does nothing, and you still reply 200, because from the provider's point of view the delivery succeeded. Replying with an error to a duplicate would only make the provider send it again.

The example below shows a complete receiving handler, using PostgreSQL's ON CONFLICT DO NOTHING.

The webhook endpoint's only job is to say "got it" honestly. Everything else can wait for a worker.

typescript
// POST /webhooks/payments
app.post("/webhooks/payments", express.raw({ type: "application/json" }), async (req, res) => {
const signature = req.header("Stripe-Signature") ?? "";
if (!verifySignature(req.body, signature, process.env.WEBHOOK_SECRET!)) {
return res.status(400).send("bad signature"); // not from the gateway: reject
}
const event = JSON.parse(req.body.toString("utf8"));
// Store first. The unique key on (provider, event_id) makes a duplicate a no-op.
await db.query(
`INSERT INTO webhook_inbox (provider, event_id, event_type, payload, received_at, status)
VALUES ('stripe', $1, $2, $3, now(), 'pending')
ON CONFLICT (provider, event_id) DO NOTHING`,
[event.id, event.type, event],
);
return res.status(200).send("ok"); // then reply, fast
});

#07Lie 1: Duplicates, Handled in Two Layers

The inbox's unique key catches the simple duplicate: the exact same event delivered twice. But that's only the first of two layers, and relying on it alone is a common mistake.

The second layer exists because the same business fact can arrive under different event IDs. Stripe's documentation notes that "In some cases, two separate Event objects are generated and sent," and recommends identifying those duplicates using the ID of the underlying object together with the event type. A manual resend from a dashboard, a migration between two webhook endpoints, or a provider's own internal retry can also produce what looks like a new event for something you already handled. Your inbox sees two different event IDs and happily accepts both. If your processing logic isn't safe to repeat, the customer is credited twice.

So the real protection has to live in the business data, not just the inbox. For payments, the strongest version is simple: every payment the gateway reports has its own transaction ID, and your payments table should have a unique constraint on it. Recording a payment then means inserting a row, and a second insert for the same transaction does nothing, whatever event it came from. This is the Idempotent Consumer pattern, described by Chris Richardson on microservices.io: "Make a consumer idempotent by having it record the IDs of processed messages in the database." The important detail is to do the check and the business update in the same database transaction, so there is no moment in between where two workers can both decide "this is new."

This is the receiving-side mirror of what we covered in The Hardest Part of Idempotency Happens After the Database Commit. There, the danger was your system doing an outside action twice. Here, the danger is the outside world telling your system the same thing twice. In both cases, the answer is the same: give each real-world fact a unique identity, and let the database refuse to record it twice.

The example below records a payment exactly once, inside one transaction, no matter how many events report it.

Dedupe the delivery to save work. Dedupe the business fact to stay correct.

sql
-- One row per real-world payment, whatever event or retry reported it
CREATE TABLE payments (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT REFERENCES orders(id),
gateway_txn_id TEXT NOT NULL UNIQUE, -- the real dedupe key
amount_cents BIGINT NOT NULL,
currency TEXT NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Inside the worker, in ONE transaction:
BEGIN;
INSERT INTO payments (order_id, gateway_txn_id, amount_cents, currency)
VALUES ($1, $2, $3, $4)
ON CONFLICT (gateway_txn_id) DO NOTHING; -- second report of the same payment: no-op
UPDATE webhook_inbox SET status = 'processed', processed_at = now()
WHERE provider = 'stripe' AND event_id = $5;
COMMIT;

#08When There's No Useful ID: Make the Change Itself Idempotent

Not every event carries a clean transaction ID you can put a unique constraint on. Some events describe a change of state, like "subscription renewed," "invoice marked uncollectible," or "dispute closed," rather than a new thing to record. For these, you can't dedupe by inserting a row. You have to make the update itself safe to repeat.

The rule is to write updates that describe the final state, not the change. "Set status to paid" is idempotent: run it once or ten times, and the status is paid. "Add the amount to the balance" is not: run it twice, and the balance is wrong. "Toggle the flag" is the worst of all, because the second run undoes the first. When you review a webhook handler, look for every +=, every counter increment, and every toggle. Each one is a duplicate bug waiting to happen.

A useful habit is to make updates conditional on the current state. Instead of UPDATE orders SET status = 'paid' WHERE id = $1, write UPDATE orders SET status = 'paid', paid_at = now() WHERE id = $1 AND status = 'awaiting_payment'. The first time, it changes one row. The second time, it changes zero rows, because the order is no longer awaiting payment. Your code can check the number of affected rows to know whether this run did anything new. That number is also a great log line: "applied" versus "already applied" tells you instantly whether you're seeing duplicates.

If you truly need a running total, like a prepaid wallet balance, don't store the total as the source of truth. Store each credit and debit as its own row with a unique reference, and compute the balance from those rows, or update the cached total in the same transaction as the insert. Accountants have worked this way for centuries: a ledger of entries is safe to audit and safe to repeat; a single number that people keep editing is neither.

The example below contrasts the two styles.

"Set it to paid" survives a retry. "Add the money again" doesn't.

sql
-- NOT safe to repeat: a duplicate event doubles the credit
UPDATE wallets SET balance_cents = balance_cents + $2 WHERE customer_id = $1;
-- Safe to repeat: describe the final state, and only from the expected state
UPDATE orders
SET status = 'paid', paid_at = now()
WHERE id = $1 AND status = 'awaiting_payment'; -- 0 rows on a duplicate
-- Safe running totals: a ledger of unique entries
INSERT INTO wallet_entries (customer_id, reference, amount_cents)
VALUES ($1, $2, $3)
ON CONFLICT (reference) DO NOTHING; -- the balance is SUM(amount_cents)

#09Lie 2: Out of Order

Events don't just repeat. They also arrive in the wrong order. Stripe's documentation says it "doesn't guarantee the delivery of events in the order that they're generated," and gives a realistic example: creating a subscription can produce customer.subscription.created, invoice.created, invoice.paid, and charge.created, and your endpoint must not depend on receiving them in that order. Retries make this worse. If the first delivery of event A fails and is retried an hour later, event B, which happened after A, will reach you first.

The obvious fix is to sort events by their timestamp. Stripe explicitly warns against it: event timestamps are recorded in seconds, "so distinct events can share a timestamp. Don't use created to determine event order or whether you've already processed an event." Arrival time is even worse, for the reasons above.

The reliable fix is a State Machine: a clear list of the states a record can be in, and the only transitions allowed between them. An invoice can go from open to paid, and from paid to refunded. It can never go from refunded back to paid. Once you have this list, the order of events stops mattering for correctness. If a "refunded" event arrives for an invoice that is still open, because the "paid" event hasn't arrived yet, your handler doesn't apply it blindly. It either waits and retries the event later, or, better, asks the provider for the current state of the invoice, which we'll come to in the next section. And if an old "paid" event arrives after the invoice is already refunded, the state machine simply refuses to move backwards.

Some providers give you a version number or a sequence on each object. Where that exists, it's the cleanest tool of all: store the last version you applied, and ignore any event whose version is lower. The state machine still matters, though, because many events carry no version, and because your own business rules ("a cancelled order can never become paid") are not something the provider can enforce for you.

The example below shows a small transition table and the guard every update goes through.

Arrival order is a fact about the network. Allowed transitions are a fact about your business. Only the second should decide.

typescript
type InvoiceStatus = "open" | "paid" | "refunded" | "void";
const ALLOWED: Record<InvoiceStatus, InvoiceStatus[]> = {
open: ["paid", "void"],
paid: ["refunded"],
refunded: [], // terminal
void: [], // terminal
};
async function applyTransition(invoiceId: string, to: InvoiceStatus): Promise<"applied" | "ignored" | "deferred"> {
const { status: from } = await invoices.get(invoiceId);
if (from === to) return "ignored"; // duplicate: already there
if (ALLOWED[from].includes(to)) {
// Conditional update: only succeeds if nobody else moved it in the meantime
const changed = await invoices.updateStatusIf(invoiceId, from, to);
return changed ? "applied" : "deferred";
}
// Not a legal move from here. Either it's stale (ignore) or an earlier event is missing (defer).
return isBehind(from, to) ? "ignored" : "deferred";
}

#010Thin Events: Treat the Webhook as a Doorbell, Not a Letter

There is a different way to solve both duplicates and ordering, and many providers are moving toward it. Instead of trusting the data inside the webhook, treat the webhook only as a signal that something changed, and then ask the provider for the current state.

Think of it as a doorbell instead of a letter. A letter carries content, and if two letters arrive in the wrong order, you have to work out which one is newer. A doorbell carries nothing. It just tells you to go and look. If the doorbell rings three times, you look three times, and you see the same thing each time: the current truth.

Stripe has built this into its newer event format. It offers two payload styles. "Snapshot" events carry a copy of the object at the moment of the event, and Stripe notes this data can be out of date by the time you process it. "Thin" events carry little more than the ID of the object that changed, and its libraries provide a fetchRelatedObject() method to retrieve "the latest version of the object associated with the event." For new integrations, Stripe's dashboard now labels thin payloads as the recommended choice. The Standard Webhooks spec makes the same argument from the design side: "you can always make a thin one full, but not the other way around."

Fetching current state solves several lies at once. A duplicate event leads to a duplicate fetch, which returns the same state, so applying it twice changes nothing. An out-of-order event leads to a fetch of the newest state, so you never apply something stale. Even a late event is harmless, because you apply what is true now, not what was true then.

It isn't free, though. Every event now costs an extra API call, which adds latency and counts against the provider's rate limits. During a spike, like the start of a billing month, that can matter. And you still need your own state machine and unique constraints, because two workers fetching at the same moment can still race each other. A good rule of thumb: fetch current state for anything involving money or access, and use the snapshot for low-stakes events where an occasional stale value does no harm.

The list below sums up the trade-off.

A letter tells you what was true. A doorbell sends you to see what is true now.

  • Snapshot payloads: No extra call, and fast. But the data may be stale, and order and duplicates are entirely your problem.
  • Thin payloads plus fetch: Always current, and duplicates and order matter much less. But each event costs an extra API call and depends on the provider's API being up.
  • Practical mix: Fetch for payments, refunds, disputes, and anything that grants or removes access. Use the snapshot for notifications, analytics, and other low-risk events.

#011Lie 3: The Payment That Arrives Before the Bill

Sometimes the money arrives before your system is ready for it. A customer pays through a hosted payment page, and the "payment succeeded" webhook reaches you before the request that creates your own order record has finished. A bank transfer arrives with a reference your system hasn't generated yet. A subscription renewal is charged by the gateway a few seconds before your own renewal job runs and creates this cycle's invoice. In all of these, the handler looks for the record the payment belongs to, finds nothing, and has to decide what to do.

The worst choice, and a very common one, is to log a warning and return. The event is marked processed. The provider won't send it again. And somewhere there is a customer who paid and whose account shows nothing. This is the one bug in this article that turns directly into an angry support ticket, because from the customer's side it looks like you took their money and lost it.

The rule is simple: never drop money. If a payment arrives and you can't find what it belongs to, record it anyway, in a holding state. Two designs work well. The first is to create the missing record from the payment itself. If the payment clearly belongs to a known customer and cycle, create the invoice or order right there, already marked as paid, using an insert that won't duplicate it if the normal flow creates it a moment later. The second is an "unmatched payments" table: the payment is saved with everything you know about it, and a matching job, or a person, links it to the right record later. Either way, the money is visible, accounted for, and can't disappear.

The second half of this rule is about the normal flow. When your own code later goes to create the invoice for that cycle, it must check whether a payment already exists and, if so, adopt it rather than creating a second, unpaid invoice for the same period. Unique keys on the business identity help here too. If there can only be one invoice per subscription per billing cycle, a database constraint on that pair makes the "create" step safe whichever side gets there first.

The example below shows the "create or adopt" pattern.

A payment you can't match is still a payment. Park it, never drop it.

sql
-- One invoice per subscription per cycle, whoever creates it first
ALTER TABLE invoices ADD CONSTRAINT one_invoice_per_cycle UNIQUE (subscription_id, cycle_start);
-- Payment webhook arrives first: create the invoice as paid
INSERT INTO invoices (subscription_id, cycle_start, amount_cents, status, paid_at)
VALUES ($1, $2, $3, 'paid', now())
ON CONFLICT (subscription_id, cycle_start)
DO UPDATE SET status = 'paid', paid_at = COALESCE(invoices.paid_at, now())
WHERE invoices.status = 'open'; -- adopt an open invoice; never touch a closed one
-- If the payment can't be tied to any subscription at all, park it
INSERT INTO unmatched_payments (gateway_txn_id, amount_cents, currency, raw_reference, received_at)
VALUES ($4, $3, $5, $6, now())
ON CONFLICT (gateway_txn_id) DO NOTHING;

#012Lie 4: Late Events and Old Records

The opposite problem is just as real. An event arrives for something that is already over. A refund for an order from three months ago. A payment retry that finally succeeded for a cycle you already marked as unpaid and closed. A dispute opened long after the original charge. A delayed delivery that sat in the provider's retry queue for two days while your endpoint was down. These events are valid. They're just late, and a handler that assumes every event is about "the current" record will put them in the wrong place.

The most common mistake is looking up the target record by "the latest one." A payment arrives for a customer, so the handler finds the customer's most recent invoice and marks it paid. That works until the payment is actually for last month's invoice, and this month's invoice gets marked paid instead. Now last month still looks unpaid, this month looks paid by mistake, and the books are wrong in two places at once.

The fix is to route every event by a reference you control. When you create a payment, invoice, or checkout session with the provider, store your own record's ID in the provider's metadata or reference field. Most gateways support this. When the webhook comes back, it carries that reference, and you go straight to the right record, however old. "The latest" should never be how a webhook finds its target.

The second rule for late events is just as important: never reopen a finished record. If a late payment arrives for a cycle that was already closed as unpaid, don't flip that old record back to "paid" and re-run everything that happens on payment, like renewal, activation, or receipt emails. Those side effects belong to the moment the cycle was live, not to today. Instead, record the payment as its own fact, against that old cycle, and let a clear business rule decide what happens next: apply it as a credit, refund it, or flag it for a person. Terminal states in your state machine, like closed, refunded, and void, exist precisely so that late news can't quietly rewrite history.

The table below shows how common late events should be handled.

Late news should be recorded against the past. It should never be allowed to rewrite it.

Late eventWrong handlingRight handling
Payment for an old, unpaid cycleMark "the latest invoice" paidFind the cycle by stored reference; record the payment against it; apply a rule such as credit or refund
Refund for a months-old orderReopen the order and re-run its workflowAdd a refund entry linked to that order; leave its finished status alone
Renewal event for a cancelled subscriptionReactivate the subscriptionCheck the subscription's terminal state; record and alert instead of reactivating
Delayed retry after an outageProcess it as if it were newProcess normally; dedupe and state rules make it safe

#013Lie 5: The Webhook That Never Arrives

The four lies so far are all about events that arrive in an inconvenient way. The fifth is the most dangerous, because nothing happens at all. The event is simply never delivered, and nothing in your system notices.

This happens more often than people expect. Your endpoint was down longer than the provider's retry window. Razorpay, for example, disables a webhook after failures continue for 24 hours. GitHub doesn't retry failed deliveries at all. Someone rotated the signing secret, and for an hour every delivery failed verification. A deploy broke the route. The endpoint was removed from the provider's dashboard during a cleanup. In every case, the provider's records and yours quietly drift apart, and the first sign is usually a customer asking why their account was suspended when they paid.

That's why webhooks should never be your only source of truth. Treat them as the fast path: the quick, usually reliable way to learn about changes in near real time. Then add Reconciliation as the safety net: a scheduled job that asks the provider directly what happened, and compares that with what your system recorded. Most payment providers let you list recent payments, invoices, or events through their API, so the job can fetch everything from the last day, look up each item in your own tables, and handle any mismatch. Payments the provider has but you don't get recorded, through exactly the same idempotent code path the webhook uses. Differences in status get flagged.

The beauty of the earlier sections is that they make reconciliation easy. Because recording a payment is idempotent, the reconciliation job can safely "re-record" everything it finds, and only the truly missing ones actually change anything. The webhook and the reconciler don't need to coordinate. They both feed the same front door, and the unique constraints make sure each fact lands once.

How often should it run? It depends on how quickly a missed event hurts. For payments that unlock access, hourly is common. For end-of-month billing, a daily run plus one just before the billing job is a sensible minimum. The example below shows the shape of such a job.

Webhooks tell you what changed, quickly. Reconciliation tells you what's true, eventually. You need both.

typescript
// Runs on a schedule. Uses the SAME idempotent function the webhook worker uses.
async function reconcilePayments(since: Date) {
let cursor: string | undefined;
let fixed = 0;
do {
const page = await gateway.listPayments({ createdAfter: since, startingAfter: cursor, limit: 100 });
for (const p of page.data) {
const result = await recordPayment({ // INSERT ... ON CONFLICT DO NOTHING inside
gatewayTxnId: p.id,
orderRef: p.metadata.order_ref, // our own reference, stored at creation
amountCents: p.amount,
currency: p.currency,
});
if (result === "inserted") fixed++; // a payment the webhook never told us about
}
cursor = page.hasMore ? page.data[page.data.length - 1].id : undefined;
} while (cursor);
metrics.gauge("reconcile.payments_recovered", fixed);
if (fixed > 0) alerts.warn(`Reconciliation recovered ${fixed} payments missed by webhooks`);
}

#014Processing the Inbox Safely

With the inbox pattern, the hard work moves to a background worker. That worker has its own set of problems, and getting them right is what turns a simple queue into a reliable one.

The first problem is two workers grabbing the same event. If you run several workers, which you should for throughput, they can both read the same pending row and process it at the same time. PostgreSQL has a clean answer: SELECT ... FOR UPDATE SKIP LOCKED. Each worker locks the rows it takes, and other workers skip locked rows instead of waiting for them. Combined with the idempotent processing from earlier, this makes concurrent workers both fast and safe. Most queue systems offer an equivalent.

The second problem is failure. Processing will sometimes fail: the provider's API is down when you try to fetch current state, the database times out, or a bug throws an exception. The worker should retry with backoff, and count the attempts. After a fixed number of failures, it should stop retrying and move the event to a Dead-Letter Queue, which is simply a holding area for events that need a person to look at them. Without this, one broken event, sometimes called a "poison message," gets retried forever and can block everything behind it.

The third problem is ordering within one record. Even with a state machine, it helps not to process two events for the same invoice at the same moment. A simple approach is to lock the business record itself while processing, with SELECT ... FOR UPDATE on the invoice row, so that two events for the same invoice are applied one after the other, while events for different invoices still run in parallel.

Finally, keep the inbox rows. Don't delete events once they're processed. Keep them, with their status, attempt count, and any error, for at least as long as you might need to investigate a billing dispute. The inbox becomes your audit trail: exactly what the provider told you, when, how many times, and what you did about it.

The example below shows a worker loop with all four ideas.

A queue that can't fail safely just moves the outage from the endpoint to the worker.

sql
-- Claim a batch of pending events; other workers skip these rows instead of waiting
WITH batch AS (
SELECT id FROM webhook_inbox
WHERE status = 'pending' AND next_attempt_at <= now()
ORDER BY received_at
LIMIT 20
FOR UPDATE SKIP LOCKED
)
UPDATE webhook_inbox w SET status = 'processing', attempts = attempts + 1
FROM batch WHERE w.id = batch.id
RETURNING w.*;
-- On failure: back off, or give up after too many attempts
UPDATE webhook_inbox
SET status = CASE WHEN attempts >= 8 THEN 'dead_letter' ELSE 'pending' END,
next_attempt_at = now() + (interval '30 seconds' * power(2, attempts)),
last_error = $2
WHERE id = $1;

#015Testing: Send It Twice, Send It Backwards, Send It Never

Most webhook handlers are tested exactly once per event type: send the event, check the result. That test proves the handler works in the perfect world. The bugs live in the other worlds, and each of the five lies gives you a test you can write.

The single most valuable test is the "send it twice" test. For every event type your handler supports, send the same event two times and assert that the final state is identical to sending it once: one payment row, one status change, one email queued. This one test, applied to every handler, catches the majority of real webhook bugs. It's cheap to write, and once it's in place, any future change that breaks idempotency fails CI immediately.

Then write tests for order: send "refunded" before "paid," and check that the result is still correct once both have arrived. Write a test for the early case: send a payment for an invoice that doesn't exist yet, and assert that the money is recorded somewhere, not dropped. Write a test for the late case: send a payment for an old, closed cycle, and assert that the old record is not reopened and the current record is untouched. And write a test for "never": skip the webhook entirely, run the reconciliation job, and assert that the payment is recovered.

Two more tests protect the front door. Send a correctly formed event with a bad signature, and assert it's rejected. Send a correctly signed event with an old timestamp, and assert it's rejected too. Most providers also offer tools for this. Stripe's CLI, for example, can forward real test events to your local machine and resend specific events, which makes the duplicate test easy to run against a real payload.

The list below summarizes the tests, and the example after it shows the "send it twice" test.

If your test suite only sends each webhook once, it's testing the one scenario production never gives you.

  • Duplicate: The same event twice gives the same state as once.
  • Same fact, different event IDs: Two events reporting the same payment create one payment row.
  • Out of order: A later event first, then the earlier one, gives the correct final state.
  • Early: A payment before its invoice exists is recorded, then adopted when the invoice is created.
  • Late: A payment for a closed cycle doesn't reopen it or touch the current cycle.
  • Never: No webhook, then reconciliation, recovers the payment.
  • Front door: A bad signature is rejected; an old timestamp is rejected.
typescript
test("payment_succeeded is idempotent: twice equals once", async () => {
const invoice = await factory.openInvoice({ amountCents: 4900 });
const event = fakeEvent("payment_succeeded", {
id: "evt_123", txnId: "txn_abc", invoiceRef: invoice.id, amountCents: 4900,
});
await deliverWebhook(event);
await runWorkerUntilIdle();
const afterOnce = await snapshotBillingState(invoice.id);
await deliverWebhook(event); // same event again
await deliverWebhook({ ...event, id: "evt_456" }); // same fact, new event ID
await runWorkerUntilIdle();
const afterRepeats = await snapshotBillingState(invoice.id);
expect(afterRepeats).toEqual(afterOnce);
expect(await countPayments({ gatewayTxnId: "txn_abc" })).toBe(1);
expect(await countEmailsQueued({ invoiceId: invoice.id, kind: "receipt" })).toBe(1);
});

#016One Payment, Every Lie: A Walkthrough

It's worth walking a single realistic payment through the whole design, because it shows how the layers work together. None of them is enough alone. Together, each one catches what the others miss.

A customer's monthly subscription renews on the 1st. The gateway charges their card at 00:00:03. Your own renewal job, which creates this month's invoice, is scheduled for 00:05. So the "payment succeeded" webhook arrives at 00:00:04, before the invoice exists. That's the early lie. The handler verifies the signature, saves the event to the inbox, and replies 200 in a few milliseconds. The worker picks it up, finds no invoice for this cycle, and uses the "create or adopt" insert to create this month's invoice already marked paid. At 00:05, the renewal job runs, tries to create the invoice, hits the unique constraint on subscription and cycle, and adopts the existing paid one instead of creating a second.

Meanwhile, the start of the month is busy, and at 00:00:04 the server took 6 seconds to reply to one delivery, so the gateway sent the same event again at 00:01. That's the duplicate lie. The inbox's unique key ignores it. Half an hour later, the gateway's own systems generate a second, separate event about the same charge. That's the subtler duplicate. The inbox accepts it, but the payments table's unique key on the transaction ID ignores the insert, and the conditional status update changes zero rows.

On the 3rd, the customer asks for a refund, and the "refunded" event arrives. But a "payment updated" event for the same charge, created earlier, was stuck in a retry and arrives an hour after the refund. That's the out-of-order lie. The state machine sees the invoice is already refunded, and refuses to move it back. Finally, one event, a small adjustment on the 10th, is never delivered at all, because a deploy broke the route for 40 minutes and the provider's retries happened to land inside that window. That's the never lie. The nightly reconciliation job lists the day's payments, finds the adjustment missing, and records it through the same idempotent function.

The diagram below shows the path every event takes, whichever lie it's telling.

No single layer is clever. The design works because every layer assumes the others will sometimes fail.

Every event takes the same path, whatever lie it's telling

Gateway sends an event

maybe twice, late, out of order, or never

genuine and recent

Verify signature and timestamp

bad or old is rejected with 400

worker picks it up

Save to inbox, reply 200 fast

a duplicate event ID is a no-op, still 200

allowed move

Lock the record, check the state machine

illegal move is ignored if stale, deferred if early

Idempotent write

unique business key, so the same fact changes 0 rows

Reconciliation job

feeds this same write for events that never came

#017Which Setup Do You Actually Need?

Not every webhook needs an inbox table, a dead-letter queue, and an hourly reconciler. The right amount of machinery depends on what a wrong or missed event costs you. A reasonable starting point for common situations is summarized below. Treat it as a floor, not a ceiling.

The pattern is simple. Anything involving money or access needs every layer, because a mistake there costs customers' trust. Anything that only updates a dashboard or sends a notification can be lighter, because a duplicate or a missed event is an annoyance, not a loss.

Match the machinery to the cost of being wrong, not to how simple the webhook looks.

SituationReasonable minimum
Notifications only (e.g., post to a chat channel on a new pull request)Verify signature; reply fast; tolerate rare duplicates
Syncing data for display (e.g., CRM contact updates)Signature; dedupe by event ID; apply only newer versions; periodic full sync
One-time payments for ordersSignature; inbox; unique key on transaction ID; conditional status updates; daily reconciliation
Recurring billing and subscriptionsAll of the above, plus a state machine with terminal states, "create or adopt" for early payments, routing by stored reference, and reconciliation before each billing run
Anything that grants or removes accessFetch current state from the provider before acting; never act on a stale snapshot

#018Watching Your Webhooks

A webhook system can be broken for days without anyone noticing, because a missing event makes no noise. So the last layer is making the system visible, with a few numbers you can glance at and a few alerts that fire when they look wrong.

Start with the inbox, because it already contains almost everything you need. From it, you can track how many events arrive per hour, by type. A sudden drop to zero during business hours usually means the endpoint is broken, not that customers stopped paying. Track how many deliveries were duplicates. A rising duplicate rate usually means your endpoint is getting slow and the provider is timing out. Track signature failures. A burst usually means a rotated secret that wasn't deployed, or someone probing your URL. Track processing lag: how long events wait between "received" and "processed." And track the size of the dead-letter queue and the unmatched-payments table, both of which should normally be close to zero.

Then watch reconciliation itself. The number of payments the reconciler recovers is the clearest health signal you have. Zero most days means webhooks are doing their job. A sudden jump means webhooks silently failed somewhere, and the reconciler caught it. That's worth an alert every time, even though the data was fixed, because it tells you something upstream is broken.

Finally, make every event easy to trace. Log the provider's event ID and your own record ID together on every line the worker writes. When a customer says "I paid on the 3rd and my account shows nothing," you want to be able to answer in one query: did the event arrive, how many times, what did the worker decide, and why.

A missing webhook makes no noise. Your monitoring has to listen for the silence.

#019A Practical Checklist

If you're building or reviewing a webhook handler for anything that matters, this is the short version of everything above, roughly in order of how much risk each item removes:

You can't stop the gateway from repeating itself. You can make repeating harmless.

  • Verify every signature against the raw body, with a constant-time comparison and a timestamp tolerance. Never set the tolerance to zero.
  • Store first, reply second, process later. An inbox table with a unique key on the provider's event ID, and a 200 reply in milliseconds.
  • Dedupe the business fact, not just the event. A unique constraint on the payment's transaction ID, checked in the same transaction as the update.
  • Write updates that describe the final state. No +=, no toggles; use conditional updates and ledgers of unique entries.
  • Use a state machine with terminal states. Allow only valid transitions, and never move backwards or reopen a finished record.
  • Don't trust arrival order or event timestamps. Use versions where they exist, or fetch current state for anything involving money or access.
  • Never drop a payment. Create or adopt the record, or park the payment in an unmatched table.
  • Route by your own reference. Store your record ID in the provider's metadata, and never look up "the latest" record.
  • Reconcile on a schedule through the same idempotent code path.
  • Test twice, backwards, early, late, and never for every event type.
  • Watch the silence. Alert on drops in volume, rising duplicates, signature failures, dead letters, and reconciliation recoveries.

#020What Idempotency Can't Do

Everything in this article makes your handler safe to receive the same news any number of times. It doesn't make the news correct. If the gateway genuinely charges a customer twice, as two separate transactions with two separate IDs, your handler will correctly record two payments. Idempotency protects you from repeated messages about one fact. It can't tell you that two different facts shouldn't have happened. That needs business rules on the sending side, which is the problem we covered in Your API Can Retry. Your Business Can't.

Deduplication also has limits in time. If you dedupe events using a short-lived cache, as some guides suggest, an event that is redelivered after the cache expires will look new. This is exactly why the business-level unique constraints matter: a payments table with a unique transaction ID has no expiry. Use short-lived caches to save work, never as the thing that keeps you correct.

Reconciliation, too, is only as good as its schedule and its coverage. A daily job means a missed event can stay missed for up to a day. A job that only checks payments won't notice a missed dispute or a missed cancellation. Decide which kinds of events would hurt most if lost, and make sure the reconciler covers those.

And finally, none of this replaces understanding your own business states. The hardest webhook bugs aren't about HTTP at all. They're about a billing model where it's unclear which cycle a payment belongs to, or what "paid" means for a record that was already closed. The techniques here give you safe ways to apply events. Deciding what each event should mean is still your design work.

Idempotency makes the same message harmless. It can't make a wrong message right.

#021The Short Version

A webhook is a letter from a courier who promises only that you'll get it at least once. In practice, it lies to you in five ways: it arrives twice, it arrives out of order, it arrives before you're ready, it arrives long after the moment has passed, or it never arrives at all. A handler that assumes one perfect delivery will eventually double-charge, lose a payment, or rewrite a closed month.

The fix is a front desk with a few firm rules. Check the signature on every letter. Store it before saying thank you, and do the work later. Give every real-world fact a unique identity, and let the database refuse to record it twice. Write changes that describe the final state, and let a state machine decide which changes are allowed. Never drop money, never look up "the latest," and never reopen a finished record. And don't rely on letters alone: check the provider's own records on a schedule.

Do that, and the courier can knock as many times as it likes.

#022Sources

Every technical claim above comes from the provider documentation and references listed below.

  • Receive Stripe events in your webhook endpoint — Stripe documentation: duplicate events and separate Event objects, ordering not guaranteed, timestamps not usable for order, retries for up to three days, quick 2xx replies, asynchronous queues and month-start spikes, HMAC-SHA256 signatures on the raw body, constant-time comparison, 5-minute replay tolerance, IP allowlisting, snapshot vs thin payloads
  • Event destinations — Stripe documentation: thin events carry object IDs, and snapshot data can be stale
  • Best practices for using webhooks — GitHub documentation: reply within 10 seconds, queue for async processing, X-GitHub-Delivery stays the same on redelivery
  • Handling failed webhook deliveries — GitHub documentation: failed deliveries are not automatically redelivered
  • Webhooks FAQs — Razorpay documentation: 5-second response limit, 24-hour retry window with backoff, webhook disabled after continued failure, x-razorpay-event-id, 15-day replay limit
  • Standard Webhooks specification — webhook-id constant across retries, signed content msg_id.timestamp.payload, timestamp for replay protection, multi-day retry schedules, thin vs full payloads
  • Pattern: Idempotent Consumer — Chris Richardson, microservices.io: recording processed message IDs in the same transaction as the business update

Found this useful? Share it

Have a technical response or architectural perspective to share with the engineering desk?

Submit Engineering Feedback