Skip to content

Payments and Integrations Practical engineering guide

Payment Gateway Webhooks: Idempotency, Retries and Recovery

Build payment webhook processing with provider-specific verification, durable inboxes, unique financial transitions, outbox recovery and reconciliation tests.

Explore the flow Worked examples · Failure handling · Primary sources
Explore this guide

A payment webhook integration needs authenticated receipt, durable event storage, repeat-safe financial transitions and a reconciliation path for missing or ambiguous evidence. Returning success to a callback is not the same as posting a wallet effect, publishing an internal event or receiving bank settlement.

The state model and pseudocode are illustrative; it does not claim a runnable provider integration or approval for gambling payments. The payment architecture guide covers eligibility and the complete deposit/withdrawal lifecycle.

Specify the provider contract first

For each event family, record verification inputs, key management, event/operation identities, retry behavior, acknowledgement format and authoritative status-query mechanism. Do not assume every provider signs raw JSON or supplies one globally unique event ID.

Adyen's HMAC documentation distinguishes webhook formats and verification procedures. Its event-handling guide addresses processing, duplicates and ordering. These are specific documented examples, not a universal protocol.

Identify fields that may be absent in a notification. If the evidence is insufficient to establish amount, currency or the financial transition, obtain the supported authoritative details before posting. A signed message is authentic under its contract; it is not automatically a complete accounting instruction.

Technical flow

Payment Gateway Webhooks: Idempotency, Retries and RecoveryIllustrative logical boundaries; provider contracts and operating requirements determine the implementation.
  1. 01Verify source

    Apply the actual provider signature and payload verification rules

  2. 02Persist inbox

    Durably retain a scoped event before acknowledging receipt

  3. 03Commit transition

    Deduplicate financial transitions and commit wallet effects atomically

  4. 04Publish + reconcile

    Recover publication through an outbox and reconcile authoritative evidence

The illustrated path separates transport receipt, business processing and reconciliation. A durable inbox lets processing resume after an acknowledged delivery even if a worker later fails.

BoundaryEvidence
HTTP receiptBounded request, endpoint configuration and verification outcome
Event inboxSource scope, durable identity and unprocessed/processed state
Payment transitionPermitted state change and authoritative references
Ledger operationUnique intended effect, currency and balanced postings
Outbox/consumerCommitted event identity and repeat-safe application
ReconciliationExternal/internal discrepancy and accountable resolution

Keep transport retry, event retry and command retry as separate mechanisms. Replaying a stored notification is not permission to repeat a payout request.

Authenticate before trusting business fields

Bound the request body and preserve the representation required by the provider's verifier. Use the documented SDK or carefully reviewed verification implementation for that event type. Key rotation may require a controlled overlap; follow the actual contract and retain nonsecret key/version evidence.

Validate merchant/account, environment, payment reference and expected financial scope. Do not let an untrusted request choose another merchant's verification key or route itself into a different tenant merely by changing a header.

Log safe diagnostic references and verification outcomes, not secrets or unnecessary sensitive payloads. Restrict access and retention for raw evidence. A signature failure should not create a wallet entry just to keep callback response metrics green.

Use two deduplication boundaries

First deduplicate durable receipt according to the provider event/delivery identity. Then protect the financial operation. Different event identities may report the same capture, credit or reversal, while one payment can legitimately contain several distinct operations.

Bind the operation key to player/account, amount, currency, operation kind and supporting reference. If the same key returns with a conflicting payload, investigate/reject it rather than returning another operation's stored success.

For a hypothetical 25-unit deposit notification delivered three times, one valid financial effect is 25, not 75. If a second event reports the same effect, event-level uniqueness alone is insufficient. If a later distinct refund is valid, it must not be suppressed merely because it relates to the same original payment.

The wallet ledger guide explains the transaction boundary and reservation invariants that make this distinction enforceable.

Acknowledge durable receipt, then process safely

The precise acknowledgement timing/format must fit the provider contract. A useful application pattern is to acknowledge only after verified evidence is durably accepted, then process through a retryable worker. If storage fails, do not pretend receipt is durable.

receive(request):
    verified = provider_adapter.verify_bounded_request(request)
    require_approved_source_scope(verified)
    transaction:
        persist_receipt_if_new(verified.identity, verified.evidence)
    return_provider_acknowledgement()

