Bill payment services online depend on asynchronous notifications, but a webhook is not a transaction. It is a delivery attempt that can arrive late, arrive twice, arrive out of order, or never arrive at all. For a brokerage engineering team, that distinction matters when a provider event should credit a MetaTrader 5 or cTrader account, release a withdrawal, update a ledger, or trigger a reconciliation task.
This article presents a practical design for payment webhooks that remains correct under duplicates, timeouts, provider failures, and partial processing. The examples use bill-payment language, but the same patterns apply to deposits, withdrawals, recurring monthly payment flows, and other payment services connected to broker back offices.
Reference Architecture for Asynchronous Bill Payment Events
A reliable webhook system separates event delivery from business processing. The HTTP endpoint should authenticate the request, record the event, and acknowledge it quickly. It should not perform every downstream action while the provider connection is waiting.
A practical flow looks like this:
Payment Provider | | HTTPS webhook v Webhook Receiver | | Verify signature | Store raw event | Enforce event uniqueness v Inbox Table or Durable Queue | v Payment Event Worker | +--> Payment Intent State Machine +--> Ledger / Account Credit +--> Risk and Compliance Checks +--> Notification and Reporting | v Outbox / Provider Acknowledgement The receiver and worker should have different responsibilities:
- The receiver validates transport-level requirements and persists the event.
- The inbox prevents the same provider event from being accepted repeatedly.
- The worker applies business rules and changes internal state.
- The outbox records follow-up actions that must be delivered to other services.
- Reconciliation compares provider records with internal payment and ledger records.
For a forex or CFD brokerage, this boundary is especially useful because a payment event may affect several systems. A successful deposit could require a payment record update, a compliance decision, a balance credit, and a notification to the trading platform. If the webhook handler performs all four operations in one request, a timeout can leave the system uncertain about which operations completed.
The first durable write should normally contain the original payload, provider event ID, received timestamp, signature verification result, and a normalized event type. Preserve the raw payload even if the provider later changes fields or your parser contains a bug. It is valuable during investigations and replay operations.
Use a unique database constraint for the provider event ID. Application-level checks such as “query, then insert” are vulnerable to concurrent requests. Two workers can observe that an event is absent and both insert it. The database must enforce uniqueness.
A payment gateway integration can also expose multiple asynchronous paths, including card deposits, e-wallet updates, bank transfer confirmations, and crypto conversion results. In a multi-method setup, the receiver should normalize transport differences without erasing provider-specific data. The normalized record might contain:
{ "provider_event_id": "evt_123", "event_type": "payment.succeeded", "payment_intent_id": "pi_456", "amount": "250.00", "currency": "USD", "occurred_at": "2026-11-28T12:00:00Z", "raw_payload": {} } The event should be accepted only after authentication and schema validation. It should not be treated as proof that money can be credited until the payment state and the provider's payment reference have been checked.
Designing a Payment Intent State Machine
A payment intent should have explicit states rather than a collection of loosely related Boolean fields. For example, is_paid, is_failed, and is_refunded can produce contradictory combinations if separate handlers update them in different orders.
A state machine makes legal transitions visible:
created | +--> pending_provider | +--> succeeded --> credited | +--> failed | +--> expired credited | +--> reversed The names will vary by system, but the principles are stable:
- Every state has a defined meaning.
- Every transition has an allowed source state.
- Repeated events do not create a new side effect.
- Late events are evaluated against the current state.
- Irreversible actions require stronger validation than status updates.
Suppose a provider sends payment.succeeded twice. The first event moves the intent from pending_provider to succeeded, then credits the internal balance. The second event finds the intent already credited. It should be stored as a duplicate or no-op, not processed as a new deposit.
Now consider an out-of-order sequence. A payment.failed event arrives after payment.succeeded because of network delay. The handler should not blindly replace succeeded with failed. Instead, it should apply a transition policy. Some transitions are terminal, some are reversible, and some require a provider status lookup or manual reconciliation.
The state machine should distinguish payment status from account-credit status. A payment can be confirmed while the corresponding broker balance credit is still pending. Keeping these concepts separate avoids a dangerous assumption that a successful provider event means every internal action has finished.
For example:
Payment Status: succeeded Credit Status: pending Compliance Status: review This model is more useful than a single paid flag. It allows operations teams to see whether a payment is waiting for KYC or AML checks, a ledger transaction, a trading-platform API call, or manual review.
A worker should update the state and create the related side effect in a transaction where possible. If the ledger is a separate service, use a durable command or outbox record rather than relying on an in-memory function call.
For integrations that route deposits and withdrawals across multiple entities, settlement-account ownership should also be part of the intent context. A payment must not be credited to the wrong legal entity because a retry reused a generic account identifier. Teams working with broker-specific account structures can review the distinction between payment routing and a forex merchant account structure when defining these boundaries.
Idempotency Keys and the Exactly-Once Delivery Illusion
Exactly-once delivery is usually an illusion created by combining at-least-once delivery with idempotent processing. Networks fail between steps. A provider may send an event, your server may commit it, and the response may be lost before the provider receives it. The provider then retries even though the original request succeeded.
The correct goal is not “receive each event exactly once.” The goal is “make repeated delivery produce the same business result.”
There are usually two identifiers to track:
- The provider event ID, which identifies the notification.
- The payment or transaction ID, which identifies the underlying business object.
Both matter. A provider might emit several different events for one payment, such as authorization, capture, settlement, refund, or reversal. Deduplicating only by payment ID could discard legitimate lifecycle events. Deduplicating only by event ID could allow two different events to apply an invalid transition.
A basic inbox schema might look like this:
CREATE TABLE webhook_inbox ( id BIGSERIAL PRIMARY KEY, provider_event_id TEXT NOT NULL, payment_id TEXT NOT NULL, event_type TEXT NOT NULL, payload JSONB NOT NULL, received_at TIMESTAMPTZ NOT NULL, processed_at TIMESTAMPTZ, status TEXT NOT NULL, UNIQUE (provider_event_id) ); The business operation needs its own idempotency boundary. For example, a ledger credit could use a unique key composed of the payment ID and operation type:
CREATE UNIQUE INDEX one_credit_per_payment ON ledger_operations (payment_id, operation_type); That constraint protects against duplicate credits even if two workers process the same inbox record at the same time.
An idempotency key should not be accepted from an untrusted client as the only proof of identity. The server should bind it to the authenticated merchant, payment intent, amount, currency, and operation. A reused key with different parameters should produce a conflict, not a new operation.
The HTTP response also matters. A receiver should return a success status after the event is durably accepted, not after every downstream task has finished. HTTP status meanings are defined in the HTTP Semantics specification, but providers differ in how they interpret failures and retry windows. Document the behavior of each provider in configuration rather than embedding assumptions in application code.
At the gateway boundary, teams may receive events from cards, e-wallets, bank transfers, and crypto rails. A normalized idempotency layer allows those methods to share the same processing controls while retaining separate validation rules. Platforms such as iFin's payment gateway illustrate why a broker integration may need one operational view across many payment methods and currencies, without assuming that all provider events have identical semantics.
Retry Queues, Backoff Policies, and Dead-Letter Handling
Retries should be deliberate. Retrying every error immediately can create a feedback loop that increases load while the dependency is already unavailable.
Classify failures before selecting a retry action:
- Transient transport failure: retry with backoff.
- Provider rate limit: retry after the specified delay when available.
- Temporary database or queue failure: retry with bounded jitter.
- Invalid signature: reject and alert rather than retry.
- Invalid schema: quarantine for inspection.
- Unknown payment intent: retry briefly, then reconcile.
- Business rejection: mark the event according to the state policy.
Exponential backoff is common, but it should have a maximum delay and a maximum attempt count. Add random jitter so that many events received during the same outage do not retry simultaneously.
def next_delay(attempt): base = min(60 * (2 ** attempt), 3600) jitter = random.uniform(0, base * 0.2) return base + jitter The numbers are configuration examples, not universal defaults. A withdrawal status update may tolerate a longer delay than a deposit credit waiting for a trading-platform session. Define separate retry profiles by event class.
A queue message should contain enough information to resume processing safely:
{ "inbox_id": 9812, "provider_event_id": "evt_123", "attempt": 4, "available_at": "2026-11-28T12:08:00Z", "last_error_code": "provider_timeout" } Avoid putting large raw payloads in every queue message if the inbox already stores them durably. Referencing the inbox record reduces duplication and ensures that replay uses the preserved event.
A dead-letter queue is not a trash can. It is a controlled holding area for events that need investigation or a different processing path. Every dead-letter record should include the last error, attempt history, first-seen timestamp, and current payment state.
Replaying a dead-letter event must use the same idempotency checks as normal processing. Never create a separate “manual replay” path that bypasses uniqueness constraints. A replay should either complete the missing transition or safely produce a no-op.
Operations should also distinguish a failed delivery from a failed payment. A webhook can fail because your service was unavailable while the payment itself succeeded. Marking the payment as failed merely because the notification could not be processed creates reconciliation problems.
Testing Webhook Failure Modes with Local Tooling
A reliable webhook implementation needs failure tests that simulate timing and duplication, not only valid JSON payloads.
Start with a local receiver that can:
- Delay its response.
- Return configurable status codes.
- Close the connection before responding.
- Send the same event multiple times.
- Deliver events out of order.
- Change fields between attempts.
- Send malformed signatures or expired timestamps.
A compact test harness can exercise the receiver repeatedly:
for attempt in 1 2 3; do curl -i \ -X POST http://localhost:8080/webhooks/provider \ -H 'Content-Type: application/json' \ -H 'X-Signature: test-signature' \ --data @fixtures/payment-succeeded.jsondone``` The test should verify more than HTTP responses. Check that: - One inbox row exists for the provider event. - One ledger credit exists for the payment. - The final payment state is correct. - Duplicate deliveries are observable. - A retry after a timeout does not create a second side effect. - An out-of-order event follows the transition policy. - A dead-letter replay is safe. Inject a failure after each important step. For example: ```text 1. After signature verification 2. After inbox insert 3. After state transition 4. After ledger command creation 5. After outbound notification 6. Before HTTP acknowledgement This reveals the most important production scenario: the process completes a side effect and then crashes before acknowledging the webhook. The provider retries, and your idempotency controls must absorb the duplicate.
Use a database with real uniqueness constraints in integration tests. In-memory mocks often hide race conditions. Run concurrent workers against the same event and confirm that only one can create the ledger operation.
Contract tests should also validate provider-specific event schemas. When a provider adds a field, changes a status value, or sends a new event type, the receiver should fail safely and preserve the payload rather than silently treating it as a known event.
Measuring Delivery Latency, Duplicates, and Recovery Time
Webhook reliability needs operational measurements that describe both delivery and business completion.
Useful metrics include:
- Event receipt latency: provider event time to receiver acceptance.
- Queue delay: inbox acceptance to worker start.
- Processing latency: worker start to successful completion.
- End-to-end credit latency: provider event to ledger or account credit.
- Duplicate rate: repeated deliveries per event class.
- Retry depth: attempts before successful processing.
- Dead-letter count and age.
- Recovery time after a dependency outage.
- Reconciliation mismatch count.
Track these values by provider, event type, currency, and processing route. An average can hide a small group of events that remain stuck for hours. Percentile measurements and oldest-unprocessed age are more useful for operations.
Structured logs should include a correlation ID, provider event ID, payment intent ID, merchant entity, state before processing, state after processing, attempt number, and error classification. Do not log complete payment credentials or sensitive identity data.
A dashboard should answer practical questions quickly:
- Are events arriving but not being consumed?
- Are workers retrying one provider or all providers?
- Are duplicates increasing after a provider incident?
- Which payments are confirmed but not credited?
- How many dead-letter events are safe to replay?
- Is the problem delivery, state transition, compliance review, or ledger completion?
Alerting should focus on symptoms that require action. A sudden increase in duplicate events may indicate provider retries caused by slow acknowledgements. A growing queue may indicate worker capacity or a downstream outage. A stable queue with rising end-to-end latency may indicate that individual handlers are waiting too long.
The final control is reconciliation. At scheduled intervals, compare provider-side payment records with internal intents, ledger operations, and account credits. Reconciliation should create review tasks rather than directly applying unverified credits. It is the backstop for events that were delayed, malformed, lost, or routed to a dead-letter queue.
Reliable bill payment services are built around controlled uncertainty. Providers will retry, networks will interrupt requests, and workers will fail at inconvenient points. With a durable inbox, explicit state transitions, idempotent side effects, bounded retries, safe replay, and measurable recovery, those failures become operational cases instead of financial inconsistencies.
This article was created with the help of AI and reviewed by the author.
