# Idempotent Webhook Handlers in Node.js with PostgreSQL

The first time I saw a customer charged for one order and credited twice, the code looked perfectly fine. The webhook handler verified the signature, updated the order, and returned `200`. The problem was not in the handler. The problem was that the payment provider sent the same event twice, and my handler did the work twice.

Almost every webhook provider (Stripe, Razorpay, GitHub, Shopify and many more) promises **at-least-once delivery**. That means duplicates are not a bug in their system. They are part of the contract. If your handler is not idempotent, your system is wrong, even when every line of code looks right.

In this post I will show the pattern I now use for every webhook endpoint: one table, one unique constraint, and one transaction.

## Why duplicates happen

A provider sends an event and waits for a `2xx` response. If it does not get one in time, it retries. Duplicates appear in very normal situations:

- Your handler took 12 seconds, and the provider's timeout is 10 seconds. You finished the work, but the provider never saw your `200`.
- A deploy restarted the pod after the database write but before the response.
- A load balancer dropped the connection.
- The provider itself had an incident and replayed events.

You cannot prevent these cases. You can only make a second delivery of the same event do nothing.

## The core idea: record the event ID first

Every serious provider includes a unique event ID in the payload (for example `evt_...` in Stripe or the `x-github-delivery` header in GitHub). The pattern is:

1. Start a transaction.
2. Try to insert the event ID into a `processed_webhook_events` table that has a unique constraint.
3. If the insert did nothing, this is a duplicate. Commit and return `200`.
4. If the insert worked, do the business logic **in the same transaction**, then commit.

Because the insert and the business logic commit together, you never get the state "event marked as done, but the work is missing", or the opposite.

Here is the table:

```sql
CREATE TABLE processed_webhook_events (
  provider     text        NOT NULL,
  event_id     text        NOT NULL,
  event_type   text        NOT NULL,
  received_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (provider, event_id)
);
```

I include `provider` in the key because event IDs are only unique inside one provider. Two providers can, in theory, send the same ID string.

## The handler in TypeScript

This example uses Express and the `pg` library. Signature verification is out of scope here, so I show it as one function call, but never skip it in real code.

```typescript
import express from "express";
import { Pool } from "pg";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const app = express();

app.post(
  "/webhooks/payments",
  express.raw({ type: "application/json" }),
  async (req, res) => {
    const event = verifyAndParse(req); // throws if the signature is invalid

    const client = await pool.connect();
    try {
      await client.query("BEGIN");

      const inserted = await client.query(
        `INSERT INTO processed_webhook_events (provider, event_id, event_type)
         VALUES ($1, $2, $3)
         ON CONFLICT (provider, event_id) DO NOTHING
         RETURNING event_id`,
        ["payments", event.id, event.type],
      );

      if (inserted.rowCount === 0) {
        await client.query("COMMIT");
        return res.status(200).json({ status: "duplicate" });
      }

      await applyEvent(client, event); // business logic, same transaction

      await client.query("COMMIT");
      return res.status(200).json({ status: "processed" });
    } catch (err) {
      await client.query("ROLLBACK");
      console.error("webhook failed", { eventId: event.id, err });
      return res.status(500).json({ status: "error" });
    } finally {
      client.release();
    }
  },
);
```

Two details matter a lot:

- `ON CONFLICT ... DO NOTHING RETURNING event_id` gives you a race-free check. If two copies of the event arrive at the same moment, PostgreSQL lets only one insert win. The other one waits for the first transaction, then sees the conflict and returns zero rows.
- If `applyEvent` throws, the `ROLLBACK` also removes the event row. The provider retries later, and the retry gets a clean second chance.

## Make the business logic safe too

The event table protects you from duplicate deliveries of the **same event**. It does not protect you from two **different events** that describe the same change, such as `payment.captured` and `order.paid` for one payment. So the business logic should also be written as an idempotent state change, not as an increment.

```typescript
import type { PoolClient } from "pg";

type PaymentEvent = {
  id: string;
  type: string;
  data: { orderId: string; paymentId: string; amountPaise: number };
};

async function applyEvent(client: PoolClient, event: PaymentEvent) {
  if (event.type !== "payment.captured") return;

  // Set a final state; never "add" to a balance here.
  await client.query(
    `UPDATE orders
        SET status = 'paid',
            payment_id = $2,
            paid_amount_paise = $3,
            paid_at = COALESCE(paid_at, now())
      WHERE id = $1
        AND status IN ('pending', 'paid')`,
    [event.data.orderId, event.data.paymentId, event.data.amountPaise],
  );
}
```

Setting `status = 'paid'` twice gives the same result as setting it once. Writing `balance = balance + amount` twice does not. When you design the update, ask: "If this statement runs two times, is the result the same?" If the answer is no, add a guard in the `WHERE` clause or use a unique constraint on the side-effect table (for example a unique `payment_id` on a `ledger_entries` table).

## Respond fast, process later (when you need to)

If the business logic is slow, such as calling three external APIs or sending emails, you risk the provider timeout again. In that case, split the work:

1. In the HTTP handler, insert the event into the table with the raw payload and a `status = 'pending'` column, then return `200` at once.
2. A worker picks up pending rows with `SELECT ... FOR UPDATE SKIP LOCKED`, processes them, and marks them `done`.

`SKIP LOCKED` lets many workers pull from the same table without two of them taking the same row. The unique constraint still protects you from duplicate deliveries, because the second insert of the same event ID does nothing.

For most handlers that only update a few rows, the simple synchronous version above is enough. Start there.

## Common mistakes

**Checking with** `SELECT` **before** `INSERT`**.** "Select the event ID; if it does not exist, insert it" has a race condition. Two requests can both see "not found" and both continue. Let the unique constraint decide.

**Marking the event as processed in a separate transaction.** If you commit the event row first and the business logic fails after that, every retry is now treated as a duplicate. The work never happens. Keep both in one transaction.

**Returning** `500` **for duplicates.** A duplicate is a success. If you return an error, the provider keeps retrying the same event, and some providers disable your endpoint after many failures.

**Using the request body hash as the key.** Providers sometimes resend an event with a different delivery timestamp or header, so the body can change while the event is the same. Use the provider's event ID.

**Never cleaning the table.** The table grows forever. Most providers only retry for a few days, so a nightly job can delete rows older than, for example, 30 days:

```sql
DELETE FROM processed_webhook_events
WHERE received_at < now() - interval '30 days';
```

## How I test it

The best test is the one that matches reality: send the same event twice, at the same time.

```typescript
import { test, expect } from "vitest";
import request from "supertest";
import { app } from "./app";
import { signedPaymentEvent, getOrder } from "./test-helpers";

test("the same event delivered twice in parallel is applied once", async () => {
  const { body, headers } = signedPaymentEvent({ orderId: "ord_1" });

  const [a, b] = await Promise.all([
    request(app).post("/webhooks/payments").set(headers).send(body),
    request(app).post("/webhooks/payments").set(headers).send(body),
  ]);

  expect([a.status, b.status]).toEqual([200, 200]);
  expect([a.body.status, b.body.status].sort()).toEqual(["duplicate", "processed"]);
  expect((await getOrder("ord_1")).status).toBe("paid");
});
```

Run this test against a real PostgreSQL instance (for example in Docker), not a mock. The whole point is to test the database's concurrency behavior.

## Key takeaways

- Webhooks are delivered at least once. Duplicates are normal, not rare.
- Store the provider's event ID in a table with a unique constraint.
- Insert the event row and run the business logic in **one** transaction.
- Use `ON CONFLICT DO NOTHING RETURNING` instead of select-then-insert.
- Write state changes that give the same result when they run twice.
- Return `200` for duplicates, and clean old event rows on a schedule.

What is the worst duplicate-webhook bug you have seen in production? I would love to hear how you found it.
