Skip to main content

Razorpay webhook idempotency: key the event, not the payment

8 min read
Idempotency
Webhooks
Payments
PostgreSQL
Prisma
Backend
SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus

Short answer. Dedupe a Razorpay webhook on the x-razorpay-event-id header, not on the pay_… or order_… id in the body. Razorpay sends several different events about one payment (payment.authorized, payment.captured, order.paid), so a key built from the entity id makes them collide and the second one through gets dropped as a duplicate. And take the idempotency claim inside the same transaction as the handler, or a transient failure turns into a permanent one on retry.

That is the whole fix. The rest of this post is how I got it wrong in KhataGO, how the bug hid, and what to check in your own route.

What Razorpay sends for one purchase

KhataGO is a bookkeeping app with a paid tier billed through Razorpay. When someone upgrades, Razorpay creates an order, the customer pays, and Razorpay starts posting webhooks. If your webhook is subscribed to these three, one card payment on one order gets you:

  • payment.authorized, carrying payload.payment.entity with id pay_ABC
  • payment.captured, carrying payload.payment.entity with the same pay_ABC
  • order.paid, carrying both payload.order.entity and payload.payment.entity

Three deliveries, three distinct events, one payment id across all of them. A non-2xx response, or no answer within 5 seconds, gets retried with exponential backoff for 24 hours (Razorpay's best practices), and the same page warns the events may not arrive in order. So any receiver has to be idempotent. Mine was, in the sense that it had a unique column and a try-insert. It just deduplicated the wrong thing.

The key that looked right

The route stored a key in BillingEvent.razorpayEventId, which is @unique in prisma/schema.prisma and backed by BillingEvent_razorpayEventId_key in the migration. Insert, catch the unique violation (Prisma code P2002), answer 200 {"duplicate": true} and skip the handler. The same shape I use for WhatsApp webhooks in the receipt pipeline, where it works.

The key came from this function (the pre-fix lib/razorpay.ts, from git):

// Razorpay doesn't ship a top-level event.id — derive from entity.
export function extractEventId(payload: unknown): string {
  ...
  if (paymentEntity?.id) return `payment:${paymentEntity.id}`;
  if (orderEntity?.id) return `order:${orderEntity.id}`;
  ...
  return "unknown";
}

The function is called extractEventId. It returns an entity id. Every one of the three events above reduces to payment:pay_ABC. Even order.paid does, because the payment entity is read before the order entity.

The three-step failure

  1. payment.authorized arrives first. The insert wins the unique index. dispatch ignores it, correctly, because authorization is not a handled type.
  2. payment.captured arrives. The insert raises P2002. The route reads that as "seen this already", answers 200 with duplicate: true, and never calls the handler.
  3. The customer has been charged ₹299 (the Pro plan amount in RAZORPAY_PLANS) and is still on the FREE plan. There is a BillingEvent row saying the webhook was handled. Nothing logs an error. Nothing returns a 5xx.

The tell was in the same file. dispatch explicitly handles payment.captured and order.paid. Two branches, written on purpose, and the key made it impossible for both to ever run for one payment. When a route handles two event types and its dedup key cannot tell them apart, the code disagrees with itself in writing.

Two smaller things fell out of the same line. The route's header comment called the BillingEvent table an audit trail, but with an entity key the table can hold at most one row per payment, so the trail was lossy by design. And every payload the parser could not read keyed on the literal string "unknown", so the first unrecognised delivery blocked every later one, across all customers, forever.

I found this reading the route during an audit, not from a complaint. I am glad of that, because the failure produces no signal a dashboard would show.

The comment was wrong too

The route's header said it outright: "Razorpay doesn't ship a top-level event.id like Stripe does." That sentence is what made an entity key feel like the best available option. It is also false. Razorpay sends a per-event identifier; it is in the x-razorpay-event-id header, not the body, and Razorpay's webhook docs name it as the way to spot duplicate deliveries. I looked in the JSON, did not find it, and wrote the comment that stopped anyone looking again.

Claim before work, outside the transaction

There was a second defect on the same path. The old route did this:

await prisma.billingEvent.create({ data: { razorpayEventId, ... } });
// ...catch P2002 -> 200 duplicate...
await dispatch({ eventType, payload, userId, planKey });

The claim committed first. Then the handler ran on its own. If dispatch threw (a missing BillingAccount row, a dropped connection, a statement timeout), the route returned 500, Razorpay retried, and the retry hit P2002 on the row the failed attempt had already committed. It was answered 200 duplicate with the handler skipped. One transient error and the upgrade is gone for good, with no dead letter and a row asserting success.

KhataGO's agent loop already held the right invariant and said so in a comment: the tool's write and the step's DONE go in one transaction. The billing path, which is the one that takes money, did the opposite. If you want the general version of this, the idempotency keys post covers where the one atomic step has to live.

The fix

Two changes. First, the key names the event (lib/razorpay.ts, current):

export function webhookEventKey(headers: Headers, payload: unknown) {
  const headerId = headers.get("x-razorpay-event-id")?.trim();
  if (headerId) return { key: `event:${headerId}`, source: "header" };

  const eventType = typeof body.event === "string" && body.event ? body.event : "unknown";
  const entity = extractEntityKey(payload);
  if (entity) return { key: `${eventType}:${entity}`, source: "derived" };

  const createdAt = /* body.created_at as a string, else "unknown" */;
  return { key: `${eventType}:unknown:${createdAt}`, source: "derived" };
}

The header wins when present. The fallback is <event type>:<entity key>, which separates payment.authorized:payment:pay_ABC from payment.captured:payment:pay_ABC. When even the entity is unreadable, the key includes created_at, which is stable across Razorpay's retries of one event but differs between events, so two unparseable payloads no longer cancel each other. The old function was renamed extractEntityKey so the name says what it returns.

Second, the insert and the handler share a transaction (app/api/razorpay/webhook/route.ts):

await prisma.$transaction(async tx => {
  await tx.billingEvent.create({ data: { razorpayEventId, eventType, rawPayload, billingAccountId } });
  await dispatch(tx, { eventType, payload, userId, planKey });
});

A handler failure rolls the claim back, so Razorpay's retry genuinely reprocesses. P2002 is now reachable only after an earlier delivery's handler committed, which is the only time "duplicate" is the truth.

One consequence of the fix: payment.captured and order.paid both reach dispatch for a single payment now. That is fine because the write is an upsert that assigns plan, status and the period dates. An assignment applied twice is the same as once. If your handler increments something, it is not fine, and you need the handler itself to be idempotent per entity on top of the per-event key.

The tests that pin it

The webhook had no tests before this. It has eleven now, in tests/lib/razorpayWebhook.test.ts. The ones that matter:

  • webhookEventKey returns different keys for payment.authorized and payment.captured on the same pay_1, while extractEntityKey returns the same entity for both. That pair is the bug, stated as an assertion.
  • order.paid and payment.captured sharing one payment get different keys.
  • Two unrecognised payloads with different created_at get different keys.
  • The route test posts payment.authorized then payment.captured with real HMAC signatures. The upsert is called once, with plan: "PRO", and the two BillingEvent inserts carry two distinct keys.
  • The rollback test stages the insert inside a fake transaction, makes the upsert reject with "connection reset", and asserts that nothing was committed. A second post then succeeds and commits exactly one row.
  • A genuine redelivery with x-razorpay-event-id: evt_1 and a P2002 from the insert returns 200 with duplicate: true and never calls the upsert.

These run against mocked Prisma, so they prove the route's logic, not the database. The unique index itself is in the migration.

What to check in your own route

  • Print the key your dedup uses for payment.authorized, payment.captured and order.paid on one test payment. If any two match, you have this bug.
  • Read x-razorpay-event-id from the headers. Keep a derived fallback for replays and fixtures, and build it from the event type as well as the entity.
  • Grep for a constant fallback key. "unknown" as a unique value is a global lock with capacity one.
  • Put the claim insert and the handler in one transaction. A claim committed before the work converts every retryable failure into a silent permanent one.
  • If a route handles two event types, write the test that sends both for the same entity and asserts both ran.
  • Give the money path tests before any other path. The repo had 84 test files when I found this, and none of them touched Razorpay.

The project is KhataGO. The finding is number 14 in its FINDINGS file, and the Razorpay section of its CLAUDE.md now says, in red, not to move dispatch back outside the transaction.

SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus