Payment Processing Architecture: From Swipe to Settlement
Every time a customer taps "Pay," a chain of network calls spanning card networks, issuing banks, and acquiring banks fires in under two seconds. Building a reliable payment processing architecture means understanding each hop, protecting cardholder data at every layer, and handling the edge cases — retries, refunds, chargebacks, and currency conversion — that turn a toy checkout into a production-grade money pipeline.
The Payment Flow: Authorization, Capture, Settlement#
A card transaction moves through three distinct phases:
- Authorization — The merchant's payment gateway sends an authorization request through the card network (Visa, Mastercard) to the issuing bank. The bank checks funds, fraud signals, and 3-D Secure challenges, then returns an approval code or decline.
- Capture — The merchant signals that the goods or services have been fulfilled and the authorized amount should be collected. Some integrations use auth-and-capture in a single step; others separate them (hotel pre-auths, for example).
- Settlement — The card network orchestrates the net transfer of funds between the issuing bank and the acquiring bank, typically in a nightly batch. The merchant receives the settled amount minus interchange and processing fees.
Understanding this three-phase model is critical because failures can occur at each stage. An authorization may succeed but capture may fail if the auth expires (usually 7 days for e-commerce).
PCI DSS Compliance#
The Payment Card Industry Data Security Standard defines 12 requirements organized into six goals: build a secure network, protect cardholder data, maintain a vulnerability management program, implement strong access control, monitor and test networks, and maintain an information security policy.
For most engineering teams, the practical approach is to minimize PCI scope:
- Never store raw card numbers. Use a PCI-compliant vault or processor.
- Use hosted payment fields (Stripe Elements, Braintree Drop-in) so card data never touches your servers.
- SAQ A vs SAQ D — Hosted fields qualify you for the simplest self-assessment questionnaire (SAQ A), dramatically reducing compliance burden.
- Tokenize early, tokenize always. Replace PANs with opaque tokens at the edge.
Tokenization#
Tokenization replaces sensitive card data with a non-reversible token that is meaningless outside the payment processor's vault.
Customer → Hosted Field → Processor Vault → Token returned
↓
Encrypted PAN stored
(processor's PCI environment)
Tokens can be single-use (for one-time payments) or multi-use (for saved cards and subscriptions). Network tokens issued by card networks (Visa Token Service, Mastercard MDES) go further — they improve authorization rates and automatically update when a card is reissued.
Choosing a Payment Gateway#
The three dominant modern gateways each have architectural trade-offs:
| Feature | Stripe | Braintree | Adyen |
|---|---|---|---|
| Developer experience | Best-in-class SDKs, docs | Good, PayPal-native | Enterprise-focused |
| Global acquiring | 46+ countries | 45+ countries | 30+ countries (direct) |
| Pricing model | Flat percentage | Flat percentage | Interchange++ |
| Subscription billing | Native (Stripe Billing) | Add-on | Partial |
| Multi-currency | Automatic conversion | Supported | Strong multi-acquiring |
For startups, Stripe's developer experience and unified API surface are hard to beat. For enterprise merchants processing at scale, Adyen's interchange-plus pricing and direct acquiring relationships often win on cost.
Multi-Gateway Strategy#
High-volume merchants route transactions through multiple gateways to:
- Increase authorization rates by retrying declines on an alternate processor.
- Reduce concentration risk — a single gateway outage does not halt revenue.
- Optimize interchange by routing domestic transactions through local acquirers.
Implement a routing layer that selects the gateway based on card BIN, currency, amount, and historical approval rates.
Idempotent Payments#
Network failures between your server and the payment gateway create a dangerous scenario: the charge may have succeeded, but you never received the response. Without idempotency, a naive retry will double-charge the customer.
Idempotency keys solve this. Attach a unique client-generated key (typically a UUID) to every payment request. The gateway stores the key-to-response mapping; replaying the same key returns the original result without re-executing the charge.
const paymentIntent = await stripe.paymentIntents.create(
{ amount: 2500, currency: 'usd', payment_method: pmId },
{ idempotencyKey: `order_${orderId}_attempt_${attemptNo}` }
);
Design your key scheme carefully. Tying it to the order ID prevents duplicate orders; appending an attempt counter allows intentional retries after a genuine decline.
Webhook Handling#
Payment events are inherently asynchronous. Dispute opened, payout completed, subscription renewed — these arrive as webhooks, not synchronous responses.
Reliable webhook processing checklist:
- Verify signatures. Every major gateway signs webhook payloads (HMAC-SHA256). Reject unsigned events.
- Respond 2xx immediately. Perform heavy processing asynchronously after acknowledging receipt.
- Idempotent handlers. Webhooks can be delivered more than once. Deduplicate by event ID.
- Ordered processing. Events for the same resource may arrive out of order. Use event timestamps or sequence numbers.
- Dead-letter queue. If processing fails after retries, route the event to a DLQ for manual investigation.
Gateway → Your Endpoint → 200 OK → Enqueue Job → Process Async
↓
Verify Signature
Deduplicate by event_id
Update order state
Refunds and Chargebacks#
Refunds are merchant-initiated reversals. They follow the settlement path in reverse: the acquirer debits the merchant and the issuer credits the cardholder. Refunds can take 5–10 business days to appear on the customer's statement.
Chargebacks are customer-initiated disputes filed through the issuing bank. The merchant must respond with compelling evidence within a tight window (usually 7–20 days depending on the network).
Architectural considerations:
- Track refund state separately from order state. An order can be partially refunded.
- Store evidence artifacts (receipts, shipping tracking, logs) in a format ready for chargeback response.
- Monitor chargeback ratios. Exceeding 1% triggers card network monitoring programs and potential fines.
Subscription Billing#
Recurring billing adds state management complexity on top of one-time payments:
- Billing cycles — Monthly, annual, usage-based, or hybrid plans.
- Proration — Upgrading mid-cycle requires calculating the difference.
- Dunning — When a renewal charge fails, retry with exponential backoff (day 1, day 3, day 7) before canceling.
- Trial management — Track trial start, end, and conversion without charging prematurely.
- Plan versioning — Grandfather existing subscribers when pricing changes.
Most teams should lean on Stripe Billing or a dedicated billing engine like Recurly or Chargebee rather than building subscription state machines from scratch.
Subscription Created → Invoice Generated → Payment Attempted
↓ ↓
Trial Period Success → Activate
Failure → Dunning Retry
↓
Final Failure → Cancel
Multi-Currency Support#
Selling globally means handling multiple currencies, and the architecture has two main approaches:
- Presentment currency conversion — Display prices in the customer's local currency but settle in your base currency. The payment processor handles FX at the time of charge.
- Multi-currency settlement — Maintain bank accounts in multiple currencies and settle locally. This avoids FX fees but adds treasury complexity.
Key implementation details:
- Store amounts in minor units (cents, pence) as integers to avoid floating-point errors.
- Record the currency code (ISO 4217) alongside every monetary amount.
- Lock the exchange rate at the time of charge and store it for reconciliation.
- Handle partial refunds in the original transaction currency, not the settlement currency.
Putting It All Together#
A production payment processing architecture typically looks like this:
Client (Hosted Fields)
↓ token
API Gateway → Payment Service → Gateway Router
↓ ↓
Order Service Stripe / Adyen / Braintree
↓ ↓
Database (orders, Webhooks → Event Processor
subscriptions, ↓
refund state) Update order state
Trigger notifications
The payment service owns idempotency, retry logic, and gateway selection. The event processor handles asynchronous webhook events, deduplicates them, and updates downstream systems. The order service maintains the business state — what was purchased, its fulfillment status, and refund history.
Payment processing architecture is one of the highest-stakes system design domains. Card data must be protected, charges must never be duplicated, and every edge case — expired auths, partial refunds, currency mismatches, chargeback deadlines — must be handled gracefully. Get the foundations right and you build customer trust and regulatory confidence from day one.
Want to explore more system design topics? Visit codelit.io for visual, interactive deep dives.
This is article #167 in the Codelit system design series.
Try it on Codelit
Chaos Mode
Simulate node failures and watch cascading impact across your architecture
Related articles
Try these templates
E-Commerce Checkout System
Production checkout flow with Stripe payments, inventory management, and fraud detection.
11 componentsPayment Processing Platform
PCI-compliant payment system with multi-gateway routing, fraud detection, and reconciliation.
9 componentsDigital Banking Platform
Neobank with accounts, transfers, card management, budgeting, and regulatory compliance.
9 componentsBuild this architecture
Generate an interactive Payment Processing Architecture in seconds.
Try it in Codelit →
Comments