Why do multi-PG transitions cause incidents, and what should you block first?

As transaction volume grows or a service expands into digital wallets and cross-border payments, relying on a single payment gateway (PG) becomes a bottleneck. Teams connect two or more providers to improve fee leverage and protect revenue during provider, VAN, or card-issuer outages. Yet stitching two provider APIs together with conditional branches often produces duplicate charges and settlement gaps before it ever saves a sale.

Failures tend to cluster around three boundaries. First, when an authorization response from the primary PG is delayed, the server requests a new authorization from a secondary PG without confirming whether the first transaction succeeded. Second, after traffic weights are changed, cancellation or partial refund requests for older orders are sent to the newly active PG instead of the original provider. Third, differing webhook retry rules and settlement formats across providers overwrite order states out of sequence.[2][6]

The goal of a multi-PG architecture is not merely swapping a provider name at runtime. Its core purpose is placing a common gateway layer between order/accounting systems and external providers so every transaction is tracked in a single ledger with its exact provider, merchant ID (MID), and lifecycle state.[7]

Separating order, payment, and fulfillment states for a single provider is covered in Payment succeeded, but there is no order: designing payment and order state consistency. Here we build on that state model to define adapter boundaries, failover preconditions, billing-key constraints, refund attribution, and settlement normalization across multiple payment providers.

Where should the boundary sit between order logic and PG adapters?

If adding a payment provider forces edits across cart, checkout, coupon deduction, refund screens, and admin tools, the system lacks a gateway layer. The order domain should only know how much needs to be authorized or refunded for an order, while provider-specific payload assembly and signature checks live inside gateway adapters.

Separating the gateway core from provider adapters confines a new provider integration to one adapter module and one settlement parser. Whether a provider uses client authentication followed by server confirmation (confirm) like Toss Payments or a Payment Intent lifecycle like Stripe, the gateway maps both onto a single internal payment-attempt state machine.[2][5]

LayerResponsibilityCore data persistedDelegated to provider adapter
Order and billing layerCalculate payable amount, lock discounts/inventory, trigger fulfillmentInternal order ID, item-level payable amounts, fulfillment stateNone (never references provider names directly)
Payment gateway coreRoute selection, payment attempt creation, idempotency, state transitionsPayment attempt ID, selected PG and MID, canonical state, routing reasonWhen to invoke confirm, cancel, or query and retry bounds
PG adapter layerProvider API calls, auth headers and idempotency keys, code translationRaw PG transaction key, raw response code and timestamp, payload hashProvider-specific HTTP requests and error-code mapping
Webhook and settlement collectorSignature verification, event deduplication, settlement file normalizationWebhook receipt ID, normalized transaction, fee, and payout-date rowsProvider-specific signature checks and CSV or API parsing

Canonical internal states should not copy a single provider's status strings verbatim. Define states around the next operational decision in your system, such as PREPARED (attempt created), AUTH_COMPLETED (buyer authenticated before capture), CAPTURE_PENDING (authorization in flight, outcome uncertain), CAPTURED (authorization confirmed), CANCEL_REQUESTED (cancellation in progress), CANCELED (cancellation confirmed), and FAILED (explicit decline).[2][4]

Persist the provider and merchant ID immutably on every payment attempt

When a first attempt on Provider A is declined and the buyer retries on Provider B, there is one internal order but two payment attempts. Each payment attempt record locks in the chosen provider code, merchant ID (MID), currency, routing rule version, and idempotency key at creation time.[3][5]

Without that immutable attempt record, operations cannot explain why an order routed to Provider B, and downstream refund or reconciliation jobs lose track of which merchant account to query. Criteria for evaluating providers before integration are available in the PG Selection Guide.

How the service works

Connect payment routes through one transaction model — Handle provider differences in the integration layer and manage routing and transaction state consistently.

Where do pre-checkout routing and post-authorization failover diverge?

The most dangerous misconception in multi-PG engineering is calling a secondary PG inside the catch block of a primary PG authorization call. Payment execution splits into pre-authentication (before opening the checkout window) and post-authorization request (when funds move), and the failover rules for those two phases are fundamentally different.[2][7]

Before opening the payment window, the gateway can freely assign any healthy provider based on health checks, issuer maintenance schedules, payment method, currency, fee tiers, or traffic weights. Once a buyer has authenticated inside a specific PG's checkout window, however, that authentication token cannot be captured on another provider. Furthermore, if your server calls the authorization API and receives a network timeout or 5xx response, the transaction enters an uncertain state where it may already have been approved.[3][4]

