Why Did My Webhook Handler Run Twice for One Event? At-Least-Once Delivery, Explained

One payment came in. Two orders went out. The provider swears it sent one event, your logs show two, and now finance wants to know why a customer was charged once but shipped twice.

This is one of the most common production incidents I see with webhook integrations, and almost every team’s first instinct is wrong. They open a ticket with the provider claiming a double-send bug. The provider closes it as working-as-intended, because it is. The webhook did not fire twice by accident. It fired twice because that is what the delivery contract promises, and your handler was not built to expect it.

At-least-once is a promise, not a bug

Almost every webhook sender in the wild — Stripe, GitHub, Shopify, your payment gateway, your own internal event bus — delivers with at-least-once semantics. That phrase is doing a lot of work. It means the sender guarantees your endpoint will receive each event one or more times. It explicitly does not guarantee exactly once. Exactly-once delivery across a network is, for practical purposes, unachievable; every serious system chooses at-least-once and pushes the deduplication problem onto the receiver.

The mechanism is a retry loop. The sender POSTs your event, then waits for a 2xx response inside a timeout window. It retries — often with exponential backoff over hours or days — whenever it does not get a clean, timely 2xx. The trap is that a retry does not mean your handler failed. It means the sender did not hear that it succeeded. Those are very different things, and the gap between them is where duplicate processing lives.

Concretely, your handler runs twice for one logical event when:

  • You did the work but timed out replying. You wrote the order, then a slow downstream call pushed your response past the sender’s timeout. It retries; you write the order again.
  • You returned a 5xx after committing. The database commit succeeded, then an unrelated line threw before you sent 200. The sender sees the error and redelivers.
  • The 200 was lost on the wire. You succeeded and replied, but the ACK never reached the sender. From its side, that is indistinguishable from a failure.
  • The provider simply sends twice. Some do, occasionally, even on success. The documentation for most tells you plainly to expect it.

None of these is a fault in the sender. Retrying is exactly what a reliable sender is supposed to do — the same behaviour that makes webhooks survive your endpoint being down for a deploy is the behaviour that duplicates events. If you want the background on the sender side of that contract, I have written about retries, backoff, dead-letter queues and idempotent receivers separately. This post is about the receiver.

The real root cause: a non-idempotent handler

Given that duplicates are guaranteed, the defect is not that the event arrived twice. The defect is that your handler produces a different outcome the second time. A handler is idempotent when processing the same event twice leaves the system in the same state as processing it once. “Insert an order row” is not idempotent. “Insert an order row for this event, unless one already exists” is.

The fix has two independent parts, and you need both. First, deduplicate on a stable identifier the sender controls. Every reputable provider stamps each event with an ID — Stripe’s evt_..., a delivery UUID in a header — that is constant across retries of the same event. Do not dedupe on a hash of the payload or your own received-at timestamp; those can differ between deliveries. Second, make the side effects themselves idempotent, so that even if two deliveries race past your dedupe check simultaneously, the database refuses to create the second order.

Fix it in Postgres with a unique constraint

The most durable dedupe lives in the same transaction as the work, enforced by the database. A unique constraint on the provider’s event ID turns a race into a caught error rather than a second order. This is the version I reach for first, because it survives process crashes, redeploys and a Redis outage — the ledger and the side effect commit atomically.

-- PostgreSQL 17: the dedupe ledger
CREATE TABLE processed_events (
  event_id   text PRIMARY KEY,
  handled_at timestamptz NOT NULL DEFAULT now()
);

-- Handle the event and its side effect in ONE transaction.
BEGIN;

-- Claim the event. If it was already handled, zero rows return
-- and we skip the side effect entirely.
INSERT INTO processed_events (event_id)
VALUES ($1)
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id;

-- Only if the INSERT above returned a row do we create the order.
INSERT INTO orders (payment_id, amount_cents, currency)
VALUES ($2, $3, $4);

COMMIT;

In application code you branch on whether the first insert returned a row. If rowCount is zero, this event has been handled before: log it, return 200, do nothing else. Because both inserts share one transaction, a crash between them rolls back the claim too, so a retry can legitimately reprocess. Two concurrent deliveries cannot both win the primary key.

The Redis variant, and when to use it

When the side effect is not a database write — you are enqueuing a job, calling a third-party API, sending an email — a Redis dedupe key is faster and cheaper than a table. Use SET with the NX and EX options in a single command. The old standalone SETNX cannot set a TTL atomically, so a crash between SETNX and EXPIRE leaves a key that never dies; the combined form closes that window. NX means “only if absent”, and the reply tells you whether you won the claim.

// Express 5 + Node 22, using the node-redis client (redis@4/5).
// IMPORTANT: verify the signature on the RAW body first, before JSON parsing,
// with express.raw({ type: "application/json" }) mounted on this route.
app.post("/webhooks/payments", async (req, res) => {
  const eventId = req.get("x-event-id"); // e.g. Stripe's evt_...
  if (!eventId) return res.status(400).send("missing event id");

  // Atomic claim: set the key only if absent, expire after 24h.
  // Reply is "OK" if we won the claim, null if it already existed.
  const claim = await redis.set(`webhook:${eventId}`, "1", {
    NX: true,
    EX: 60 * 60 * 24,
  });

  if (claim === null) {
    // Already processed (or in flight). Acknowledge and stop.
    return res.status(200).send("duplicate ignored");
  }

  try {
    await handlePayment(req.body); // the non-idempotent side effect
    return res.status(200).send("ok");
  } catch (err) {
    // We failed AFTER claiming. Release the claim so the retry can
    // legitimately reprocess, then signal failure to the sender.
    await redis.del(`webhook:${eventId}`);
    return res.status(500).send("processing failed");
  }
});

The trade-off is honest: the Redis claim and the side effect are not one atomic unit, so if the process dies after handlePayment succeeds but before you release or the reply lands, the TTL will eventually expire the key and a much later retry could reprocess. For anything financial, prefer the Postgres constraint, where the ledger and the work commit together. Redis is the right tool when the side effect is idempotent at the far end anyway, or when a rare double-send is tolerable.

The rule to build every handler on

Two operational habits pay for themselves. Verify the signature on the raw request body before you trust the event ID, or an attacker replays a valid ID to trip your dedupe or forge one — the same mutual-authentication thinking that applies to service-to-service calls. And keep the dedupe ledger, because a persisted record of every event ID you have processed is exactly what you need to reconstruct and replay what happened when someone disputes it months later.

Treat every webhook endpoint as if it will be called twice, because it will be. The question is never whether a duplicate arrives. It is only whether your handler notices.

Build and rescue work

Hands-on delivery of this kind is handled by Sixteen Pillars Studio.

Free interactive tool

Website compliance checklist

What your site has to do, based on what it actually does

Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.

Most technology problems are not technology problems. They are control problems.

The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.