Backend Development

Webhook Best Practices: Verify, Queue and Deduplicate Events

Webhook best practices for Indian product teams: verify signatures on the raw body, reply fast, queue work, deduplicate by event ID and reconcile what gets missed.

Illustration of events flowing through a queue into a backend, representing webhook best practices for signatures, retries and idempotency

Quick answer

Webhook best practices come down to five rules: verify the signature against the raw request body, return a 2xx response within seconds, push the real work to a queue, deduplicate by the provider's event ID because delivery is at-least-once, and run a reconciliation job for events you never received. Do all five before you trust webhooks with orders or money.

Key takeaways

  • Verify the signature using the raw, unparsed request body and your webhook secret before you read anything in the payload.
  • Reply with a 2xx status quickly and move slow work such as emails, invoices and CRM updates to a background queue.
  • Assume every event can arrive twice or out of order, and store each event ID under a unique constraint so a repeat does nothing.
  • Design handlers around the current state of the object, not the order in which events arrive.
  • Add a scheduled reconciliation job that asks the provider for anything still pending, because webhooks can be delayed, disabled or missed.
On this page
  1. What is a webhook, and why does it need so much care?
  2. How do you verify a webhook signature?
  3. Why should you respond fast and queue the real work?
  4. How do you make webhook handling idempotent?
  5. What if events arrive out of order?
  6. How do you recover events you never received?
  7. How should you test webhooks before launch?
  8. Webhook launch checklist
  9. How Arham Technology approaches webhook handling
  10. What should you do next?

A customer pays by UPI, closes the app, and your order stays on "pending". Or a courier sends "delivered" twice and your system emails the customer two feedback requests and credits a loyalty bonus twice. Both problems come from the same place: a webhook endpoint that was built for the happy path.

Following a few webhook best practices turns that endpoint from a source of support tickets into a dependable part of your backend. This guide covers how to verify events, respond quickly, deduplicate, handle ordering and recover from missed deliveries, with examples from Razorpay and Stripe documentation.

What is a webhook, and why does it need so much care?

A webhook is an HTTP request that a provider sends to a URL you register when an event happens, such as a payment capture, a refund, a shipment update or a form submission. It is the provider calling you, instead of you polling them.

That makes your webhook URL a public door into your system. Anyone on the internet can send a request to it, so it needs the same care as any other API route. Our API security checklist covers the wider controls, and webhooks add three extra problems: you must prove the sender is genuine, you must survive repeated and reordered deliveries, and you must handle the case where nothing arrives at all.

How do you verify a webhook signature?

Verify the signature header using your webhook secret and the exact raw request body, and reject anything that does not match. This is the first line of code in a handler, before you parse the payload or touch the database.

The details differ by provider, but the pattern is the same:

  • Razorpay signs each payload with HMAC using SHA256, with your webhook secret as the key, and sends it in the X-Razorpay-Signature header. The Razorpay webhook validation guide warns that you must pass the raw body and not parse or cast it first.
  • Stripe sends a Stripe-Signature header and expects you to verify it with the raw body, the header and your endpoint secret. Its webhook documentation adds that the signed timestamp lets you reject old payloads, and that the default tolerance of 5 minutes should not be set to zero because that disables the recency check.

The most common bug is a framework that parses JSON before your code sees it. Re-serialising the object changes spacing or key order, and the signature then fails. In Express, capture the raw body for the webhook route only. In Laravel, read the request content directly and hand it to the verifier.

Keep the secret in an environment variable or secrets manager, and store each provider's webhook secret separately from its API key. If you rotate it, Razorpay notes that retried older events still need the old secret for validation, so plan the changeover.

Why should you respond fast and queue the real work?

Return a 2xx status within seconds and move everything slow to a background queue. Providers treat a slow or failed response as a failed delivery and send the event again, so long handlers create duplicate work.

Razorpay documents that if your server accepts an event but does not respond in 5 seconds, the request is marked as a timeout and sent again. A handler that verifies the signature, updates three tables, generates a PDF invoice and sends an email can easily cross that line on a busy day.

A reliable handler does only this:

  1. Read the raw body and verify the signature.
  2. Save the event and its ID in an inbox table, or push it to a queue.
  3. Return 200.
  4. Let a worker process the saved event with retries of its own.

Because the event is stored first, you can replay it after a bug fix. Our guide to scaling your backend with caching, queues and read replicas explains the queue side in more depth.

How do you make webhook handling idempotent?

Store each event's unique ID under a database unique constraint and skip any event you have already handled. Idempotency means processing an event twice has the same result as processing it once.

Razorpay says its delivery is at-least-once and recommends checking the x-razorpay-event-id header, which is unique per event. Stripe likewise advises verifying the signature first, then checking whether you have already processed the event and returning 200 if you have, which stops further retries.

A simple table is enough:

Column Purpose
provider Which system sent it, for example razorpay or stripe
event_id The provider's unique event identifier
event_type For example payment.captured
received_at For debugging and clean-up
status Received, processed or failed

Put a unique constraint on provider plus event_id. When two copies arrive at the same moment, the database lets one in and rejects the other, which a check in application code cannot guarantee. Also make the business action itself safe: marking an already-paid order as paid should change nothing, and a loyalty credit should be tied to the order ID.

What if events arrive out of order?