Phase and failure conditionChance original payment succeededImmediate failover to another PGSafe recovery procedure
Pre-checkout routing (maintenance notice or open circuit breaker)None (before call)AllowedCreate a new payment attempt with the secondary PG and MID
Buyer cancels or fails authentication in checkout windowNone (capture never called)Allowed (as a new attempt)Close the prior attempt and open a new attempt on the secondary PG
Pre-capture parameter or signature error (explicit 4xx decline)NoneConditionally allowed (new auth required)Inspect error code, request fresh buyer authentication, never reuse token
Post-capture response timeout, dropped connection, or 5xxPresent (outcome uncertain)Forbidden (risks duplicate charge)Query original PG status with same idempotency/transaction key or confirm network reversal
Original PG query confirms non-approval or completed reversalNone (termination verified)Allowed (requires buyer re-auth)Mark prior attempt as failed and guide buyer to a new attempt on secondary PG

Both Toss Payments and Stripe idempotency guidelines specify that network errors must be resolved by retrying against the same provider with the original Idempotency-Key or querying transaction status before taking any other action.[3][5] An idempotency key only prevents duplicate capture within the same provider; it cannot stop your server from creating a second charge on a different provider.

Circuit breakers should redirect only new checkout entries

To prevent cascading failures when error rates or latency cross a threshold, a circuit breaker should switch default routing for incoming traffic to a secondary provider.[7] That switch applies strictly to new checkout attempts.

In-flight transactions that have already authenticated on the primary PG and sit in CAPTURE_PENDING must not be handed over to the secondary PG when the circuit breaker trips. Finishing in-flight attempts through the primary provider's status-lookup and reversal pipeline prevents simultaneous approvals across two providers.

Why are subscription billing keys and card tokens incompatible across PGs?

Unlike one-time checkouts, recurring billing and one-click re-payments request authorization using a stored billingKey or customer payment-method token. Teams often assume a subscription charge can simply fail over to a secondary PG during an outage, but a standard PG billing key is a reference token valid only within that provider and merchant account (MID).

Passing a billing key issued by Provider A into Provider B's charge API results in an invalid-token decline. Delegating raw card storage to the provider and holding only a provider-scoped token is the exact mechanism used to minimize Payment Card Industry Data Security Standard (PCI DSS) compliance scope.[1]

  1. Single billing key with staged retry model: Most services that avoid expanding PCI DSS card-vault scope keep charges on the issuing PG and handle transient outages through exponential backoff retries and billing grace periods rather than cross-PG token failover.
  2. Backup payment method model: Allow customers to register a secondary payment method backed by a different provider or wallet in advance, and charge the backup method according to pre-disclosed rules only when the primary route suffers a permanent decline or extended outage.
  3. Guided re-registration migration model: When retiring a provider account or permanently shifting volume, prompt active subscribers during their renewal window to register a payment method on the new provider while keeping renewals and refunds alive on the old provider until migration completes.

Lifecycle states, retry schedules, and grace-period policies for recurring charges are covered in Does connecting a recurring billing API complete a subscription service?. When planning multi-PG support for subscriptions, verify token ownership and re-registration flows rather than assuming transparent cross-provider token portability.

Why must cancellations and partial refunds ignore current routing rules?

Even on the day you shift new traffic from 80% Provider A / 20% Provider B to 100% Provider B, customers who paid through Provider A yesterday will request cancellations and partial refunds. If the refund module reads the "current default PG" setting and sends a cancel request to Provider B, every refund fails with a transaction-not-found error.

Cancellations and partial refunds must bypass the routing engine and dispatch directly to the pg_provider, merchant_id (MID), and pg_transaction_id stored on the original payment attempt record. When an order undergoes multiple partial cancellations, each cancellation attempt links as a child of the original payment attempt, and refundable balance is validated against original captured amount minus cumulative refunded amount.[2]

Cancellation or refund scenarioRouting and attribution sourceConsistency check before executionSafeguard on failure
Full cancellation of an older order after routing changeLocked PG, MID, and transaction key on original payment attemptConfirm original attempt state is CAPTUREDNever consult the active routing table
Multi-step partial refunds on a single paymentOriginal attempt PG plus a distinct idempotency key per refund stepCumulative refunded amount plus current refund ≤ original captured amountHold for review if discount or shipping recalculation mismatches
Partial refund on a split order (points, coupon, and PG)Separate internal balance restoration from PG cash refund by priority ruleSum of PG cash refund and internal credit restoration matches order adjustmentIsolate in compensation-pending state if only one side succeeds
Network reversal after post-capture timeoutSame PG, MID, and order identifier used in the authorization requestConfirm capture status via lookup before issuing cancel or marking unapprovedMove to status-recheck queue if reversal response is lost

