DEV Community

Cover image for Building an Idempotent Payment Webhook Pipeline
ifin.co
ifin.co

Posted on

Building an Idempotent Payment Webhook Pipeline

Building an Idempotent Payment Webhook Pipeline

A payment gateway is only as reliable as the system that receives and processes its events. For a forex or CFD brokerage, a webhook may confirm a deposit, update a withdrawal, or report a failed authorization. If that event is lost, processed twice, or applied out of order, the result can be an incorrect balance, a duplicate payout, or a support incident that is difficult to reconstruct.

We build webhook pipelines around one assumption: delivery is at least once, not exactly once. The provider may retry an event, the network may time out after successful processing, and workers may restart halfway through a transaction. Idempotency, durable ingestion, explicit state transitions, and observable retries turn those failure modes into controlled behavior.

Event Contracts and Signature Verification

Start with the event contract before writing the consumer. A webhook should contain enough information to identify the event, the business object, and the state transition being reported.

A practical event envelope usually includes:

  • event_id, unique for the original event
  • event_type, such as deposit authorized or withdrawal settled
  • occurred_at, the provider timestamp
  • merchant_account_id or entity identifier
  • payment_id or withdrawal identifier
  • amount and currency
  • status
  • attempt
  • payload_version
  • signature or signature headers

The event ID must identify the event itself, not the delivery attempt. If the provider sends the same event three times, all three deliveries should carry the same event ID. The retry attempt can be tracked separately.

We also recommend treating the payload as an immutable fact. Do not mutate the original event after it enters the system. If a field needs normalization, store the original message and create a normalized internal representation alongside it.

Verify Before Trusting the Payload

Signature verification must happen before business processing. The receiver should validate:

  1. The signature against the exact raw request body.
  2. The timestamp or freshness window, if the provider signs one.
  3. The key ID, if several signing keys are active.
  4. The expected merchant entity or account.
  5. The supported payload version.

Parsing and reserializing JSON before verification can invalidate a signature because field order, whitespace, or escaped characters may change. Read the raw body first, verify it, then parse it.

A common signed-message pattern is:

signed_content = timestamp + "." + raw_body
signature = HMAC_SHA256(secret, signed_content)
Enter fullscreen mode Exit fullscreen mode

The actual construction depends on the provider. The important design rule is that the verification algorithm, canonical input, timestamp tolerance, and key rotation procedure must be documented as part of the event contract.

For systems using a standardized approach to signed HTTP messages, the HTTP Message Signatures standard provides useful terminology and design guidance. A custom HMAC scheme can still be valid, but it should be explicit and consistently implemented across services.

Never use the webhook signature as the idempotency key. A new delivery may have different transport headers while representing the same business event.

The Ingestion Path: Queue, Store, and Acknowledge

The HTTP endpoint should do as little work as possible. Its responsibility is to authenticate the request, persist the event safely, enqueue processing, and return an appropriate response.

The recommended path is:

Provider
   |
   v
Webhook API
   |
   +--> Verify signature
   |
   +--> Insert immutable event
   |
   +--> Enqueue event reference
   |
   v
Fast acknowledgement

Worker
   |
   +--> Load event
   +--> Check processing state
   +--> Apply business transition
   +--> Record outcome
Enter fullscreen mode Exit fullscreen mode

Do not call a trading platform, ledger service, fraud engine, or payout provider inside the initial HTTP request unless there is a strong operational reason. A slow downstream dependency can cause the provider to time out and retry. That retry may arrive while the first request is still running, creating concurrent processing.

The durable event store and queue should be coordinated carefully. A common failure looks like this:

  1. The API writes the event to the database.
  2. The process crashes before publishing to the queue.
  3. The provider assumes delivery failed and retries.
  4. The system now has a stored event but no queued job.

The outbox pattern addresses this gap. The request transaction stores both the received event and an outbox record. A separate publisher reads unsent outbox records and places them on the queue. The publisher may also deliver an item more than once, which is acceptable because the consumer is idempotent.

For a brokerage, the initial response should distinguish between accepted and rejected messages. A valid event that has been durably stored can usually receive a success response even if downstream processing has not finished. An invalid signature, malformed body, unsupported authentication method, or unacceptable entity should be rejected without entering the processing queue.

