Subscribe

Idempotent payment webhooks in golang with an event table

Payment providers like Razorpay deliver webhooks at least once. Verify the signature on the raw body, record each event in a Postgres table with a unique (provider, event_id), process it in the same transaction and check the captured amount before settling.

Idempotent payment webhooks in golang with an event table

Payment webhooks arrive more than once. That's not a bug on the provider's side, it is the contract. Razorpay's docs say it plainly: delivery is at least once, a non 2xx response or no answer within 5 seconds counts as a failure, and failed events are retried with exponential backoff for 24 hours. Process the same payment.captured twice and you might send two receipts, extend a plan twice or write two ledger rows.

When we built our payment flow, the webhook handler got a small events table as its idempotency gate. In this blog we will look at that pattern in plain Go and Postgres: verify the signature, record the event, process it once, and check the captured amount before settling anything. I used Razorpay because that's the provider I know; the same shape works for Stripe or anyone else.

The tables

CREATE TABLE IF NOT EXISTS webhook_events (
    id           bigserial PRIMARY KEY,
    provider     text        NOT NULL,
    event_id     text        NOT NULL,
    event_type   text        NOT NULL,
    payload      jsonb       NOT NULL,
    status       text        NOT NULL DEFAULT 'received',
    note         text        NOT NULL DEFAULT '',
    received_at  timestamptz NOT NULL DEFAULT now(),
    processed_at timestamptz,
    CONSTRAINT uq_webhook_events UNIQUE (provider, event_id)
);

CREATE TABLE IF NOT EXISTS orders (
    id                 bigserial PRIMARY KEY,
    gateway_order_id   text   NOT NULL UNIQUE,
    amount_paise       bigint NOT NULL,
    status             text   NOT NULL DEFAULT 'created',
    gateway_payment_id text   NOT NULL DEFAULT ''
);

-- No unique constraint on purpose: the tests use it to count side effects.
CREATE TABLE IF NOT EXISTS ledger (
    id           bigserial PRIMARY KEY,
    order_id     bigint NOT NULL REFERENCES orders(id),
    payment_id   text   NOT NULL,
    amount_paise bigint NOT NULL
);

The unique (provider, event_id) is the whole trick. provider is there so a second payment provider later doesn't need a new table. Keeping the raw payload as jsonb costs a bit of disk and saves a lot of guessing when someone asks "what exactly did they send us".

Verify the signature on the raw body

Razorpay signs each webhook with HMAC-SHA256 of the raw request body, keyed with the webhook secret you set in the dashboard, and sends the hex digest in X-Razorpay-Signature. The important word is raw. If you decode the JSON and encode it again, key order and spacing change and the signature won't match.

func VerifySignature(body []byte, sigHex, secret string) bool {
    got, err := hex.DecodeString(sigHex)
    if err != nil || secret == "" {
        return false
    }
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write(body)
    return hmac.Equal(got, mac.Sum(nil))
}

hmac.Equal compares in constant time. A plain == on strings would work functionally, but don't. And an empty secret returns false, so a missing config value fails closed instead of accepting everything.

The event id

Razorpay sends X-Razorpay-Event-Id, unique per event. If it's ever missing (an old test tool, a proxy that drops headers), I build one from the event type and the entity id, like payment.captured-pay_X1. It is stable across retries, which is all that matters.

eventID := r.Header.Get("X-Razorpay-Event-Id")
if eventID == "" {
    eventID = ev.Event + "-" + entityID(ev)
}

Record and process in one transaction

This is the part I spent the most time on. The handler does everything inside one database transaction:

  1. INSERT ... ON CONFLICT DO NOTHING the event.
  2. SELECT status ... FOR UPDATE that row.
  3. If the status is not received, it was handled already: commit and return 200.
  4. Otherwise dispatch, set the status, commit.
func (h *Handler) process(ctx context.Context, eventID string, ev event, body []byte) (dup bool, err error) {
    tx, err := h.DB.Begin(ctx)
    if err != nil {
        return false, err
    }
    defer tx.Rollback(ctx) // no-op after Commit

    // A second delivery of the same event blocks here until the first
    // transaction commits or rolls back.
    _, err = tx.Exec(ctx, `
        INSERT INTO webhook_events (provider, event_id, event_type, payload)
        VALUES ($1, $2, $3, $4)
        ON CONFLICT (provider, event_id) DO NOTHING`,
        provider, eventID, ev.Event, body)
    if err != nil {
        return false, err
    }

    var status string
    err = tx.QueryRow(ctx, `
        SELECT status FROM webhook_events
        WHERE provider = $1 AND event_id = $2 FOR UPDATE`,
        provider, eventID).Scan(&status)
    if err != nil {
        return false, err
    }
    if status != "received" {
        return true, tx.Commit(ctx)
    }

    newStatus, note, err := h.dispatch(ctx, tx, ev)
    if err != nil {
        return false, err
    }

    if _, err := tx.Exec(ctx, `
        UPDATE webhook_events SET status = $3, note = $4, processed_at = now()
        WHERE provider = $1 AND event_id = $2`,
        provider, eventID, newStatus, note); err != nil {
        return false, err
    }
    return false, tx.Commit(ctx)
}