Calculation pitfalls around discounts, shipping fees, and taxable versus tax-exempt splits during partial refunds follow the rules in Why partial refund amounts drift: separating discounts, shipping, and refund state. In a multi-PG gateway, adapter metadata should also encode provider-specific partial-refund limits such as maximum refund count or time windows on certain wallets.

How the service works

Connect transaction states from order to refund — Integrate payment methods with orders and verify delays, retries, cancellations and refunds.

How do you normalize divergent webhooks and settlement files into one ledger?

Each payment provider uses different webhook event names, signature headers, timeouts, and retry schedules. Toss Payments requires an HTTP 200 response within 10 seconds and retries up to 7 times on failure, whereas Stripe documents endpoint-secret verification via Stripe-Signature and explicitly warns that events may arrive out of order.[2][6]

Configure webhook endpoints so the provider adapter verifies authenticity, persists the raw event payload durably, and returns 200 immediately. Downstream workers then translate the raw payload into a canonical internal event and pass it through the shared state-transition guard, preventing a delayed approval webhook from reopening an order that was already canceled.

Normalize raw provider settlement files into a common ledger schema before reconciliation

For finance and operations teams, the hardest part of running multiple PGs is reconciling incompatible Excel sheets and settlement APIs. One provider groups rows by transaction date while another groups by capture or payout date, and VAT or fee rounding rules vary by contract.

  • Stage 1 (Raw ingestion): Load each provider's settlement API response or file into an immutable raw table with ingestion timestamp and file hash.
  • Stage 2 (Canonical schema normalization): Map every provider row into unified columns: provider code, MID, provider transaction key, internal payment attempt ID, event type (capture/cancel), gross amount, provider fee, VAT, net settlement amount, and scheduled payout date.
  • Stage 3 (Three-way reconciliation): Match the internal order/payment ledger, the normalized PG settlement ledger, and bank deposit statements to classify missing transactions, fee discrepancies, and held payouts automatically.

Reconciliation matching rules and exception handling are detailed in When order totals, PG statements, and bank deposits differ, what is your reconciliation baseline? and the Payments Reconciliation Resource.

Which failover and edge-case scenarios must be tested before launch?

A multi-PG gateway cannot go live just because a happy-path payment succeeded in staging. Before production cutover, run fault-injection tests in an isolated sandbox to verify six operational boundaries.

Test scenarioInjected conditionPass criterionEvidence to verify
Pre-checkout provider switchForce primary PG circuit breaker openNew orders route to secondary PG checkout without delayRouting reason and secondary MID recorded on payment attempt
Timeout during capture callDelay primary PG capture response past timeoutNo automatic secondary PG charge; transaction enters lookup/reversal queueExactly one active captured transaction exists for the order
Refund after routing changeSwitch default PG from A to B, then partially refund an A orderRefund request dispatches to Provider A's original MID and succeedsRefund attempt log showing Provider A and original transaction key
Duplicate and out-of-order webhooksReplay an older approval webhook after cancellation completesCanceled state remains intact and is not overwritten by stale approvalWebhook receipt log and rejected state-transition audit entry
Sequential retry on same orderProvider A declines for limit exceeded, buyer retries on Provider BAttempt 1 closes as failed, Attempt 2 captures, fulfillment runs onceTwo attempt records linked to one order and one fulfillment constraint
Multi-PG daily settlement reconciliationFeed sample capture, partial refund, and fee files from PGs A and BNormalized ledger isolates count, amount, and fee variances accuratelyPer-provider reconciliation report and exception queue output

You can cross-check required pre-launch controls item by item in the Payment Integration Checklist.

Keeping new payment providers from turning into full service rewrites

The success of a multi-PG rollout depends less on how many providers you sign than on how cleanly your gateway layer isolates order and accounting logic from provider specifics. Once payment-attempt identifiers, pre- versus post-capture failover boundaries, original-PG refund attribution, and normalized settlement ledgers are in place, adding a new PG or wallet becomes a single adapter addition rather than a platform rewrite.

Start by inspecting whether your current database separates order IDs from payment-attempt IDs and tracing which branch your code takes when a capture call times out. Checking those two points alone reveals most duplicate-charge risks before a multi-PG migration begins.

If your team is planning to evolve a single-PG checkout into a multi-PG gateway or streamline authorization, cancellation, and settlement reconciliation pipelines, explore project scope through our Payment Gateway Architecture Service, PG Integration & Payment System Build Service, and Reconciliation Automation Service.