Reliable payment webhooks: retries, duplicates and ordering
A reliable payment webhook handler assumes any event can arrive twice, late or out of order, and never depends on a single delivery. It verifies the signature, stores the event_id under a unique constraint, answers 200 within seconds, then processes the event in the background by reading the checkout's current status. A periodic poll catches anything missed, and an alert fires when deliveries fail. CoinStack retries a failed delivery 8 times over about a day.
What goes wrong with payment webhooks?
Every failure below happens in normal operation as well as during outages. The CoinStack webhooks guide warns about the first two directly: "The same event can arrive more than once" and "Events can arrive out of order, and a retried event can arrive after a newer one."
| Failure | Typical cause | What it does to a naive handler | Defense |
|---|---|---|---|
| Duplicate delivery | Your 200 was lost, or you answered after 10 seconds | Ships the order twice, sends 2 emails | Store event_id; claim the order with a conditional update |
| Out-of-order delivery | A retried older event lands after a newer one | Moves a paid order back to "confirming" | Act on the checkout's current status from the API |
| Missed event | Endpoint down longer than the retry schedule | Order stays unpaid although the USDC arrived | Periodic reconciliation |
| Slow handler | Fulfilment runs inside the request | Counted as a failure and sent again | Answer first, process later |
| Redirect | URL changed from http to https, or a trailing slash rule | Every delivery fails | Register the final URL; watch delivery codes |
Stripe documents the same behavior for its own events: "Webhook endpoints might occasionally receive the same event more than once" and it "doesn't guarantee the delivery of events in the order that they're generated." Its advice for duplicates is the one used below: log the event IDs you have processed and skip the ones already logged.
How does CoinStack retry a failed delivery?
A delivery succeeds when your server answers with any 2xx status within 10 seconds. Anything else counts as a failure, including a timeout and a redirect. After a failure CoinStack tries again after 1 minute, 5 minutes, 30 minutes, 2 hours, 5 hours, 8 hours and 8 hours. After the eighth attempt the event is not sent again unless you resend it.
| Attempt | Delay after the previous one | About how long after the event |
|---|---|---|
| 1 | None | Immediately |
| 2 | 1 minute | 1 minute |
| 3 | 5 minutes | 6 minutes |
| 4 | 30 minutes | 36 minutes |
| 5 | 2 hours | 2 hours 36 minutes |
| 6 | 5 hours | 7 hours 36 minutes |
| 7 | 8 hours | 15 hours 36 minutes |
| 8 | 8 hours | 23 hours 36 minutes |
The table shows why retries alone are not enough. Suppose your server goes down for 3 hours and a customer pays 2 minutes into the outage. Attempts 1 to 5 all fail, and attempt 6 arrives about 7 hours 36 minutes after the payment. The USDC was in your wallet the whole time, but a customer who bought a server waited most of a working day for it. A deploy that breaks the route for a weekend runs past the eighth attempt, and those events wait in Recent events until you resend them.
The fix is to stop treating delivery as the only path. Resend the backlog when you recover, and run a poll that does not depend on webhooks at all. Both are below.
Step 1: verify, record the event ID, answer
The request handler does as little as possible: check the signature, write one row, answer. How to verify payment webhooks explains the signature check and the verifySignature function used here. The examples use Node.js with Express and PostgreSQL through the pg package, which reads its connection settings from the standard PG* environment variables.
CREATE TABLE orders (
id bigserial PRIMARY KEY,
checkout_id text UNIQUE,
status text NOT NULL DEFAULT 'awaiting_payment',
created_at timestamptz NOT NULL DEFAULT now(),
paid_at timestamptz
);
CREATE TABLE webhook_events (
event_id uuid PRIMARY KEY,
kind text NOT NULL,
checkout_id text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
attempts int NOT NULL DEFAULT 0,
processed_at timestamptz
);// webhook.js
import express from "express";
import pg from "pg";
import { verifySignature } from "./lib/coinstack-signature.js";
const db = new pg.Pool();
const app = express();
app.post("/webhooks/coinstack", express.raw({ type: "application/json" }), async (req, res) => {
const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
if (!verifySignature(req.get("CoinStack-Signature"), body, process.env.COINSTACK_WEBHOOK_SECRET)) {
return res.status(400).send("Invalid signature");
}
const event = JSON.parse(body);
const checkoutId = event.data.checkout?.checkout_id ?? event.data.payment?.checkout_id;
await db.query(
`INSERT INTO webhook_events (event_id, kind, checkout_id)
VALUES ($1, $2, $3)
ON CONFLICT (event_id) DO NOTHING`,
[event.event_id, event.kind, checkoutId],
);
res.sendStatus(200);
});The primary key on event_id is the duplicate filter. event_id stays the same when CoinStack retries an event and when you resend it, so a second copy hits the constraint and PostgreSQL's ON CONFLICT DO NOTHING turns it into a no-op. The handler still answers 200, because a duplicate is not an error and you do not want it retried.
Two details matter. The row is written before the 200, so if the database is down the insert throws, Express answers 500, and CoinStack retries later: nothing is lost. And the handler stores only the identifiers. Both checkout.* events and payment.* events carry a checkout_id, and the next step reads everything else fresh.
If you would rather not keep a table as a queue, push the event into the job system you already run (BullMQ, Sidekiq, Celery or Laravel queues) after the insert. The PHP and Laravel tutorial does exactly that.
Step 2: process from the checkout's current status
The worker never trusts the order in which events arrived, and never trusts the status inside the event. The docs describe data as "the checkout or payment as it was when the event happened", which may no longer be true. Instead, the worker gets the checkout and acts on what the API says now.
// coinstack.js
export async function coinstack(method, path) {
const response = await fetch(`https://coinstack.net/api/v1${path}`, {
method,
headers: { Authorization: `Bearer ${process.env.COINSTACK_API_KEY}` },
});
const body = await response.json();
if (!body.success) throw new Error(`${response.status} ${body.response}`);
return body.response;
}// sync.js
import { coinstack } from "./coinstack.js";
const PAID = ["completed", "resolved"];
export async function syncCheckout(db, checkoutId) {
const known = await db.query("SELECT 1 FROM orders WHERE checkout_id = $1", [checkoutId]);
if (known.rowCount === 0) return; // not ours, such as the dashboard test event
const { checkout } = await coinstack("GET", `/checkouts/${encodeURIComponent(checkoutId)}`);
if (!PAID.includes(checkout.status)) return;
const { rows } = await db.query(
`UPDATE orders SET status = 'paid', paid_at = now()
WHERE checkout_id = $1 AND status = 'awaiting_payment'
RETURNING id`,
[checkoutId],
);
if (rows.length === 1) {
await fulfil(rows[0].id, checkout); // runs once per order
}
}The conditional UPDATE is the second guard against duplicates. Two workers handling 2 different events for the same checkout can both reach this line, but only one of them changes a row from awaiting_payment to paid, and only that one fulfils. If fulfil sends email or calls another system, keep it safe to repeat or write those jobs to a table in the same transaction.
Here is how this handles disorder. Say the customer's payment produces checkout.confirming and then checkout.completed, and the first one fails and is retried after the second. The worker processes completed: the API says completed, the order is paid. Then the late confirming arrives: the API still says completed, the order is already paid, nothing happens. A handler that copied the event's status into the order would have set it back to "confirming."
// worker.js
import { syncCheckout } from "./sync.js";
export async function processNextEvent(db) {
const client = await db.connect();
let row;
try {
await client.query("BEGIN");
({ rows: [row] } = await client.query(
`SELECT event_id, checkout_id FROM webhook_events
WHERE processed_at IS NULL AND attempts < 10
ORDER BY attempts, received_at
LIMIT 1
FOR UPDATE SKIP LOCKED`,
));
if (row) {
await syncCheckout(client, row.checkout_id);
await client.query("UPDATE webhook_events SET processed_at = now() WHERE event_id = $1", [row.event_id]);
}
await client.query("COMMIT");
return Boolean(row);
} catch (error) {
await client.query("ROLLBACK");
if (row) await db.query("UPDATE webhook_events SET attempts = attempts + 1 WHERE event_id = $1", [row.event_id]);
throw error;
} finally {
client.release();
}
}Call processNextEvent in a loop from one or more worker processes. FOR UPDATE SKIP LOCKED lets several workers run without picking the same row. If the API call fails, the transaction rolls back, the event's attempts goes up, and it is tried again later; after 10 failures it stops and waits for the alert in step 4.
Decide in advance what a paid event means for an order you already cancelled. A payment that arrives after a checkout's expires_at can still complete it, with the late flag set, and CoinStack then sends checkout.completed. Either fulfil it or refund the customer from your own wallet. Overpaid and late crypto payments walks through the choice.
Step 3: reconcile with a periodic poll
The poll is the path that works when webhooks do not. Every 5 to 15 minutes, look up every order still waiting for payment and run the same syncCheckout on it.
// reconcile.js
import { syncCheckout } from "./sync.js";
export async function reconcile(db) {
const { rows } = await db.query(
`SELECT checkout_id FROM orders
WHERE status = 'awaiting_payment'
AND checkout_id IS NOT NULL
AND created_at > now() - interval '3 days'`,
);
for (const { checkout_id } of rows) {
try {
await syncCheckout(db, checkout_id);
} catch (error) {
console.error(`Reconcile ${checkout_id}: ${error.message}`);
}
}
}The 3-day window is longer than the default 24-hour checkout life on purpose, so a late payment on an expired checkout still gets picked up. If you set expires_at yourself, make the window comfortably longer than your expiry. One failing lookup is logged and skipped rather than stopping the run.
CoinStack's own WooCommerce plugin works the same way. Its setup guide says it looks up the checkout's status when CoinStack sends a payment update, when a customer returns from the checkout, and every few minutes for recent unpaid orders. WooCommerce order statuses for crypto shows what that looks like from the store side. For finance-level matching of orders, checkouts and payments, see how to reconcile crypto payments.
Step 4: alert on failed deliveries
Retries and polling hide problems, which is good for customers and bad for you if a broken endpoint goes unnoticed for a week. List events returns each event with its delivery record per webhook: delivered, attempts, the HTTP code your server returned last, and next_at, which is null once the event is delivered or CoinStack has stopped trying. It needs an API key with read and write access.
// monitor.js
import { coinstack } from "./coinstack.js";
export async function findFailedDeliveries(hours = 26) {
const since = Date.now() - hours * 3600 * 1000;
const failing = [];
let cursor = null;
do {
const query = cursor ? `?limit=100&cursor=${encodeURIComponent(cursor)}` : "?limit=100";
const page = await coinstack("GET", `/events${query}`);
for (const { event, deliveries } of page.events) {
if (Date.parse(event.created_at) < since) return failing;
for (const delivery of deliveries) {
if (!delivery.delivered && delivery.attempts >= 3) {
failing.push({ event, delivery, abandoned: delivery.next_at === null });
}
}
}
cursor = page.cursor;
} while (cursor);
return failing;
}Run it every 10 minutes. Three failed attempts means about 6 minutes of failure, which is enough to rule out a single blip. Page someone when the list is not empty, and include delivery.code: 0 means CoinStack got no answer at all, 404 usually means a changed route, and 400 on every event usually means a wrong signing secret.
When the endpoint is fixed, resend what failed. Recent events in the dashboard has a resend button, and Resend an event does it through the API. Entries marked abandoned will never arrive without this. The worker's own failures need the same treatment: alert on any webhook_events row with attempts at 10, or unprocessed for more than an hour.
How do you test this before launch?
Each failure mode can be triggered on purpose. Resending a delivered event from the dashboard gives you a genuine duplicate with the same event_id; your handler should answer 200 and change nothing. Stopping your app, paying a small checkout and starting the app again shows a missed event being picked up by the reconciliation run, or by the retry after 1 minute. Pointing the webhook at a URL that returns 404 shows the alert firing. The smallest checkout is worth 1 US dollar, so the whole set costs a few dollars; how to test a crypto checkout has the full plan.
Frequently asked questions
How long does CoinStack keep retrying a failed webhook?
About a day. A failed delivery is retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 5 hours, 8 hours and 8 hours, for 8 attempts in total. After the last one the event is not sent again on its own. You can resend it at any time from Recent events in the dashboard or through the Resend an event endpoint, and the event_id stays the same.
Can I fulfil straight from the event data without calling the API?
You can, and for a single checkout.completed subscription it usually works. The risk is ordering: the event body is a snapshot from when the event happened, and a retried older event can arrive after a newer one. Reading the checkout with one API call before acting removes that risk, and also means a forged or replayed body cannot change an order.
Should the handler return an error when processing fails?
If you store the event and process it later, answer 200 as soon as the row is written, because the event is safe with you. If you process inside the request, returning a 5xx on failure is fine: CoinStack retries, and your duplicate checks make the retry harmless. Stay under the 10-second limit either way, or a successful run is counted as a failure and sent again.
Do I need both webhooks and polling?
Yes, for anything that delivers value automatically. A webhook is sent as soon as the checkout changes, so it is the fast path. The poll covers the times your endpoint was down, misconfigured or slow. Limited to orders still waiting for payment and run every 5 to 15 minutes, it costs 4 to 12 API calls per open order per hour.
Which webhook events should a payment handler subscribe to?
Most integrations need only checkout.completed, plus checkout.expired if you release stock or cancel orders when a checkout closes unpaid. Add checkout.resolved if you mark underpaid checkouts as resolved, since that status also means paid. Payment events are useful for showing progress, but decide whether an order is paid from the checkout, because a completed payment can still leave its checkout partial.