Design a Reliable Payment Webhook Receiver: Idempotency, Retries and Transactional Outbox

Tags:

From payment to fulfillment: six steps

1. Pay

Customer pays; provider creates an event.

2. Verify

Check signature on raw request bytes and timestamp.

3. Commit

Store inbox and outbox in one transaction.

4. Acknowledge

Return HTTP 2xx only after durable commit.

5. Process

Relay publishes; worker handles retries.

6. Fulfill

Use a unique business key to prevent duplicate effects.

Lost response? Provider retries → same event ID → no second inbox row. External effects still need downstream idempotency or reconciliation.

System Design Daily · Intermediate to senior · Editorial interview practice

The ₹1,499 payment that arrived twice

In this fictional bookstore scenario, customer Neha pays ₹1,499 for order O-42. Ananya receives event E-17, commits it, but the HTTP response is lost. The provider sends E-17 again. Ravi sees two HTTP requests but one durable inbox entry. A worker eventually marks the order paid and creates one fulfillment command. This is a realistic teaching scenario, not a claim about a particular company’s internal design.

A documented real-world analogue is Stripe: its webhook documentation describes signed events, asynchronous handling, retries and possible duplicate or unordered delivery. The architecture below is our own proposed receiver, not Stripe’s internal architecture.

Requirements and scale assumptions

Accept authenticated provider events, acknowledge durable intake, deduplicate, process asynchronously, expose delivery status to authorized operators and support audited replay. Assume 99.95% monthly intake availability, p95 acknowledgement under 250 ms, and p95 processing under 30 seconds in normal operation. These are proposed targets, not measured results. An outage may violate processing latency without losing accepted events.

Assume 10 million events/day: about 116 events/s average and 1,160/s at 10× peak. At 2 KB/event, raw payloads consume 20 GB/day or 600 GB for 30 days, before indexes, replicas and outbox records. A 30-minute peak outage creates about 2.09 million queued events. At 2,000/s processing capacity with 1,160/s ongoing arrivals, drain time is roughly 42 minutes. Provision for retries and skew separately.

Meet the participants

Receiver

Verifies authenticity and commits intake.

Database

Enforces uniqueness and atomic writes.

Relay

Publishes committed outbox records.

Queue

Buffers work and isolates bursts.

Worker

Applies business state transitions.

Reconciler

Checks provider truth and repairs gaps.

High-level architecture

Provider –signed POST–> Load balancer –> Receiver
Provider <–2xx after commit————– Receiver
|
v
PostgreSQL transaction
[Inbox + Outbox]
|
Outbox relay
v
Durable queue
|
Worker –> Order DB + effect outbox
| |
v v
Retry / DLQ Fulfillment API
(idempotency key)
Reconciler <–> Provider API; reconciles order state

The inbox and intake outbox share a transaction. The worker’s order update, processed-event record and effect outbox share a separate local transaction. The external fulfillment API is outside that transaction. Queue acknowledgement follows the worker commit. No cross-system exactly-once claim is made.

API contracts and data model

POST /webhooks/{provider} accepts raw signed JSON, with provider-specific signature headers. Return 2xx for durably accepted or already accepted events, 400 for invalid payload/signature, 503 for unavailable durable storage. An authenticated GET /internal/events/{id} exposes state; POST /internal/events/{id}/replay requires scoped operator access and an audit reason. Replays reuse business keys.

CREATE TABLE inbox (
provider text NOT NULL,
account_id text NOT NULL,
event_id text NOT NULL,
payload jsonb NOT NULL,
received_at timestamptz DEFAULT now(),
PRIMARY KEY(provider, account_id, event_id)
);
CREATE TABLE outbox (
id uuid PRIMARY KEY,
event_key text NOT NULL UNIQUE,
payload jsonb NOT NULL,
published_at timestamptz
);
CREATE INDEX pending_outbox ON outbox(id)
WHERE published_at IS NULL;

The account scope comes from verified provider context and endpoint configuration, not an untrusted header. Store processing attempts and next retry time separately; index by due time. Orders are keyed by tenant and order ID. A unique fulfillment command key such as tenant/order/ship prevents different event IDs from creating the same shipment. Keep dedupe keys at least through the supported replay horizon, and retain business uniqueness as long as needed.

Implementation: atomic intake

