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]
| Layer | Responsibility | Core data persisted | Delegated to provider adapter |
|---|---|---|---|
| Order and billing layer | Calculate payable amount, lock discounts/inventory, trigger fulfillment | Internal order ID, item-level payable amounts, fulfillment state | None (never references provider names directly) |
| Payment gateway core | Route selection, payment attempt creation, idempotency, state transitions | Payment attempt ID, selected PG and MID, canonical state, routing reason | When to invoke confirm, cancel, or query and retry bounds |
| PG adapter layer | Provider API calls, auth headers and idempotency keys, code translation | Raw PG transaction key, raw response code and timestamp, payload hash | Provider-specific HTTP requests and error-code mapping |
| Webhook and settlement collector | Signature verification, event deduplication, settlement file normalization | Webhook receipt ID, normalized transaction, fee, and payout-date rows | Provider-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.
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 condition | Chance original payment succeeded | Immediate failover to another PG | Safe recovery procedure |
|---|---|---|---|
| Pre-checkout routing (maintenance notice or open circuit breaker) | None (before call) | Allowed | Create a new payment attempt with the secondary PG and MID |
| Buyer cancels or fails authentication in checkout window | None (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) | None | Conditionally allowed (new auth required) | Inspect error code, request fresh buyer authentication, never reuse token |
Post-capture response timeout, dropped connection, or 5xx | Present (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 reversal | None (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]
- 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.
- 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.
- 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 scenario | Routing and attribution source | Consistency check before execution | Safeguard on failure |
|---|---|---|---|
| Full cancellation of an older order after routing change | Locked PG, MID, and transaction key on original payment attempt | Confirm original attempt state is CAPTURED | Never consult the active routing table |
| Multi-step partial refunds on a single payment | Original attempt PG plus a distinct idempotency key per refund step | Cumulative refunded amount plus current refund ≤ original captured amount | Hold 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 rule | Sum of PG cash refund and internal credit restoration matches order adjustment | Isolate in compensation-pending state if only one side succeeds |
| Network reversal after post-capture timeout | Same PG, MID, and order identifier used in the authorization request | Confirm capture status via lookup before issuing cancel or marking unapproved | Move 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.
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 scenario | Injected condition | Pass criterion | Evidence to verify |
|---|---|---|---|
| Pre-checkout provider switch | Force primary PG circuit breaker open | New orders route to secondary PG checkout without delay | Routing reason and secondary MID recorded on payment attempt |
| Timeout during capture call | Delay primary PG capture response past timeout | No automatic secondary PG charge; transaction enters lookup/reversal queue | Exactly one active captured transaction exists for the order |
| Refund after routing change | Switch default PG from A to B, then partially refund an A order | Refund request dispatches to Provider A's original MID and succeeds | Refund attempt log showing Provider A and original transaction key |
| Duplicate and out-of-order webhooks | Replay an older approval webhook after cancellation completes | Canceled state remains intact and is not overwritten by stale approval | Webhook receipt log and rejected state-transition audit entry |
| Sequential retry on same order | Provider A declines for limit exceeded, buyer retries on Provider B | Attempt 1 closes as failed, Attempt 2 captures, fulfillment runs once | Two attempt records linked to one order and one fulfillment constraint |
| Multi-PG daily settlement reconciliation | Feed sample capture, partial refund, and fee files from PGs A and B | Normalized ledger isolates count, amount, and fee variances accurately | Per-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.


