Daniel Cohen·
Payment state machine with the idempotency guard that stops double charges on retry
Designs a robust payment processing system with multi-gateway support, idempotency, reconciliation, PCI compliance, and failure handling.
Payment System Architecture Design
You are a Principal Engineer who built payment systems at Stripe and Adyen. Design a comprehensive payment processing architecture.
**Business Model**: {{business_model}} (marketplace, subscription SaaS, e-commerce, usage-based billing)
**Payment Methods**: {{payment_methods}} (credit cards, ACH, digital wallets, BNPL, crypto, bank transfers)
**Geographic Scope**: {{geographic_scope}} (countries/currencies supported, local payment methods needed)
**Volume Targets**: {{volume_targets}} (TPS, monthly transaction volume, peak during sales events)
Design the complete payment system:
1. **Payment Flow Architecture** - Intent-based payment API, state machine (created → requires_action → processing → succeeded/failed), webhooks
2. **Payment Gateway Integration** - Primary (Stripe/Adyen/Braintree) + fallback gateway strategy, unified adapter pattern, smart routing
3. **PCI DSS Compliance** - Scope minimization using tokenization (never touch raw PAN), SAQ-A compliance, network segmentation
4. **Idempotency System** - Idempotency keys with 24-hour storage, replay detection, response caching for safe retry
5. **Card Vault Design** - Token storage with tokenization provider, network tokens (Visa VTS/Mastercard MDES), PCI scope analysis
6. **Subscription Engine** - Billing cycle management, proration logic, trial handling, dunning management (retry schedule: 1,3,5,7 days)
7. **Reconciliation System** - Daily automated reconciliation between gateway reports and internal ledger, discrepancy detection and alerts
8. **Fraud Detection** - Rule engine + ML model integration, 3D Secure 2.0, velocity checks, risk scoring pre-authorization
9. **Ledger & Accounting** - Double-entry bookkeeping, immutable transaction log, idempotent posting, multi-currency support
10. **Webhook System** - At-least-once delivery with signatures (HMAC-SHA256), exponential backoff retry, endpoint verification
11. **Reporting & Analytics** - Real-time payment metrics dashboard, settlement forecasting, chargeback ratio monitoring
12. **Dispute Management** - Chargeback workflow (retrieval request → representment), evidence collection automation, win rate tracking
13. **Disaster Recovery** - Gateway failover (automatic in <5 seconds), payment state recovery, incomplete transaction reconciliation
Include the payment state machine diagram and webhook payload schemas with verification pseudocode.
Ergebnisse
Payment architecture for a **subscription SaaS** (cards + SEPA, EU/US, ~200 TPS peak). Intent-based state machine, tokenization keeps you out of PCI scope, idempotency keys make retries safe.
**Payment state machine**
```
created ─▶ requires_action ─▶ processing ─▶ succeeded
│ │
└──────────────▶ failed ◀──────┘ (retryable vs terminal split)
```
**Idempotency** — the single most important safety net for money:
```typescript
async function charge(req: ChargeReq, key: string): Promise<Receipt> {
const cached = await idem.get(key); // 24h store
if (cached) return cached; // replay → same response, no double charge
const receipt = await gateway.charge(req);
await idem.put(key, receipt, "24h");
return receipt;
}
```
**PCI scope:** raw PANs never touch our servers — the client tokenizes with Stripe Elements, we store only the token, landing us at SAQ-A. **Gateway strategy:** Stripe primary, Adyen fallback behind a unified adapter; on a 5xx or timeout we fail over in < 5s. **Webhooks** are verified by HMAC-SHA256 and processed idempotently (events arrive at-least-once, sometimes out of order):
```json
{ "type": "payment_intent.succeeded", "id": "evt_9Kd",
"data": { "object": { "id": "pi_812", "amount": 4999 } } }
```
**Ledger:** double-entry, append-only, every posting idempotent. **Dunning** retries failed subscription charges on days 1/3/5/7 before cancellation. Daily reconciliation diffs the gateway report against our ledger and alerts on any mismatch.
Modell: Claude Opus 4
36 Likes10 SavesScore: 31
3 Kommentare
Lena Fischer·
Pasted, tweaked two lines, shipped. Love it.
Jonas Weber·
The abort/cleanup detail is underrated. Most people forget it and leak memory.
Priya Nair·
Genuinely better than the Stack Overflow answer I'd been copying.