Write handlers that look at the current state of the object, because providers do not promise delivery order. Razorpay states that you may not always receive webhooks in the order the events occurred, using payment.authorized followed by payment.captured as its example.

Practical rules for ordering:

  • Never assume a sequence. If payment.captured arrives first, do not wait for payment.authorized.
  • Move state forward only. Define the allowed transitions, and ignore an older event that would move an order backwards.
  • Treat final states as final. Razorpay says that once a payout reaches processed or reversed, later webhooks for it should be ignored.
  • When in doubt, fetch. Call the provider's API for the object's current status instead of trusting the payload's position in time.

How do you recover events you never received?

Run a scheduled reconciliation job that asks the provider about anything still unresolved. Webhooks can be delayed, your server can be down during a deployment, and a provider can disable a failing endpoint.

The timelines are limited. Razorpay retries with exponential backoff for 24 hours after the event was created, and if failures continue for that long, the webhook is disabled until you fix the problem and enable it again from the dashboard. Stripe retries live events for up to three days. After that window, only your own reconciliation can catch up.

A simple version is a job that runs every 10 to 15 minutes, finds orders or invoices that have been pending longer than expected, queries the provider's API and applies the same handler logic you use for webhooks. Because the handler is idempotent, running it twice is safe. For payments specifically, see our guide to payment gateway integration in India.

Also alert on the signals that matter: a sudden drop in webhook volume, a rise in signature failures, and a growing backlog in your inbox table.

How should you test webhooks before launch?

Test in the provider's test mode on a staging server with a public HTTPS URL, then deliberately break things. Razorpay's documentation notes that localhost cannot receive events directly, and that many common tunnelling and request-capture domains are blocked as webhook URLs, so a staging host is the dependable route.

Run these cases before going live:

  1. A valid event, which should be processed once.
  2. The same event sent twice, which should change nothing the second time.
  3. A request with a wrong signature, which should be rejected and logged.
  4. Events in the wrong order, which should end in the correct final state.
  5. Your worker crashing halfway, which should retry safely.
  6. Your endpoint returning an error for an hour, followed by recovery through reconciliation.

Webhook launch checklist

Use this table before you enable webhooks in production:

Area Check
Authenticity Signature verified on the raw body, secret stored outside code
Replay protection Timestamp tolerance kept where the provider supports it
Speed Handler returns a 2xx status within seconds, work is queued
Idempotency Unique constraint on provider and event ID, safe business actions
Ordering State transitions defined, final states protected
Recovery Reconciliation job and alerts on volume and failures
Privacy Payloads and personal data kept out of plain logs
Documentation Event types, owners and replay steps written in a runbook

How Arham Technology approaches webhook handling

Our backend development service treats webhooks as part of the API surface, not an afterthought. On a typical project we:

  1. Map the events and failure modes during the domain and threat sketch, including what must never happen twice.
  2. Agree the contract for events we receive and, where you expose webhooks to customers, events we send.
  3. Build the inbox, verification and worker flow in Node.js or Laravel, with automated tests for duplicates, bad signatures and ordering.
  4. Add reconciliation and logging so missing events are detected and every action can be traced by request or event ID.
  5. Hand over a runbook that explains how to replay events and rotate secrets.

If you are building a subscription product that sends events to your own customers, the same principles apply to our SaaS development work.

What should you do next?

Open your existing webhook handler and check three things today: does it verify the raw body, does it return quickly, and does it survive the same event arriving twice? If any answer is no, fix that first. If you are planning a new integration, agree the event flow before the first endpoint is written. Explore our backend development service or contact us with your integration list, and we will suggest a practical plan.

Frequently asked questions

What is a webhook in simple terms?

A webhook is an HTTP request that another system sends to your server when something happens, such as a payment being captured or a shipment being delivered. Instead of you asking repeatedly, the provider pushes the news to a URL you registered. Your endpoint must accept it, check it is genuine and act on it.

How do I verify a webhook is genuine?

Check the signature header using your webhook secret and the exact raw request body. Razorpay sends an HMAC SHA256 signature in the X-Razorpay-Signature header, and Stripe sends a Stripe-Signature header that your server verifies with its official library. If the signature does not match, reject the request and do nothing.

Why do I receive the same webhook twice?

Most providers use at-least-once delivery. If your server accepts an event but does not answer in time, or returns an error, the provider sends it again. Razorpay documents this behaviour and gives each event a unique x-razorpay-event-id header. Store that ID and skip events you have already processed.

How fast should a webhook endpoint respond?

Answer within a few seconds, and ideally much faster. Razorpay treats a response slower than 5 seconds as a timeout and sends the event again. Verify the signature, save the event, return a 2xx status and let a background worker do the slow work.

What happens if my webhook endpoint is down?

The provider retries for a limited time. Razorpay retries with exponential backoff for 24 hours and then disables the webhook, while Stripe retries live events for up to three days. After that you must recover missing events yourself, which is why a reconciliation job that checks the provider's API is worth building.

Should I rely only on webhooks for payments?

No. Use webhooks as the main signal, but also keep a fallback that queries the payment status for orders still pending after a set time. Razorpay itself notes that webhooks are asynchronous and suggests polling its APIs for business-critical, synchronous cases.

NEXT STEP

Want Backend Development done right?

Get a free consultation and a clear plan โ€” scope, timeline and cost โ€” from our Mumbai team.

Get a free consultation โ†’See Backend Development