process(receipt):
    authoritative = obtain_required_payment_evidence(receipt)
    transaction:
        lock_payment_in_verified_account_scope()
        transition = evaluate_documented_transition(authoritative)
        if transition.unresolved:
            retain_current_financial_state_and_open_case()
        else:
            apply_unique_financial_operation(transition)
            append_required_ledger_postings()
            mark_receipt_processed()
            insert_outbox_event_for_committed_transition()

This is provider-neutral pseudocode. Persist the state of deferred cases so workers can make progress without spinning forever. The complete implementation needs database constraints, safe retries and provider-specific verification/query logic.

Treat out-of-order events as a state problem

Do not set payment status to whichever notification arrived last. A delayed initiation event must not erase a confirmed transition, but a valid later reversal may require a new effect. The event's meaning and authoritative state determine the response.

Maintain explicit transition rules, operation references and an ambiguity path. When evidence conflicts, retain the current safe financial commitment and open reconciliation rather than guessing which timestamp is decisive.

Distinguish confirmed failure of one attempt from failure of the whole payment journey. A player may have several attempts with different references. A callback for attempt A must not update attempt B because both belong to the same user or checkout session.

Provider-generated timestamps can help trace the incident, but cross-system ordering may still be incomplete. Use the documented operation lifecycle and queries rather than inventing a universal total order.

Review every crash boundary

Crash pointRequired behavior in the proposed design
Before inbox persistenceNo false durable acknowledgement; provider recovery remains possible
After inbox commit, before workerStored receipt is discoverable and retryable
During ledger transitionAtomic outcome or rollback; no half-posted effect
After ledger commit, before external event publicationOutbox preserves the notification obligation
After publication, before delivery markerConsumer handles a duplicate safely
After provider payout, before responseOriginal outcome remains unknown until reconciled

AWS's transactional outbox guidance describes the local-write/publish boundary and duplicate handling. An outbox does not make all downstream side effects exactly once or include a provider's financial system in your database transaction.

Keep a stable event identity and a documented ordering scope. A message reaching a queue is not proof that the wallet transition or finance report has been applied.

Recover lost events and uncertain commands separately

Use supported status queries or reports to find aged pending payments and compare them with inbox/ledger records. Keep rate-limit and permission requirements in that recovery plan. Missing notifications should be observable as unresolved state, not disappear into a quiet webhook endpoint.

For payouts, retain relevant funds while the submission outcome is unknown. Submitting through another provider can create a second payout even if the first request timed out. Resolve the original using its supported references before replacement.

Reconciliation should identify an operation, evidence owner, discrepancy type and next action. “Retry the callback” is not enough when the original source event is missing or the provider's authoritative state differs from your transition model.

The provider table and merchant-eligibility qualifications remain in the payment lifecycle guide; this tutorial does not recommend Stripe or any other general payment API as approved for a gambling business.

Test correctness before increasing callback throughput

Build deterministic fixtures for valid, invalid, duplicate, conflicting and reordered events. Run them with concurrent workers and injected process/database failures. Assert final operations, postings, inbox state and reconciliation cases, not just response codes.

Include provider/environment mismatch, same key with changed amount, notification before the initiation response, partial reversal, legitimate multiple captures and an unknown payout. Explicitly isolate test credentials and prevent test traffic from reaching production execution adapters.

Monitor oldest unprocessed receipt, repeated processing failure, invalid verification, unresolved financial state and reconciliation age. A low webhook response time with a growing unprocessed inbox is not healthy end-to-end processing.

These checks are proposed for an implementation; no live payment operation was performed for this guide. For a scoped review of payment gateway integration, bring the event contract, state map and sample reconciliation records.

Frequently asked questions

Should all business processing happen before the webhook returns?

Follow the provider's acknowledgement contract. A durable, verified receipt with a recoverable worker can separate response timing from financial work, but storage and retry obligations must be explicit.

Is a payment ID a sufficient idempotency key?

Not necessarily. One payment can have several valid operations. Define identities for the actual financial effect and its scope.

Can the latest timestamp determine the correct payment state?

Not universally. Use documented lifecycle rules and authoritative records; delayed and corrective events can require different treatment.

Does an outbox remove the need for idempotent consumers?

No. Publication can repeat around acknowledgement failures. Consumers need their own repeat-safe effect boundary.

What should a dashboard show besides callback errors?

Show unprocessed evidence, processing age, unresolved payments, ledger conflicts and reconciliation ownership. Endpoint success alone is incomplete evidence.

Further reading

Primary sources

  1. Stripe documentation: Idempotent requests
  2. PCI Security Standards Council
  3. Adyen's HMAC documentation
  4. event-handling guide
  5. AWS's transactional outbox guidance