Operational documentation for broker payment operations should reflect this separation between receipt, processing, and settlement. It helps support teams understand why a provider may show a successful delivery while the internal payment status is still pending.

Keep the Raw Event

Store the raw body, selected headers, verification result, received timestamp, and source address where appropriate. The raw event supports incident analysis, replay, and future parser changes.

Avoid storing secrets or unnecessary personal data in logs. The event database may need stricter access controls than ordinary application logs because it can contain payment and customer information.

Idempotency Keys and Duplicate Delivery Control

Idempotency means that processing the same event more than once produces the same business result as processing it once. It does not mean that every database operation is automatically safe to repeat.

Use a database uniqueness constraint on the provider event ID:

CREATE TABLE payment_events (
    event_id              VARCHAR(128) PRIMARY KEY,
    payment_id             VARCHAR(128) NOT NULL,
    event_type             VARCHAR(64) NOT NULL,
    payload                JSONB NOT NULL,
    received_at            TIMESTAMP NOT NULL,
    processing_status      VARCHAR(32) NOT NULL,
    processed_at           TIMESTAMP NULL,
    last_error             TEXT NULL
);
Enter fullscreen mode Exit fullscreen mode

The unique key prevents two workers from inserting the same event as separate records. However, it does not by itself protect the business operation. The consumer must also make the state transition conditional.

For example, a deposit confirmation should not simply execute:

UPDATE balances
SET available_amount = available_amount + :amount
WHERE account_id = :account_id;
Enter fullscreen mode Exit fullscreen mode

If the handler runs twice, the balance may be credited twice. Instead, record a ledger entry with a unique reference derived from the payment event:

INSERT INTO ledger_entries (
    idempotency_key,
    account_id,
    amount,
    currency,
    entry_type
)
VALUES (
    :event_id,
    :account_id,
    :amount,
    :currency,
    'deposit'
)
ON CONFLICT (idempotency_key) DO NOTHING;
Enter fullscreen mode Exit fullscreen mode

Only a newly inserted ledger entry should affect the account balance. The ledger insert and balance update should be performed in one transaction, or the balance should be derived from an append-only ledger.

Separate Event Idempotency From Business Idempotency

A provider event ID protects against duplicate delivery of that event. A business idempotency key protects against duplicate execution of an operation.

These may not be identical. For example:

  • One payment can generate multiple legitimate lifecycle events.
  • A provider may issue a corrected event with a new event ID.
  • A manual replay may reuse the original event ID.
  • A withdrawal instruction may need protection across both API requests and webhook events.

Define the invariant explicitly. A withdrawal should have one approved instruction, one payout reference, and one final settlement effect. The system should reject or safely ignore attempts that would violate that invariant, even if the incoming event IDs differ.

Handle Out-of-Order Events

A successful event can arrive before an earlier pending event. Do not assume delivery order unless the provider guarantees it and the guarantee is enforced per payment.

Store the event sequence or provider version when available. Then apply rules such as:

  • Ignore a transition that is older than the stored payment state.
  • Accept a terminal state only from an authorized transition.
  • Keep unknown future states without treating them as failures.
  • Route contradictory events for review rather than overwriting data silently.

This state-machine approach is safer than mapping every webhook directly to a database update.

Retry Backoff, Dead-Letter Queues, and Replay

Retries should be based on the error category, not merely on whether the handler returned an exception.

Transient failures include temporary database unavailability, queue timeouts, rate limits, and short-lived downstream errors. These may be retried with exponential backoff and jitter:

delay_seconds = min(
    base_delay * (2 ** retry_count) + random_jitter,
    maximum_delay
)
Enter fullscreen mode Exit fullscreen mode

Permanent failures include an invalid payload version, an unknown payment reference, a failed signature, or a state transition that violates business rules. Retrying these errors without changing the input only creates noise.

A useful worker outcome model is:

SUCCESS
RETRYABLE_FAILURE
PERMANENT_FAILURE
MANUAL_REVIEW
Enter fullscreen mode Exit fullscreen mode

The distinction should be recorded with the event, not left only in application logs. That gives operations teams a way to query all events waiting for replay or review.

Dead-Letter Queues Are Part of the Design

A dead-letter queue is not a disposal area. It is a controlled holding area for events that exceeded their retry policy or require human analysis.

Each dead-letter record should preserve:

  • Original event ID
  • Payment or withdrawal ID
  • Last error category
  • Last error message, redacted where necessary
  • Retry count
  • First failure time
  • Last attempt time
  • Consumer version
  • Suggested next action

Replay must be deliberate. A replay tool should support filtering by event ID, payment ID, date range, error type, and consumer version. It should also show whether the event already produced a business effect.

Never replay by deleting the original event and pretending it was never processed. Keep the original record, create a replay attempt, and link the attempt to its source. This maintains an audit trail and prevents operators from losing the history of a difficult incident.

For a broker, this matters when a deposit status has already reached an internal account but the external platform update failed. The replay target may be only the platform synchronization step, not the entire payment flow. Designing handlers as smaller idempotent stages makes selective replay possible.

Mapping Acquirer Failures to Stable API Errors

External payment providers often return different codes for similar conditions. If those codes leak directly into the brokerage API, every integration client becomes dependent on provider-specific behavior.

Create an internal error taxonomy with stable meanings. For example:

PAYMENT_DECLINED
PAYMENT_REQUIRES_ACTION
PAYMENT_TEMPORARILY_UNAVAILABLE
PAYMENT_LIMITED
PAYMENT_NOT_FOUND
PAYMENT_DUPLICATE
PAYMENT_INVALID_REQUEST
PAYMENT_COMPLIANCE_REVIEW
PAYMENT_UNKNOWN_ERROR
Enter fullscreen mode Exit fullscreen mode

The adapter layer maps provider responses into this taxonomy. Store both values:

  • The stable internal code for application behavior.
  • The original provider code for investigation and reporting.

Do not map every unknown response to PAYMENT_DECLINED. A timeout is not the same as a refusal, and a compliance review is not the same as an invalid card request. Incorrect categorization can cause the frontend to show the wrong instruction and can make retry behavior unsafe.

The mapping should also determine whether a webhook is terminal. A provider may send a temporary failure followed by a success. Another may send a final decline that should never be retried automatically. Those differences belong in the adapter contract.

Use versioned mappings. When a provider changes its response codes, update the adapter without changing the meaning of the internal API unless the business semantics have changed. This keeps MetaTrader 5, cTrader, back-office, and mobile clients insulated from provider-specific changes.

When evaluating a merchant account integration model, document which errors are exposed to the brokerage, which remain internal, and which require manual review. The technical contract should be clear before multiple teams build against it.

Observability with Correlation IDs and Latency Metrics

A webhook incident often crosses several systems: provider, API gateway, queue, worker, ledger, fraud service, and trading platform. Without correlation IDs, engineers are forced to search by timestamps and partial payment references.

Generate or propagate these identifiers:

  • correlation_id for the complete business flow
  • event_id for the provider event
  • payment_id for the payment lifecycle
  • delivery_id for the individual webhook attempt
  • job_id for the queue message
  • ledger_entry_id for the accounting effect

Return the correlation ID in API responses where appropriate and include it in structured logs. Do not put sensitive payment data into the ID itself.

Track latency as separate measurements rather than one total number:

  • Time from provider event creation to receipt
  • Signature verification duration
  • Time from receipt to durable storage
  • Queue wait time
  • Worker execution time
  • Downstream provider latency
  • Time from authorization to account credit
  • Time from withdrawal approval to payout status update

These measurements reveal different failure modes. A growing queue wait time points to worker capacity or downstream blocking. A high receipt-to-storage time points to the ingress service. A long authorization-to-credit interval may indicate an internal state transition issue rather than a payment provider problem.

Useful metrics include event throughput, duplicate rate, retry count, dead-letter volume, processing age, terminal error rate, and the number of payments stuck in non-terminal states. Alert on changes in behavior, not only absolute failures. A sudden increase in duplicate deliveries can indicate provider retries, network timeouts, or slower acknowledgements.

Finally, test the pipeline with failure injection. Kill workers after the ledger commit, delay queue acknowledgements, send duplicate events concurrently, reorder lifecycle messages, and replay dead-lettered records. The goal is not to prove that failures never occur. The goal is to prove that the same payment cannot be credited or paid out twice, that every event remains traceable, and that recovery does not depend on guesswork.

This article was created with the help of AI and reviewed by the author.

Top comments (0)