{"id":10556,"date":"2026-11-25T04:24:11","date_gmt":"2026-11-25T04:24:11","guid":{"rendered":"https:\/\/cybersecurityinfocus.com\/?p=10556"},"modified":"2026-11-25T04:24:11","modified_gmt":"2026-11-25T04:24:11","slug":"design-a-reliable-payment-webhook-receiver-idempotency-retries-and-transactional-outbox","status":"publish","type":"post","link":"https:\/\/cybersecurityinfocus.com\/?p=10556","title":{"rendered":"Design a Reliable Payment Webhook Receiver: Idempotency, Retries and Transactional Outbox"},"content":{"rendered":"<div class=\"wp-block-group is-layout-constrained wp-block-group-is-layout-constrained\">\n<h2 class=\"wp-block-heading\">From payment to fulfillment: six steps<\/h2>\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-7387b849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> 1. Pay<\/h3>\n<p class=\"wp-block-paragraph\">Customer pays; provider creates an event.<\/p>\n<\/div>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> 2. Verify<\/h3>\n<p class=\"wp-block-paragraph\">Check signature on raw request bytes and timestamp.<\/p>\n<\/div>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> 3. Commit<\/h3>\n<p class=\"wp-block-paragraph\">Store inbox and outbox in one transaction.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-7387b849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> 4. Acknowledge<\/h3>\n<p class=\"wp-block-paragraph\">Return HTTP 2xx only after durable commit.<\/p>\n<\/div>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> 5. Process<\/h3>\n<p class=\"wp-block-paragraph\">Relay publishes; worker handles retries.<\/p>\n<\/div>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> 6. Fulfill<\/h3>\n<p class=\"wp-block-paragraph\">Use a unique business key to prevent duplicate effects.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p class=\"wp-block-paragraph\"><strong>Lost response?<\/strong> Provider retries \u2192 same event ID \u2192 no second inbox row. External effects still need downstream idempotency or reconciliation.<\/p>\n<\/div>\n<p class=\"wp-block-paragraph\"><strong>System Design Daily \u00b7 Intermediate to senior \u00b7 Editorial interview practice<\/strong><\/p>\n<h2 class=\"wp-block-heading\">The \u20b91,499 payment that arrived twice<\/h2>\n<p class=\"wp-block-paragraph\">In this fictional bookstore scenario, customer Neha pays \u20b91,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\u2019s internal design.<\/p>\n<p class=\"wp-block-paragraph\">A documented real-world analogue is Stripe: its <a href=\"https:\/\/docs.stripe.com\/webhooks\" target=\"_blank\" rel=\"noopener\">webhook documentation<\/a> describes signed events, asynchronous handling, retries and possible duplicate or unordered delivery. The architecture below is our own proposed receiver, not Stripe\u2019s internal architecture.<\/p>\n<h2 class=\"wp-block-heading\">Requirements and scale assumptions<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<p class=\"wp-block-paragraph\">Assume 10 million events\/day: about 116 events\/s average and 1,160\/s at 10\u00d7 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.<\/p>\n<h2 class=\"wp-block-heading\">Meet the participants<\/h2>\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-7387b849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> Receiver<\/h3>\n<p class=\"wp-block-paragraph\">Verifies authenticity and commits intake.<\/p>\n<\/div>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> Database<\/h3>\n<p class=\"wp-block-paragraph\">Enforces uniqueness and atomic writes.<\/p>\n<\/div>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> Relay<\/h3>\n<p class=\"wp-block-paragraph\">Publishes committed outbox records.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-7387b849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> Queue<\/h3>\n<p class=\"wp-block-paragraph\">Buffers work and isolates bursts.<\/p>\n<\/div>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> Worker<\/h3>\n<p class=\"wp-block-paragraph\">Applies business state transitions.<\/p>\n<\/div>\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<div class=\"wp-block-group has-text-color has-background is-layout-constrained wp-container-core-group-is-layout-b62443b2 wp-block-group-is-layout-constrained\">\n<h3 class=\"wp-block-heading\"> Reconciler<\/h3>\n<p class=\"wp-block-paragraph\">Checks provider truth and repairs gaps.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<h2 class=\"wp-block-heading\">High-level architecture<\/h2>\n<p>Provider &#8211;signed POST&#8211;&gt; Load balancer &#8211;&gt; Receiver<br \/>\nProvider &lt;&#8211;2xx after commit&#8212;&#8212;&#8212;&#8212;&#8211; Receiver<br \/>\n                                            |<br \/>\n                                            v<br \/>\n                                  PostgreSQL transaction<br \/>\n                                  [Inbox + Outbox]<br \/>\n                                            |<br \/>\n                                     Outbox relay<br \/>\n                                            v<br \/>\n                                      Durable queue<br \/>\n                                            |<br \/>\n                                         Worker &#8211;&gt; Order DB + effect outbox<br \/>\n                                            |                  |<br \/>\n                                            v                  v<br \/>\n                                      Retry \/ DLQ      Fulfillment API<br \/>\n                                                       (idempotency key)<br \/>\nReconciler &lt;&#8211;&gt; Provider API; reconciles order state<\/p>\n<p class=\"wp-block-paragraph\">The inbox and intake outbox share a transaction. The worker\u2019s 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.<\/p>\n<h2 class=\"wp-block-heading\">API contracts and data model<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<p>CREATE TABLE inbox (<br \/>\n provider text NOT NULL,<br \/>\n account_id text NOT NULL,<br \/>\n event_id text NOT NULL,<br \/>\n payload jsonb NOT NULL,<br \/>\n received_at timestamptz DEFAULT now(),<br \/>\n PRIMARY KEY(provider, account_id, event_id)<br \/>\n);<br \/>\nCREATE TABLE outbox (<br \/>\n id uuid PRIMARY KEY,<br \/>\n event_key text NOT NULL UNIQUE,<br \/>\n payload jsonb NOT NULL,<br \/>\n published_at timestamptz<br \/>\n);<br \/>\nCREATE INDEX pending_outbox ON outbox(id)<br \/>\n WHERE published_at IS NULL;<\/p>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Implementation: atomic intake<\/h2>\n<p>def receive(raw, headers, endpoint):<br \/>\n    # Pseudocode: provider SDK validates raw bytes and time.<br \/>\n    event = verify_with_provider_sdk(raw, headers, endpoint)<br \/>\n    key = (endpoint.provider, event.verified_account, event.id)<br \/>\n    with db.transaction() as tx:<br \/>\n        inserted = tx.insert_inbox_if_absent(key, event.payload)<br \/>\n        if inserted:<br \/>\n            tx.insert_outbox(key, event.payload)<br \/>\n    return 200  # only after successful commit<\/p>\n<p class=\"wp-block-paragraph\">Implement insert-if-absent using INSERT \u2026 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 <a href=\"https:\/\/docs.aws.amazon.com\/prescriptive-guidance\/latest\/cloud-design-patterns\/transactional-outbox.html\" target=\"_blank\" rel=\"noopener\">AWS transactional outbox guidance<\/a>.<\/p>\n<h2 class=\"wp-block-heading\">Failure story: what if the response disappears?<\/h2>\n<p>Provider -&gt; Receiver: E-17<br \/>\nReceiver -&gt; DB: commit inbox + outbox<br \/>\nReceiver -X Provider: response lost<br \/>\nProvider -&gt; Receiver: E-17 again<br \/>\nReceiver -&gt; DB: unique key conflict (already durable)<br \/>\nReceiver -&gt; Provider: 200<br \/>\nRelay -&gt; Queue: E-17 (possibly more than once)<br \/>\nWorker -&gt; DB: apply guarded transition + effect command<br \/>\nWorker -&gt; Queue: acknowledge after commit<\/p>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Ordering, consistency and scaling<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Reliability, security and cost<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Alternatives and trade-offs<\/h2>\n<p class=\"wp-block-paragraph\"><strong>Direct durable queue:<\/strong> fewer database writes on intake, but dedupe and audit move downstream. <strong>Inbox plus outbox:<\/strong> strong local acceptance invariant and auditability, with relay complexity. <strong>CDC relay:<\/strong> avoids polling but adds connector offsets and schema evolution concerns. <strong>Synchronous processing:<\/strong> simplest at low volume, but slow dependencies cause retries and couple availability. Choose based on durability, latency and operational requirements.<\/p>\n<h2 class=\"wp-block-heading\">Testing and interview follow-ups<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n<p class=\"wp-block-paragraph\"><strong>Does HTTP 200 mean the order shipped?<\/strong> No. It means durable intake in this contract. Processing status is separate.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Does FIFO guarantee exactly-once fulfillment?<\/strong> No. Broker guarantees do not cover external side effects.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Can Redis alone deduplicate?<\/strong> Not safely if keys can expire or be lost before the replay horizon. Use durable uniqueness for critical effects.<\/p>\n<p class=\"wp-block-paragraph\"><strong>How do I replay a DLQ event?<\/strong> Fix the underlying cause, authorize and audit replay, preserve original business keys, then verify resulting state.<\/p>\n<h2 class=\"wp-block-heading\">Knowledge check<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Key takeaway and further reading<\/h2>\n<p class=\"wp-block-paragraph\">Design for repeat delivery, durable acceptance and safe business transitions. Treat reconciliation as a normal reliability mechanism, not an emergency patch.<\/p>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/docs.stripe.com\/webhooks\" target=\"_blank\" rel=\"noopener\">Stripe webhook documentation<\/a> \u00b7 <a href=\"https:\/\/docs.aws.amazon.com\/prescriptive-guidance\/latest\/cloud-design-patterns\/transactional-outbox.html\" target=\"_blank\" rel=\"noopener\">AWS transactional outbox<\/a> \u00b7 <a href=\"https:\/\/programesecure.com\/design-distributed-job-scheduler\/\">Distributed job scheduler<\/a> \u00b7 <a href=\"https:\/\/programesecure.com\/distributed-api-rate-limiter-system-design\/\">Distributed API rate limiter<\/a><\/p>","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-10556","post","type-post","status-publish","format-standard","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10556"}],"collection":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10556"}],"version-history":[{"count":0,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10556\/revisions"}],"wp:attachment":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10556"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10556"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10556"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}