def receive(raw, headers, endpoint):
# Pseudocode: provider SDK validates raw bytes and time.
event = verify_with_provider_sdk(raw, headers, endpoint)
key = (endpoint.provider, event.verified_account, event.id)
with db.transaction() as tx:
inserted = tx.insert_inbox_if_absent(key, event.payload)
if inserted:
tx.insert_outbox(key, event.payload)
return 200 # only after successful commit

Implement insert-if-absent using INSERT … ON CONFLICT DO NOTHING RETURNING. The relay claims pending rows with leases, publishes to a durable broker and marks published only after broker confirmation. A crash between publish and marking can cause duplicates; consumers must tolerate them. This follows the design rationale in AWS transactional outbox guidance.

Failure story: what if the response disappears?

Provider -> Receiver: E-17
Receiver -> DB: commit inbox + outbox
Receiver -X Provider: response lost
Provider -> Receiver: E-17 again
Receiver -> DB: unique key conflict (already durable)
Receiver -> Provider: 200
Relay -> Queue: E-17 (possibly more than once)
Worker -> DB: apply guarded transition + effect command
Worker -> Queue: acknowledge after commit

If a worker crashes after committing but before acknowledging, redelivery finds the processed marker and does not repeat the transaction. If the external shipping call succeeds but its response is lost, retry with the same downstream idempotency key or query the shipping system before deciding what to do. A dead-letter queue (DLQ) is a quarantine, not proof of resolution.

Ordering, consistency and scaling

Do not apply events in arrival order. For a payment-success event, verify the payment maps to the order, amount and currency; use guarded state transitions and retrieve current provider state when snapshots conflict. Refunds and disputes are separate legitimate transitions. Serialize per aggregate where needed; partition by tenant/order key, not event ID, when preserving aggregate order. A queue cannot restore provider ordering that never existed.

Start with a multi-AZ relational database and managed queue. Scale stateless receivers horizontally, batch relay work and tune worker concurrency to database capacity. Cache non-authoritative configuration only; never use an evictable cache as the sole dedupe ledger. For very large tenants use isolated queues or quotas. For multi-region intake, route each tenant to a home region or use a globally consistent uniqueness store; asynchronous replicas alone cannot prevent simultaneous duplicate acceptance.

Reliability, security and cost

Use bounded exponential backoff with jitter, classify permanent errors, cap attempts and alert on oldest pending age. Monitor acknowledgement latency, signature failures, duplicate ratio, outbox lag, queue age, DLQ count and reconciliation mismatches. Encrypt payloads, rotate signing secrets, cap request sizes, redact personal data and restrict replay permissions. Store only required fields and expire raw payloads according to policy. Cost drivers include database writes, replicated storage, queue operations and outbound provider API calls; batch where safe and measure rather than invent prices.

Alternatives and trade-offs

Direct durable queue: fewer database writes on intake, but dedupe and audit move downstream. Inbox plus outbox: strong local acceptance invariant and auditability, with relay complexity. CDC relay: avoids polling but adds connector offsets and schema evolution concerns. Synchronous processing: simplest at low volume, but slow dependencies cause retries and couple availability. Choose based on durability, latency and operational requirements.

Testing and interview follow-ups

Test concurrent identical events, different IDs for one payment, invalid signatures, stale snapshots, database failure before commit, lost acknowledgement, relay crash after publish, worker crash after commit and external timeout after success. Assert business effects, not just HTTP status. Senior follow-up: how do you reconcile a regional failover with conflicting order updates? Discuss home-region fencing, recovery objectives and the cost of global coordination.

Frequently asked questions

Does HTTP 200 mean the order shipped? No. It means durable intake in this contract. Processing status is separate.

Does FIFO guarantee exactly-once fulfillment? No. Broker guarantees do not cover external side effects.

Can Redis alone deduplicate? Not safely if keys can expire or be lost before the replay horizon. Use durable uniqueness for critical effects.

How do I replay a DLQ event? Fix the underlying cause, authorize and audit replay, preserve original business keys, then verify resulting state.

Knowledge check

1. Where should the 2xx response occur? After durable intake commit. 2. What happens if relay publication succeeds but marking fails? Possible duplicate delivery. 3. Why use a business key as well as event ID? Different events can represent the same intended effect.

Key takeaway and further reading

Design for repeat delivery, durable acceptance and safe business transitions. Treat reconciliation as a normal reliability mechanism, not an emergency patch.

Stripe webhook documentation · AWS transactional outbox · Distributed job scheduler · Distributed API rate limiter

Categories

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *