Razorpay's webhook docs say it plainly: your endpoint might receive the same event more than once, and that's expected behaviour. For a one-off payment, a duplicate usually means a second "thanks for your order" email. For subscriptions it's worse: a duplicate subscription.charged can extend someone's access by two months, create two GST invoices for one payment, or credit a referral bonus twice. Razorpay subscription webhook idempotency is the fix, and it's less code than most teams expect.
Below is the pattern we use. The examples are Node.js and Postgres, but nothing depends on that: the same design works behind a Laravel API, a Firebase Cloud Function, or whatever serves your Flutter, React Native or web app.
What Razorpay guarantees, and what it doesn't
From Razorpay's webhook documentation:
- Every webhook carries an
x-razorpay-event-idheader, unique per event. Duplicates of the same event share it. - Every webhook carries
X-Razorpay-Signature, an HMAC-SHA256 of the raw request body using your webhook secret. - Your endpoint must return a 2xx within 5 seconds. Otherwise the delivery counts as failed and is retried with exponential back-off for 24 hours. If failures continue for 24 hours, the webhook is disabled.
What the docs don't promise is ordering. Subscription events have a logical sequence (authenticated, activated, charged, later pending, halted or cancelled) but a retry of an older event can arrive after a newer one. Your handler has to cope with both duplicates and reordering.
Razorpay subscription webhook idempotency in three layers
Layer 1: verify, record, acknowledge
The HTTP handler should do as little as possible: verify the signature against the raw body, insert the event into a table keyed by event ID, and return 200. No business logic. That keeps you well inside the 5-second window and makes duplicates harmless at the door.
app.post('/webhooks/razorpay', express.raw({ type: 'application/json' }), async (req, res) => {
const sig = req.get('X-Razorpay-Signature') || '';
const expected = crypto
.createHmac('sha256', process.env.RAZORPAY_WEBHOOK_SECRET)
.update(req.body) // raw Buffer, not re-serialised JSON
.digest('hex');
if (sig.length !== expected.length ||
!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) {
return res.sendStatus(400);
}
await db.query(
`INSERT INTO webhook_events (event_id, body, status)
VALUES ($1, $2, 'received')
ON CONFLICT (event_id) DO NOTHING`,
[req.get('x-razorpay-event-id'), req.body.toString('utf8')]
);
res.sendStatus(200);
});
Two details that bite people. Verify against the raw bytes: if your framework parses JSON first and you re-stringify it, the signature won't match. And use a constant-time comparison for the signature.
The primary key on event_id is the whole deduplication mechanism. A second delivery hits ON CONFLICT DO NOTHING, still gets a 200, and Razorpay stops retrying.
Layer 2: process from the table, not the request
A worker picks up rows with status received, processes them, and marks them processed in the same database transaction as the business change. If the worker crashes halfway, the transaction rolls back and the row is still received, so it gets picked up again.
Use SELECT ... FOR UPDATE SKIP LOCKED if you run more than one worker, so two workers never grab the same row. If you already have a queue like RabbitMQ or Cloud Tasks, use it to wake the worker, but keep the table as the record of what's been done. A message lost between the insert and the enqueue is then just a delay, because a periodic sweep finds any row still sitting in received.
Layer 3: make the business effect idempotent too
Event-ID deduplication handles exact duplicates. It doesn't handle two different events that describe the same thing. A successful renewal can produce both payment.captured and subscription.charged, each with its own event ID, both carrying the same payment ID. If both are wired to "extend access and raise an invoice", you'll do it twice.
So key the business effect on the business identifier:
- A
subscription_chargestable with a unique constraint on the Razorpay payment ID. Extending access and issuing the invoice happen only when that insert succeeds. - Pick one event as the trigger for each effect. For subscriptions,
subscription.chargedis the natural one for renewals; letpayment.capturedupdate payment records only. - Compute access from data, not increments. "Access until the current period's end date from the charge record" survives replays. "Add 30 days" does not.
Handling out-of-order subscription events
Each webhook payload includes a created_at timestamp. Store the timestamp of the last event you applied to each subscription, and when a status-changing event arrives that's older than that, record it but don't move the status backwards.
For anything ambiguous, fetch the subscription from Razorpay's API and set your status from the response. The webhook tells you something changed; the API tells you what's true now. That one extra call removes a whole category of race conditions, and it's cheap compared with a support ticket from a customer who paid and got locked out.
Don't forget the webhook that never came
Idempotency handles too many deliveries. You also need to handle zero. If your endpoint is down long enough, Razorpay disables the webhook, and nothing tells your app that renewals stopped arriving.
- Alert when no Razorpay webhooks have arrived in a period where you'd normally see some.
- Run a nightly reconciliation that lists recent subscription payments from the API and compares them with your
subscription_chargestable. Missing rows get inserted through the same idempotent path as webhooks, so running it twice is safe. - Check the webhook's status in the Razorpay dashboard after any outage.
We built post-payment reconciliation and GST invoicing for a production ed-tech payment portal, and these three layers are what kept double-processing out of it. If your subscription backend has started producing duplicate invoices or mystery access extensions, orithLabs can review it or rebuild the webhook path as part of our web development work. The first call is free.