Why not insert first and then process separately? Two reasons.

If processing fails, the transaction rolls back and the event row goes with it. The handler returns 500, Razorpay retries, and the retry is processed as new. If the insert had been committed on its own, the retry would find the row already there, and you have to remember to check its status as well.

The second reason I found by accident. I tried the "insert outside the transaction" version once, using h.DB.Exec for the insert while a transaction was already open, and ran my test that fires 10 copies of the same event at once. It hung. The goroutine dump showed all 10 stuck in pgxpool.(*Pool).Acquire. Each request held one connection for its transaction and waited for a second one for the insert, and pgxpool's default size is the larger of 4 and the number of CPUs, which on my Mac is 10. Classic pool deadlock. One transaction, one connection, and the problem is gone.

A duplicate that arrives while the first is still running waits on the unique index until the first commits, then sees processed and acks. If the first rolled back, the waiting one inserts and does the work. No double processing either way.

Dispatch and the amount check

func (h *Handler) paymentCaptured(ctx context.Context, tx pgx.Tx, ev event) (string, string, error) {
    p := ev.Payload.Payment.Entity

    var orderID, want int64
    var orderStatus string
    err := tx.QueryRow(ctx, `
        SELECT id, amount_paise, status FROM orders
        WHERE gateway_order_id = $1 FOR UPDATE`, p.OrderID).Scan(&orderID, &want, &orderStatus)
    if errors.Is(err, pgx.ErrNoRows) {
        return "ignored", "no matching order", nil
    }
    if err != nil {
        return "", "", err
    }

    // Never settle an order for a different amount than we asked for.
    if p.Amount != want {
        msg := fmt.Sprintf("order %d: captured %d paise, expected %d (payment %s)", orderID, p.Amount, want, p.ID)
        if h.Alert != nil {
            h.Alert(msg)
        }
        return "needs_review", msg, nil
    }

    if orderStatus == "paid" { // the checkout callback got there first
        return "processed", "already paid", nil
    }

    if _, err := tx.Exec(ctx, `
        UPDATE orders SET status = 'paid', gateway_payment_id = $2 WHERE id = $1`,
        orderID, p.ID); err != nil {
        return "", "", err
    }
    if _, err := tx.Exec(ctx, `
        INSERT INTO ledger (order_id, payment_id, amount_paise) VALUES ($1, $2, $3)`,
        orderID, p.ID, p.Amount); err != nil {
        return "", "", err
    }
    return "processed", "", nil
}

Amounts from Razorpay are integers in paise so compare int64 to int64. No floats anywhere near money.

The amount check is cheap and I would never skip it. The order row holds what we asked the customer to pay. If the capture says something else, something is wrong somewhere, and settling the order anyway turns a weird event into a real loss.

What to return on a mismatch took me while to decide. My first instinct was a 500 so the event stays "unprocessed". But a mismatch won't fix itself on retry. Razorpay would retry for 24 hours, and if deliveries keep failing for that long it disables the webhook, which stops every other event too. So I mark the event needs_review, alert a human and return 200. The raw payload is in the table for whoever picks it up.

The order lookup is also FOR UPDATE, and the "already paid" branch is there because the browser callback after checkout often marks the order paid before the webhook lands. Both paths have to be safe to run in any order. Razorpay also says events aren't guaranteed to arrive in order, so don't assume payment.authorized comes before payment.captured.

Keep it fast

You get 5 seconds. Everything above is a handful of indexed queries, which is fine. Sending emails, generating PDFs or calling other APIs is not; record the work and let a background worker do it (the Postgres job queue with SKIP LOCKED post is one way). And make sure deploys don't cut handlers in half; the graceful shutdown post covers the drain delay.

Testing it

The tests run against a throwaway Postgres 18 container and sign payloads with a test secret:

docker run -d --name pg-test -e POSTGRES_PASSWORD=pw -p 127.0.0.1::5432 postgres:18-alpine
export TEST_DATABASE_URL="postgres://postgres:pw@127.0.0.1:$(docker port pg-test 5432 | cut -d: -f2)/postgres?sslmode=disable"
go test ./webhook/ -v -p 1

The cases are a bad signature (400, nothing stored), 10 concurrent copies of one event (all 200, exactly one ledger row), a forced failure before commit followed by a retry (500 then 200, one ledger row), no event id header twice (one row with id payment.captured-pay_X1), and a captured amount of 100 paise against an order of 49900 (200, order not paid, one alert). All five passed with Go 1.27.3 and pgx v5.13.0.

When the tests pass, clean up the container with docker rm -f pg-test.