TL;DR
- A payment webhook is an at-least-once notification. Treat it as a prompt to reconcile state, not as a one-time command you can trust without verification.
- Verify the provider signature against the original request bytes before parsing JSON. Use the provider SDK when available and store the signing secret outside application code.
- After verification, persist the event durably and return a success response only after the database commit. Run business effects asynchronously with event-level deduplication and operation-level idempotency.
- Events can arrive more than once, late, or out of order. Use legal state transitions, retrieve canonical provider state when needed, and reconcile gaps.
- Stripe and Razorpay have different signature formats and delivery controls. Keep provider verification adapters separate and test each against official examples.
Webhooks deliver notifications, not a transaction
A webhook receiver is an HTTP endpoint that accepts event notifications from an external system. Payment providers use it to report asynchronous changes such as a payment becoming authorized, a dispute opening, or a subscription invoice succeeding. Delivery is separate from the API request that started a payment. The caller can time out while the provider completes work, and the provider can retry a delivery after a network failure.
That means your endpoint must tolerate duplicate delivery and temporary downtime. A response can be lost after your server commits. If the provider retries, it cannot know whether your database saved the event unless your system records an event identity and returns the same outcome for a duplicate. The endpoint should therefore do a small amount of reliable work, acknowledge promptly, and leave slower application behavior to a durable worker.
The first design mistake is to call the payment gateway from the webhook request and then update several internal tables before responding. Any timeout in that chain can make the provider retry after some of the side effects have already happened. The second mistake is to return success before recording anything, which turns a process crash into a lost payment update. A reliable boundary is simpler: authenticate the message, persist it in an inbox, commit, and then acknowledge.
Stripe recommends inspecting event delivery failures and retrying undelivered events after an outage. Its event management guide documents automatic retries for up to three days and a list-events recovery flow limited to events created within the last 30 days. Treat those provider windows as recovery aids, not as your only event archive. Stripe webhook delivery and undelivered-event recovery
Verify the exact bytes the provider signed
HMAC verification authenticates a message by calculating a keyed digest over the message bytes and comparing it with the signature sent by the provider. JSON parsing and serialization can change whitespace, field ordering, number formatting, or escaping. If you parse the body and reconstruct JSON before verification, you are checking different bytes.
Read the raw body once, verify it using the signing secret for that specific endpoint and environment, and only then decode the JSON. Use official provider libraries when possible because signature formats include details such as timestamp handling and multiple signatures. Do not share a signing secret between test and live endpoints. Rotate secrets using the provider's supported overlap behavior and deploy the replacement before removing the old one.
from fastapi import FastAPI, Header, HTTPException, Request
import stripe
app = FastAPI()
@app.post("/webhooks/stripe")
async def stripe_webhook(
request: Request,
stripe_signature: str | None = Header(default=None),
):
if not stripe_signature:
raise HTTPException(status_code=400, detail="Missing signature")
raw_body = await request.body()
try:
event = stripe.Webhook.construct_event(
payload=raw_body,
sig_header=stripe_signature,
secret=STRIPE_WEBHOOK_SECRET,
)
except (ValueError, stripe.error.SignatureVerificationError):
raise HTTPException(status_code=400, detail="Invalid webhook")
await persist_verified_event("stripe", event, raw_body)
return {"received": True}
This is only the verification boundary. persist_verified_event must insert an inbox record in a transaction and commit before the handler returns success. Keep the secret in a secret manager or protected deployment variable, not in source code or a response body. Stripe documents that signature verification needs the original payload and endpoint secret. Stripe signature verification guidance
Razorpay uses its own signature contract
Razorpay's webhook signature is an HMAC-SHA256 digest over the raw body using the webhook secret. Its validation guide specifically warns against parsing or casting the body before verification. A manual verifier should use a constant-time digest comparison and a strict hex decode, or preferably use a maintained SDK helper with the provider's current behavior.
import hashlib
import hmac
def verify_razorpay(raw_body: bytes, signature: str, secret: bytes) -> bool:
try:
supplied = bytes.fromhex(signature)
except ValueError:
return False
expected = hmac.new(secret, raw_body, hashlib.sha256).digest()
return hmac.compare_digest(expected, supplied)
Do not reuse the Razorpay webhook secret for checkout signature verification. The two signatures protect different request flows. Keep provider-specific code in a small adapter that returns a normalized verified event to the ingestion layer. Razorpay webhook signature validation and event guidance
Persist an inbox before acknowledging delivery
Make the receiver's transaction small and durable. The inbox row should retain the provider name, event identity, event type, received time, verified payload, processing state, attempt count, and a safe error code. A unique constraint on the provider and stable event identifier gives duplicate requests a clear path. Keep raw payload retention limited and encrypted because it can include personal or payment data.
CREATE TABLE webhook_inbox (
id bigserial PRIMARY KEY,
provider text NOT NULL,
provider_event_id text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
payload_sha256 bytea NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
state text NOT NULL DEFAULT 'pending'
CHECK (state IN ('pending', 'processing', 'done', 'dead')),
attempts integer NOT NULL DEFAULT 0,
next_attempt_at timestamptz NOT NULL DEFAULT now(),
last_error_code text,
UNIQUE (provider, provider_event_id)
);
CREATE INDEX webhook_inbox_ready_idx
ON webhook_inbox (next_attempt_at, id)
WHERE state IN ('pending', 'processing');
The exact uniqueness key depends on the provider's event contract. Stripe includes an event ID in the signed JSON object. Razorpay documents an event ID header for duplicate identification, but its signature is calculated over the body. Validate the signed body first, then treat the header as delivery metadata. Record a body digest as an additional diagnostic and replay signal, and make each business operation idempotent as well. A stable event ID prevents ordinary redelivery from repeating work, while idempotent business writes protect against different event messages describing the same logical effect.
In the same transaction, insert the inbox row. If the unique event key already exists, return a success response after confirming the existing record is durable. If the database write fails, return a non-success status so the provider can retry. Avoid acknowledging first and writing later to an in-memory queue. A process restart between those actions loses the event.
INSERT INTO webhook_inbox (
provider, provider_event_id, event_type, payload, payload_sha256
)
VALUES ($1, $2, $3, $4::jsonb, $5)
ON CONFLICT (provider, provider_event_id) DO NOTHING
RETURNING id;
Keep acknowledgement timing aligned with the provider's limits, but do not promise a universal response-time target such as 200 milliseconds without measuring your own infrastructure. The critical requirement is that the request path does no long-running business work and returns only after the durable insert has committed.
Move payment effects into a durable worker
A worker claims pending inbox rows, applies domain transitions, and marks each event complete. Use a lease or row lock so multiple workers cannot own the same row at once. Process the effect and update inbox state in a transaction when both are in the same database. If the worker calls an external API, that call cannot share a database transaction. Supply a stable idempotency key to the provider and store the external operation ID.
WITH next_event AS (
SELECT id
FROM webhook_inbox
WHERE state = 'pending'
AND next_attempt_at <= statement_timestamp()
ORDER BY next_attempt_at, id
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE webhook_inbox AS w
SET state = 'processing', attempts = attempts + 1
FROM next_event
WHERE w.id = next_event.id
RETURNING w.*;
Do not hold this transaction open while making a network call. Claim the work with a lease, commit, make the idempotent provider request, then record its result in a new transaction. If a worker dies after the provider accepts an operation but before the local update, retry with the same idempotency key or reconcile by the stored business reference. This is the same ambiguity addressed by payment API idempotency keys.
Keep separate deduplication boundaries for event delivery and business effect. A provider may send two different events concerning one payment, or send an event that is later superseded by a refund or dispute. A unique inbox row alone does not guarantee that account balances, entitlements, invoices, or ledger postings stay consistent. Add database uniqueness rules around each effect, such as one ledger posting per logical provider operation. See the PostgreSQL double-entry ledger design.
Handle out-of-order events as state reconciliation
Never assume webhook delivery order equals business transition order. Razorpay explicitly warns that payment events can arrive out of order. A delayed authorization event must not overwrite a payment that is already captured or refunded. Store the provider event timestamp and identifier for audit, but use an explicit state machine to decide which transitions are legal.
For high-impact transitions, fetch the canonical payment or subscription object from the provider when the notification does not contain enough current state. Make this call from the worker, not the request handler. Apply a monotonic transition such as pending → authorized → captured only when the source object confirms it. A webhook should wake your reconciliation logic rather than be treated as unquestionable current state.
Design handlers to be safe when an earlier event never arrives. For example, a captured event may be the first event your endpoint sees after an outage. Your handler can retrieve current provider state and reconcile directly instead of waiting forever for an authorization notification. Use a periodic reconciliation job for records that remain pending longer than the provider's expected lifecycle.
Build a recovery and replay process
Keep failed events visible with a bounded retry schedule, exponential backoff, and a terminal dead-letter state. Classify failures. A brief database outage is retryable. An unsupported event type may be intentionally ignored after a durable audit record is stored. A schema mismatch should alert the owning team and remain replayable after the code is fixed.
Provide operators with a controlled replay action that reprocesses an already verified inbox record. Do not ask the operator to submit an old signed request through the public verification path: timestamp checks may correctly reject it as stale, and relaxing that check for replay weakens the endpoint. Internal replay should reference a stored verified event, record who initiated it, and still pass through idempotent business handlers.
Stripe's event dashboard and APIs can help recover missed deliveries, but provider event listing and retry availability have limits. Maintain your own event audit and reconciliation process for the business retention period. Keep replay permissions narrow and redact payload fields in support tooling.
Security and reliability checks to run before launch
- Send a valid signed payload, then alter one byte. The modified request must fail signature verification.
- Parse and reserialize JSON before verification in a negative fixture. Confirm the signature adapter rejects bytes that differ from the signed body.
- Deliver the same verified event repeatedly and confirm it creates one inbox record and one business effect.
- Stop a worker between the provider call and local completion. Confirm retry uses the same idempotency key or reconciles the existing operation.
- Deliver captured, authorized, failed, and refunded notifications out of order. Confirm impossible transitions cannot reverse the payment state.
- Disable database writes. Confirm the endpoint does not return success before an event is durably stored.
- Rotate a webhook secret using the provider-supported procedure and verify the old and new secrets are handled only during the intended overlap.
Track signature failures, accepted events, duplicate deliveries, processing lag, retry counts, dead-letter age, and reconciliation differences. Avoid logging raw signatures, secrets, or full payment payloads. Emit a provider event ID and internal correlation ID in logs so a support engineer can find an event without exposing its contents. Structured logs for correlating production events
Frequently asked questions
Should I return success before the payment event finishes processing?
Return success after the verified event is durably stored, not after all payment business logic has finished. Commit the inbox row first, then let a worker perform slower work. If the durable insert fails, return a retryable failure response so the provider can deliver the event again.
Can I parse JSON before checking a Stripe or Razorpay signature?
No. Verify the original raw request bytes before parsing. Parsing and serializing JSON can change whitespace or representation and therefore change the signed message. Use the provider SDK or its documented HMAC algorithm, endpoint secret, and signature header.
Does a unique webhook event ID guarantee a payment is processed only once?
It prevents the same identified delivery from creating another inbox entry. It does not prevent separate events, worker retries, or external API retries from repeating the same business effect. Add operation-level idempotency keys and database constraints for each effect that must happen once.
How should I deal with events that arrive out of order?
Apply an explicit payment state machine and reject transitions that move state backwards. For important state changes, retrieve the canonical payment object from the provider and reconcile your local state. Do not rely on webhook arrival order or assume every earlier event will eventually arrive.
Make the webhook boundary durable before adding business logic
A secure webhook endpoint preserves the provider's original bytes, verifies them with the correct secret, and writes a durable inbox record before acknowledging delivery. Workers then process verified events with explicit state transitions, idempotent effects, retries, and reconciliation. Provider-specific adapters keep Stripe and Razorpay's distinct signature and retry behavior from leaking into shared payment logic.
If your payment integrations need stronger replay handling, event recovery, or ledger consistency, talk with our engineering team about the webhook and idempotency boundaries before adding more payment flows.
