Backend Engineer Guide: Polymorphic Multi-Gateway Payment Routing & Automatic Failover in Go
Relying on a single payment processor exposes checkout conversion to regional acquiring bank outages, card-network routing degrades, and webhook schema lock-in. Yet scattering provider-specific SDK structs across your order service makes adding a backup gateway a three-month rewrite. As a backend engineer building multi-region checkout and settlement systems in Go, I isolate payment providers behind a polymorphic PaymentGateway interface with health-aware circuit breaking and canonical webhook normalization.
1. Canonical Domain Types & Polymorphic Provider Interface in Go
All monetary amounts are represented strictly in minor currency units (int64 cents/sen) alongside an ISO-4217 currency code—never float64. Each payment adapter translates between the canonical domain struct and the provider's wire format:
// payments/gateway.go
package payments
import (
"context"
"errors"
)
type ChargeRequest struct {
IdempotencyKey string
OrderID string
AmountMinor int64 // e.g., 15000000 for IDR 150,000 or 9900 for $99.00
Currency string // ISO-4217: "USD", "IDR", "SGD"
CustomerEmail string
}
type ChargeResult struct {
ProviderName string
ProviderReference string
CheckoutURL string
Status string // "PENDING", "SUCCEEDED", "FAILED"
}
type PaymentGateway interface {
Name() string
CreateCharge(ctx context.Context, req ChargeRequest) (*ChargeResult, error)
Healthy(ctx context.Context) bool
}
type FailoverRouter struct {
primary PaymentGateway
fallback PaymentGateway
}
func NewFailoverRouter(primary, fallback PaymentGateway) *FailoverRouter {
return &FailoverRouter{primary: primary, fallback: fallback}
}
func (r *FailoverRouter) ChargeWithFailover(ctx context.Context, req ChargeRequest) (*ChargeResult, error) {
if r.primary.Healthy(ctx) {
res, err := r.primary.CreateCharge(ctx, req)
if err == nil {
return res, nil
}
}
if r.fallback != nil && r.fallback.Healthy(ctx) {
return r.fallback.CreateCharge(ctx, req)
}
return nil, errors.New("all configured payment gateways are unavailable")
}
2. Deterministic Idempotency Key Derivation Across Retries
Note that if a network timeout occurs during primary.CreateCharge, blindly failing over to fallback.CreateCharge without first checking whether the primary gateway actually captured the card could double-charge the customer. For direct card captures, failover only occurs on connection/5xx pre-authorization errors or when routing Hosted Checkout session creation prior to user payment entry.