Payment systems architecture
Design multi-provider payment platforms: orchestration and routing, end-to-end idempotency, outbox and sagas, fraud prevention, PCI scope reduction, international payments and FX, compliance and security architecture.
- Level
- Advanced
- Modules
- 7
- Lessons
- 14
- Price
- Free
What you will learn
- Design a provider-agnostic payment layer with routing and failover
- Guarantee exactly-once business effects with idempotency, outbox and sagas
- Build layered fraud controls appropriate to cards and mobile money
- Minimise PCI DSS scope and protect payment pages from script attacks
- Plan international acceptance: local methods, FX, settlement currency and entities
- Map regulatory obligations (licensing, KYC/AML, data protection) for a payment product
- Threat-model a payment flow and secure keys, webhooks and payouts
Module 1: Multi-provider architecture and orchestration
One internal API, many providers, explicit routing rules.
Provider abstraction without lowest-common-denominator
A good abstraction normalises what all providers share (create, status, refund, webhooks, amounts, statuses) while exposing capabilities explicitly (supports partial capture? recurring? payouts?). Avoid pretending every provider is the same — route only to providers whose capabilities match the request.
Key design points:
- A canonical status model with provider mappings tested per adapter.
- Provider-specific references stored alongside your own id.
- Credentials per provider, per environment, per entity/country.
- Token portability: card tokens are provider-specific; network tokens or a third-party vault make switching possible.
Routing and failover
Routing chooses a provider per transaction using transparent rules: method and country support first, then cost, approval rate and provider health. Failover retries on another provider only when it is safe — e.g. the first attempt clearly failed before authorization. A timeout is *not* safe to fail over: you could double-charge.
Measure per provider: approval rate by BIN country/method, latency, error rates and cost. Change rules behind feature flags and watch the metrics.
For mobile money, routing often follows the customer's operator (detected from the phone prefix, verified with the API) rather than cost.
Exercise: Routing design doc
Write a one-page design for a router that serves Kenya (M-Pesa), Nigeria (cards + bank transfer) and the EU (cards + SEPA). Define the capability model, routing rules, failover rules and the metrics you will monitor.
Module 2: Idempotency and distributed transactions
Exactly-once business effects in an at-least-once world.
Idempotency end-to-end
Idempotency must exist at every boundary:
- Client → your API: clients send an Idempotency-Key; you store the key with the request hash and the response, and replay it on retries.
- Your API → provider: pass a key derived from your payment id.
- Provider → your webhooks: deduplicate by event id; state transitions ignore repeats.
- Your workers: jobs must tolerate redelivery (unique constraints, compare-and-set updates).
Reject a reused key with a *different* request body — that indicates a client bug. See the IETF Idempotency-Key header draft.
Outbox and sagas
The dual-write problem: you update your database *and* call a provider or publish an event — one can succeed while the other fails. The transactional outbox fixes it: write the state change and an outbox row in one transaction; a relay delivers the outbox row later, retrying until acknowledged.
Multi-step flows (reserve stock → authorize → create shipment → capture) span services and cannot use one ACID transaction. A saga runs each step as a local transaction with a compensating action (release stock, void authorization, refund). Compensations must be idempotent and may need human review when they fail.
Further reading: Transactional outbox, Saga.
Exercise: Saga with compensation
Implement an orchestrated saga for 'checkout' with three steps (reserve stock, authorize payment, create shipment) and compensations. Inject failures at each step and show the system ends consistent.
Module 3: Fraud prevention
Layered controls for cards and mobile money without killing conversion.
Layered fraud defence
No single control stops fraud. Layer them:
- Before payment: account age, email/phone verification, device fingerprint, velocity checks.
- At payment: provider risk engine, AVS/CVV results, BIN country vs IP country, 3DS step-up for risky orders.
- After payment: manual review queues, delayed fulfilment for high-risk goods, chargeback feedback into rules.
Track false declines as carefully as fraud losses — blocking good customers is also a cost.
Card testing and mobile-money abuse
Card testing: bots try many stolen cards with tiny amounts. Defences: rate limits per IP/device/session, CAPTCHA after failures, minimum amounts, blocking repeated declines per BIN.
Mobile money abuse looks different: STK prompt spam to random numbers, social-engineering 'I sent you money by mistake' scams, and payout fraud via compromised accounts. Defences: per-phone rate limits, confirm the paying number matches the account, hold first payouts to new recipients, and alert on unusual payout patterns.
Exercise: Velocity limiter
Build a sliding-window velocity limiter (e.g. Redis or in-memory) with rules for card attempts per IP, per BIN and STK prompts per phone. Add a test that simulates a card-testing attack.
Module 4: PCI DSS scope reduction
Keep card data out of your systems and protect payment pages.
Shrinking your PCI scope
PCI DSS v4.0.1 applies to any system that stores, processes or transmits cardholder data — or can affect its security. Your scope (and your SAQ) depends on architecture:
- SAQ A — payment fields entirely hosted by a PCI-compliant provider (redirect or provider iframe).
- SAQ A-EP — your page controls how card data is collected (e.g. direct post), though your servers never receive it.
- SAQ D — your servers handle card data.
Techniques: hosted fields/iframes, tokenization, never logging request bodies on payment routes, network segmentation, and treating mobile apps as clients that only ever see tokens.
Script security on payment pages
Skimming attacks inject JavaScript into checkout pages to steal card data before it reaches the iframe. In v4.0.1, requirements 6.4.3 (inventory and authorize payment-page scripts) and 11.6.1 (detect tampering of payment pages) target this.
In 2025 the PCI SSC revised SAQ A: those two requirements were removed from it, replaced by an eligibility criterion that the merchant confirms its site is not susceptible to script-based attacks. PCI SSC's FAQ indicates that implementing 6.4.3 and 11.6.1 is one way to meet that criterion. Practical controls: a strict Content-Security-Policy, Subresource Integrity, minimal third-party scripts on checkout, and change monitoring.
Read the source: PCI SSC blog on SAQ A updates.
Exercise: Scope assessment
Take an existing checkout (yours or a demo) and list every system in PCI scope. Propose changes to reach SAQ A eligibility, including a CSP for the checkout page.
Module 5: International payments and FX
Sell across borders: local methods, currencies, entities and settlement.
Currencies, FX and settlement
Separate three currencies in your design: presentment (what the customer sees), charge (what is authorized) and settlement (what you receive). Each conversion costs an FX spread. Decide who bears it and show prices in local currency where conversion matters.
Cross-border card transactions (issuer country ≠ acquirer country) usually cost more and decline more often. Local acquiring — through a local entity or a PSP with local licences — improves both. DCC at the point of sale has disclosure rules in some regions (e.g. the EU).
Bank-to-bank cross-border messaging now runs on ISO 20022, giving richer remittance data for reconciliation.
Local methods, entities and the MoR choice
Winning in a market usually means offering its local method: Pix in Brazil, UPI in India, mobile money in East Africa, e-wallets in Southeast Asia, SEPA and iDEAL-style bank payments in parts of Europe. Many of these require a local entity or a PSP that can contract locally.
For digital products, a merchant of record handles global tax and local acceptance for you, at a higher fee. Running your own PSP stack gives control and lower fees but makes you responsible for tax registration and compliance in each market.
Exercise: Market entry plan
Choose two new markets for a digital product. For each, identify the top local methods, whether you need a local entity, settlement currency options and the expected FX cost path. Recommend PSP vs MoR with reasons.
Module 6: Compliance landscape
Licensing, KYC/AML, consumer rules and data protection for payment products.
When does your product need a licence?
Accepting payments for your own sales through a licensed PSP rarely requires a licence. Things change when you hold or move other people's money: marketplaces paying sellers, wallets, remittances or lending. Depending on the country, that can require a payment-institution, e-money or money-transfer licence — or a structure where a licensed provider holds funds (e.g. connected-account models).
Regulators to know: central banks (e.g. the Central Bank of Kenya under the National Payment System Act), EU authorities under PSD2 (with PSD3/PSR agreed provisionally in November 2025 — check current status), and the FATF standards behind national AML/CFT laws.
Always confirm with local legal counsel; this hub is educational, not legal advice.
KYC, AML and data protection in practice
Platforms that onboard sellers must run KYC/KYB (often delegated to the PSP), screen against sanctions lists, monitor transactions and keep records. Payouts are where AML risk concentrates: hold new recipients, verify bank/wallet ownership, and watch for structuring.
Payment data is personal data: GDPR in the EU/UK, Kenya's Data Protection Act 2019, Nigeria's Data Protection Act 2023 and others govern retention, purpose and cross-border transfer. Store the minimum (tokens, last4, references), set retention periods, and document where data flows.
Exercise: Compliance map
For a marketplace that pays sellers in Kenya and Nigeria, draw who holds funds at each step and list the licences, KYC duties and data-protection obligations for you vs your provider.
Module 7: Security architecture
Threat-model payment flows and protect keys, webhooks and payouts.
Secrets, keys and least privilege
Payment credentials are bearer instruments for your money. Treat them so:
- Store in a secrets manager or encrypted env; never in repos, images or client apps.
- Separate keys per environment, service and entity; use restricted keys where offered.
- Rotate on a schedule and immediately on staff departures or leaks.
- Payout and refund capabilities live in a separate, more locked-down service with stronger approval.
Prefer short-lived OAuth tokens over long-lived keys where the provider supports both.
Threat-modelling a payment flow
Walk each step and ask what an attacker could change:
- Amount tampering in the browser → compute amounts server-side.
- Forged webhooks → verify signatures or re-query status.
- Replay of old callbacks → event-id deduplication and timestamp checks.
- IDOR on payment status endpoints → authorize by owner.
- Insider abuse of refunds/payouts → maker-checker approval and audit logs.
- SSRF/open redirects via return URLs → allowlist URLs from config.
Log security-relevant events, alert on anomalies (refund spikes, payout bursts) and rehearse key rotation.
Exercise: Threat model
Produce a STRIDE-style threat model for your checkout + webhook + refund flows with at least eight threats, each with a mitigation and an owner.