Skip to main content

Payment Platform

1. Executive Summary​

A payment platform processes money movement—charges, refunds, payouts—with correctness, auditability, and regulatory compliance paramount over raw throughput. Principal architects must design double-entry ledgers, idempotent APIs, PCI scope minimization, reconciliation with payment processors, and saga-based compensation for distributed transactions.

This chapter presents a reference architecture for a Stripe-class payment processor handling $50B annual volume with 99.99% correctness (no lost or duplicate money) and sub-second authorization latency. Double-entry ledger invariants, idempotent APIs, and nightly reconciliation are presented as non-negotiable safety properties distinct from liveness and availability concerns.

2. Why This Topic Matters​

Payment systems are among the highest-stakes distributed systems:

  • Money must balance — ledger invariants are non-negotiable.
  • External PSPs (payment service providers) are eventually consistent and retry-heavy.
  • Compliance — PCI-DSS, AML, regional regulations.
  • Idempotency — network retries must not double-charge.

Principal interviews and architecture reviews test whether candidates understand ledger design, not just "call Stripe API." Follow-up questions on ambiguous PSP timeouts and chargebacks after payout separate staff-level API knowledge from principal-level financial systems reasoning. Zero ledger imbalance tolerance should be stated explicitly in the first five minutes of the interview.

3. Problems Being Solved​

ProblemCapability
Accept paymentCard/wallet charge with auth/capture
Idempotent operationsSafe client retries
Ledger accountingDouble-entry immutable journal
Refunds / chargebacksCompensating transactions
Payouts to merchantsSettlement batching
ReconciliationMatch internal vs. PSP records
FraudRisk scoring; 3DS
CompliancePCI scope reduction; audit trail

4. Assumptions and System Model​

Phase 1: Clarify Requirements​

Functional:

  • CreatePayment(amount, currency, payment_method, idempotency_key).
  • Auth + capture (two-phase) or single charge.
  • Refund full/partial.
  • Merchant balance and settlement reports.
  • Webhooks to merchants on state changes.

Non-functional:

  • Correctness: zero duplicate charges; ledger always balances.
  • Authorization p99 < 500 ms.
  • Availability 99.99% for payment API.
  • Durability: no acknowledged payment lost.
  • Audit: immutable 7-year retention.

Non-goals: Build card network switches; cryptocurrency (separate).

AssumptionImplication
PSP handles card railsIntegrate Stripe/Adyen-class APIs
Retries inevitableIdempotency everywhere
Clock skewUse DB/ledger timestamps; not wall clock alone
Partial failuresSaga with compensation

5. Essential Terminology​

TermDefinition
PSPPayment Service Provider
Double-entry ledgerDebits = credits per transaction
AuthorizationHold funds; not yet captured
CaptureSettle authorized amount
Idempotency keyClient-supplied dedup token
PCI-DSSCard data security standard
TokenizationReplace PAN with vault token
ReconciliationMatch ledger to PSP settlement files
ChargebackDisputed reversal from issuer
SagaMulti-step txn with compensating actions
Exactly-once effectIdempotent retries achieve this semantically

6. Core Mechanism​

6.1 Phase 5: High-Level Architecture​

Figure 1: Payment platform—payment orchestration, append-only ledger, PSP integration, reconciliation loop.

6.2 Phase 3: Define APIs​

POST /v1/payments
Headers: Idempotency-Key: uuid
Body: { amount, currency, payment_method_token, merchant_id, capture: true|false }

POST /v1/payments/{id}/capture { amount? }
POST /v1/payments/{id}/refund { amount?, reason }
GET /v1/payments/{id}
GET /v1/merchants/{id}/balance
POST /v1/webhooks/psp (PSP callbacks)

States: created → processing → authorized → captured | failed | refunded | disputed.

6.3 Phase 4: Model Data​

payments: payment_id, idempotency_key (unique per merchant), merchant_id, amount, currency, status, psp_reference, created_at.

ledger_entries (append-only):

entry_idaccountdebitcreditpayment_idts
E1customer_cash1000P1...
E2merchant_payable097P1...
E3platform_fee03P1...

Invariant: Σ debits = Σ credits per currency per transaction.

idempotency_records: key, request_hash, response, expires_at.

merchant_accounts: balance derived from ledger materialized view.

6.4 Phase 6: Deep Dives​

Idempotent payment create:

  1. Check idempotency_records for key; if exists and hash matches → return stored response.
  2. If new: begin DB transaction.
  3. Insert payment processing; call PSP with idempotency header.
  4. On PSP success: append ledger entries; update status captured; commit.
  5. Store idempotency response; commit.
  6. Publish webhook via outbox.

Auth + capture (two-phase):

  • Auth: ledger hold (customer → auth_hold account).
  • Capture: move hold → merchant_payable; fee to platform.
  • Expire auth: release hold after 7 days.

Saga for refund:

  1. Initiate refund; status refunding.
  2. Call PSP refund API (idempotent).
  3. On success: compensating ledger entries (reverse merchant credit).
  4. On PSP failure: retry with backoff; manual ops if stuck.

Figure 2: Payment state machine—explicit transitions for ops and reconciliation.

PCI scope reduction:

  • Never store PAN; use PSP tokenization / Elements iframe.
  • Platform sees only tokens and last4.
  • CDE (cardholder data environment) minimized to PSP.

Reconciliation (nightly):

  1. Download PSP settlement file.
  2. Match by psp_reference to payments.
  3. Flag discrepancies: missing, amount mismatch, duplicate.
  4. Ops queue for manual resolution.

Figure 3: Idempotent charge with ledger write in same transaction boundary.

6.5 Fraud and 3DS​

Risk service scores transaction; high risk triggers 3DS challenge flow before PSP call. Decline before ledger mutation.

7. Step-by-Step Walkthrough​

7.1 Successful charge​

  1. Merchant POST $100 with idempotency key K1.
  2. Risk approves; PSP charges; ledger: debit customer $100, credit merchant $97, credit fee $3.
  3. Webhook payment.captured delivered with signed payload.

7.2 Duplicate retry​

  1. Merchant retries same K1 due to timeout.
  2. Idempotency record returns original 201—no second PSP call.

7.3 Chargeback after merchant payout​

  1. Customer disputes $500 charge 45 days post-capture.
  2. PSP debits platform; ledger creates negative merchant balance entry.
  3. Merchant balance -$200; future payouts held until positive.
  4. Ops workflow: evidence submission to card network; status disputed.
  5. Principal: chargebacks are async compensating events—design ledger for reversals.

7.4 Marketplace split payment​

  1. $100 purchase: $80 seller A, $15 seller B, $5 platform fee.
  2. Single PSP charge; ledger splits to three payable accounts.
  3. Payout batch nightly per seller; minimum payout threshold $25.
  4. Idempotency on entire payment—not per seller line.

7A. Design Phase Summary​

PhaseSectionKey decisions
Requirements§4charge, refund, ledger, recon
Scale§10shard ledger; PSP idempotency
APIs§6.2Idempotency-Key mandatory
Data model§6.3double-entry append-only
Architecture§6.1Payment → PSP + Ledger
Deep dives§6.4saga refund; recon
Reliability§8–9ambiguous PSP repair
Security§13PCI tokenization
Operations§12imbalance P0
Tradeoffs§16auth/capture; multi-PSP

8. Invariants and Guarantees​

PropertyTypeMechanism
Ledger balanceSafetyDouble-entry; DB constraints
No duplicate chargeSafetyIdempotency key + PSP idempotency
Durability after 201SafetySync replicate payment + ledger
Audit trailSafetyAppend-only ledger
LivenessProcessing completes or explicit failedReconciliation repair

9. Failure Scenarios​

ScenarioMitigation
PSP duplicate callbackIdempotent webhook handler
Ledger write fails after PSP successReconciliation repair; alert P0
Split brain idempotencyUnique constraint; transaction isolation
Currency FX roundingInteger minor units only
Chargeback after payoutNegative merchant balance; hold future payouts
Fraud attackRate limits; velocity checks
Outbox stuckRelay retry; DLQ

10. Performance Characteristics​

Phase 2: Estimate Scale​

$50B/year ≈ $1,580/sec average charge volume
Peak 10× → ~16K payments/sec
Ledger: 3 entries × 16K = 48K writes/sec → shard ledger by merchant_id
Storage: 500M txns/year × 1KB ≈ 500 GB/year ledger (compressed, tiered)
PSP latency dominates p99 (~200-400ms)
PathTarget
Create payment p99< 500 ms
Webhook delivery< 30 s
ReconciliationDaily batch + near-real-time alerts

11. Scalability Limits​

LimitMitigation
Ledger write rateShard by merchant; event sourcing
Hot merchantDedicated partition
PSP rate limitsQueue; multiple PSP accounts
Reconciliation file sizeStream parse; parallel match
Global currencyPer-currency ledger partitions

12. Operational Considerations​

Phase 9: Operations​

  • SLO: correctness incidents = 0 tolerance; availability 99.99%.
  • Dashboards: payment success rate, latency, reconciliation gap count.
  • Runbooks: stuck processing; manual refund; chargeback dispute.
  • On-call: P0 for ledger imbalance alert.
  • Freeze releases during settlement windows if required.

13. Security Considerations​

Phase 8: Security​

  • PCI: tokenization; network segmentation; annual audit.
  • API auth: merchant API keys + HMAC webhooks.
  • Encryption at rest for PII; KMS rotation.
  • AML/KYC for merchant onboarding (separate service).
  • Rate limiting; anomaly detection on refund volume.
  • Principle of least privilege for ops access to production.

14. Cost Considerations​

PSP interchange fees dominate (typically 2–3% card-present, higher CNP). Platform margin on application fee split. Ledger storage cheap relative to fraud losses and chargeback fees. Build vs. buy PSP integration: buy unless payment is strategic differentiator (marketplace, fintech core product).

Hidden costs: PCI audit scope, reconciliation ops headcount, dispute management, multi-currency FX spreads.

15A. Regulatory and Organizational Context​

Payment platforms require partnership with finance, legal, and compliance from architecture phase—not post-launch. AML/KYC for merchant onboarding, SAR filing workflows, and regional payment method support (iDEAL, UPI, etc.) shape service boundaries. Principal architects document which team owns ledger truth vs. PSP settlement truth and reconciliation SLAs between them.

21B. Extended Follow-Ups​

  1. Split payment between three sellers. — Multi-party ledger in single txn; payout scheduling per seller.
  2. PCI SAQ scope for microservices. — Network segmentation diagram; which services touch cardholder data environment.

15. Production Implementations​

SystemPattern
StripeIdempotent API; Connect for marketplaces
AdyenUnified acquiring
SquareIn-person + online ledger
PayPalWallet balance ledger

16. Alternatives and Tradeoffs​

Phase 10: Tradeoffs​

DecisionTradeoff
Single vs two-phase captureFlexibility vs complexity
Sync vs async captureLatency vs reliability
Event sourcing ledgerAudit vs query complexity
Multi-PSP routingResilience vs integration cost
Strong consistency everywhereLatency vs correctness (prefer correctness)

17. Common Misconceptions​

MisconceptionReality
"Float balance in payments table"Ledger is source of truth
"PSP success = done without ledger"Must be atomic or repairable
"UUID is enough idempotency"Need stored response + hash
"Refunds are trivial"Saga, timing, partial, FX
"We don't need reconciliation"PSP and internal always drift
"Float dollars in JSON is fine"Minor integer units only
"Webhook retry from merchant is enough"Platform must guarantee delivery attempt
"Refund = delete payment row"Append compensating ledger entries
"PCI is Infosec problem only"Data flow diagram is architecture deliverable

17A. Failure scenario drill​

PSP succeeds; app crashes before ledger commit—customer charged, merchant not credited. Detection: reconciliation next day; prevention: outbox or txn boundary including PSP idempotency key persistence before external call. P0 if widespread—principal designs ambiguous state handling before launch.

17B. Additional misconceptions​

MisconceptionReality
"Stripe handles ledger for you"Platform still needs internal books for marketplace splits
"Async capture simplifies UX"Auth hold expiry confuses users if not messaged clearly

18. Principal Architect Perspective​

  • Correctness before latency—always.
  • Idempotency is API contract, not implementation detail.
  • Ledger append-only—never update entries; only compensating entries.
  • Reconciliation is part of design, not back-office afterthought.
  • PCI scope decisions affect entire architecture.
  • Finance sign-off required on ledger schema changes—treat as regulated system.
  • No DELETE on ledger—cultural norm enforced in code review.

18.1 Incident severity model​

SeverityConditionResponse
P0Ledger imbalance detectedHalt captures; exec bridge
P1Reconciliation gap > $XOps manual match within 4h
P2Elevated processing stuckRun recon job; no user-visible if rare
P3Webhook delayRetry; merchant idempotent

Principal architects define dollar thresholds X with finance and document in on-call playbook.

19. Architecture Review Exercise​

Scenario: Team updates merchant_balance column without ledger on charge.

Review: Race conditions; audit failure; propose double-entry + derived balance.

20. Whiteboard Explanation​

"Merchants call our idempotent payment API. We check idempotency keys, score fraud, then call the PSP with their idempotency token. On success we append double-entry ledger rows in the same database transaction as the payment state update. Webhooks go through an outbox for reliable delivery. Nightly reconciliation matches PSP settlement files to our ledger. Refunds run as sagas with compensating ledger entries. We never store raw card numbers—only PSP tokens. Ledger imbalance is P0—halt captures until resolved."

21. Interview Questions​

  1. Design payment system for marketplace. — Signals: ledger, split, idempotency, PSP. Red flags: balance column update only.
  2. Double-entry ledger explain? — Signals: debits=credits, append-only. Follow-up: compensation entries.
  3. Idempotency implementation? — Signals: key store, PSP layer, recon. Red flags: UUID only.
  4. Auth vs capture? — Signals: two-phase, hold accounts. Red flags: conflate.
  5. Handle PSP timeout? — Signals: processing state, recon query. Red flags: retry charge blindly.
  6. Reconciliation process? — Signals: settlement file match, discrepancy queue. Red flags: skip.
  7. PCI scope reduction? — Signals: tokenization, no PAN. Red flags: store cards.
  8. Refund saga design? — Signals: compensating ledger, retry. Red flags: delete payment row.
  9. Prevent double charge? — Signals: idempotency at all layers. Red flags: hope.
  10. Chargeback handling? — Signals: negative balance, dispute workflow. Red flags: ignore post-payout.
  11. Multi-currency ledger? — Signals: per-currency balance, minor units. Red flags: float dollars.
  12. Webhook reliability? — Signals: outbox, merchant idempotency. Red flags: direct HTTP from request path.

22. Interview Follow-Ups​

  1. Split payment between sellers. — Marketplace Connect; multi-party ledger.
  2. Exactly-once webhook to merchant. — Outbox + merchant idempotency.
  3. $1M errant charge. — Compensation txn; incident process; regulatory notify.

22A. Production Low-Level Design (Interview + Game Day)​

Interview + ops bar per Production LLD and Game Day Standard. Whiteboard control plane (ledger/idempotency) vs money plane (PSP).

C4 context​

Step-by-step flow:

StepInteractionExplanation
1Merchant → APIIdempotent create; no second logical charge
2FraudSoft/hard decline before PSP spend
3PSPExternal money movement; own idempotency key
4LedgerDebits = credits; append-only
5–6OutboxReliable merchant notify
7–8Recon / OpsClose PSP ambiguity; P0 on imbalance

Production stack​

LayerAWS / genericPurpose
IngressAPI Gateway + WAFAuth, rate limits, mTLS for partners
Payment APIECS / EKSIdempotency + orchestration
StateAurora / PostgreSQLpayments, ledger_entries, idempotency_records
OutboxSame DB + relay → SQS/SNSWebhooks without dual-write loss
PSPStripe / AdyenCard rails; tokenization
SecretsSecrets Manager + KMSPSP keys; never log PAN
JobsEventBridge SchedulerStuck-processing sweeper; nightly recon
ObsCloudWatch + X-RayAuth latency, imbalance alerts

API contract (snippet)​

POST /v1/payments
Idempotency-Key: merch_ord_9f3a
Content-Type: application/json

{"amount":10000,"currency":"usd","method":"pm_tok_…","capture":"automatic"}

→ 200 {"payment_id":"pay_…","status":"succeeded","ledger_txn_id":"ltx_…"}
→ 200 (retry) same body — no second PSP call
→ 409 if same key, different body hash

Data model​

EntityKey fieldsNotes
idempotency_records(merchant_id, key) UNIQUEStored request hash + response
paymentspayment_id, status, psp_intent_idStates: created→processing→succeeded/failed
ledger_entriestxn_id, account, debit, credit, currencyAppend-only; Σ debit = Σ credit
webhook_outboxevent_id, payload, statusRelay until ACK

Happy-path sequence​

Step-by-step flow:

StepActionExplanation
1–2Gate on keyUnique constraint is the safety spine
3–4PSPMoney moves only after key reserved
5–6Atomic ledgerNever succeed API without balanced books
7–9ReplayRetries are free of double charge

Failure / idempotency (PSP timeout)​

Step-by-step flow:

StepFailureMitigation
1Client retriesSame Idempotency-Key → stored response
2PSP timeoutStay PROCESSING; never second charge
3Crash after PSP OKSweeper / recon completes ledger
4Ledger imbalanceP0 halt captures

SLOs (one-liner)​

SLOTarget (illustrative)How achieved
No duplicate charge0 for same idem keyUnique key + PSP key
Auth p99< 500 msTokenization; regional PSP
API availability99.99%Multi-AZ; degrade fraud soft
Ledger balanceAlwaysInvariant check + P0
Recon lag< 24 h (critical < 1 h)Settlement file + realtime query

22B. Game Day Playbooks​

Use in mock interviews (“what happens when…”) and ops drills. Pattern: inject → detect → mitigate → verify → learn.

Catalog​

#DrillFrequencyPrimary SLO under test
GD-1Duplicate Idempotency-Key stormMonthlyZero double charge
GD-2PSP 5xx / timeout floodQuarterlyPROCESSING resolve; no second charge
GD-3Ledger imbalance canaryQuarterlyP0 halt + comms
GD-4Webhook outbox backlogQuarterlyMerchant notify lag
GD-5Settlement file mismatchSemi-annualRecon queue drain
GD-6Partial region impairmentAnnualRTO / failover of API

GD-1 — Duplicate charge attempt​

Operator checklist: Confirm one psp_intent_id; Σ ledger balanced; no orphan PROCESSING.

GD-2 — PSP timeout ambiguity​

Pass criteria: Zero second PSP charges for same key; all aged PROCESSING terminal within SLA; customer/merchant status consistent with ledger.

23. Strong Answer Example​

Question: "How ensure no double charge on retry?"

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—Idempotency-Key + ledger commit + PSP key + reconciliation, not “use a database transaction and hope.”

Figure A: PRACTICE map — walk the board in this order.


Student interview script (PRACTICE)​

P — Problem framing​

"Network retries, mobile double-taps, and gateway timeouts make duplicate POST /payments inevitable. A naïve 'call PSP again' double-charges.

No double charge means: one logical merchant intent maps to at most one successful money movement and one balanced ledger txn. That requires a durable Idempotency-Key → response map, a PSP-side idempotency key, a PROCESSING state for ambiguity, and reconciliation when the network lies.

Short answer: Reserve the key first → call PSP with the same logical key → on success append double-entry ledger in one DB transaction → store response. Retries return the stored body. Timeouts stay PROCESSING until we query PSP by key—never invent a second charge."

Step-by-step flow:

StepPathInterview words
1NaiveMoney moves twice
2SafeKey is the safety spine

R — Requirements​

TypeRequirement
FRCharge / auth-capture / refund with stable payment_id
FRMerchant webhooks on terminal states
NFRZero duplicate charges for same idempotency key
NFRAuth p99 < 500 ms; API 99.99%
SafetyLedger Σ debit = Σ credit always
OpsNightly + realtime recon; P0 on imbalance

"I'd ask: marketplace splits? Auth vs capture? Which PSPs? PCI scope already tokenized?"

A — Assumptions​

AssumptionWhy it matters
PSP supports idempotency keysCloses their retry window
We never store PANSAQ reduction
At-least-once webhooksMerchant must be idempotent too
Clocks skewUse DB timestamps for PROCESSING age

"If they float a merchant_balance column without a ledger, I'd push back—that's not auditable money."

C — Capacity​

$50B/yr ÷ ~$50 AOV → ~32 txns/sec avg; 10× peak → ~320/sec
Ledger ~3 entries/txn → ~1K writes/sec peak — single primary OK early
Idempotency rows: 1 per logical op; TTL or archive after 24–72h
Bottleneck is PSP RTT 200–400 ms — parallelize fraud, not double-submit

T — Topology​

Happy path + retry:

I — Invariants​

"1. Same key + same body → same outcome. 2. Same key + different body → 409. 3. Never second PSP create for one key. 4. SUCCEEDED iff ledger balanced for that txn. 5. PROCESSING until PSP truth known."

C — Constraints​

ConstraintDesign response
PSP timeoutPROCESSING + query-by-key
Marketplace splitMulti-party ledger in one txn
PCITokenization / iframe; no PAN in logs
Refund after captureCompensating entries — never DELETE

E — Evolution​

PhaseDeliverable
M1Idempotency table + single PSP charge
M2Double-entry ledger + outbox webhooks
M3PROCESSING sweeper + recon job
M4Auth/capture + refund saga
M5Multi-PSP routing + chaos GD-1/GD-2

Closing line:

"I'd put Idempotency-Key in the contract, reserve it before PSP, append a balanced ledger on success, and resolve timeouts by querying the PSP—never by charging again. Reconciliation is part of the design, not a back-office afterthought."

Scoring signals​

StrongWeak / red flag
Key store + unique constraint"Use transactions and hope"
PSP idempotency + PROCESSINGBlind retry charge
Double-entry + reconFloat balance column
Outbox webhooksSync HTTP in request path
P0 imbalance halt"Finance will notice later"

Compact outline (2 min)​

"Idempotency-Key unique row → PSP with same logical key → ledger append on success → store response for retries → PROCESSING + recon on timeout → never second charge."

Whiteboard checklist​

  • Drew idempotency store before PSP
  • Named PROCESSING ambiguous state
  • Showed ledger debits = credits
  • Mentioned recon / sweeper
  • Said merchant webhooks via outbox

24. Weak Answer Example​

Weak: "Use transactions and hope for the best."

Red flags: No idempotency, no ledger, no reconciliation, no PSP ambiguity handling.

25. Hands-On Exercise​

  1. Build payment API with SQLite ledger (double-entry).
  2. Implement idempotency table.
  3. Mock PSP with random timeout; reconciliation job.
  4. Verify ledger always balances after tests.
  5. Extension: Partial refund saga with compensating entries.
  6. Extension: Reconciliation report CSV parser unit tests.

23A. Additional Strong Answer​

Q: Explain double-entry for $100 charge with $3 fee.

Outline: Debit customer_funds $100. Credit merchant_payable $97. Credit platform_revenue $3. Sum debits = sum credits. Refund uses compensating entries—never delete original rows. Merchant balance is derived from ledger, not floating column.

19A. Extended Review Scenario​

Scenario B: Worker charges PSP before DB transaction commits.

Review: Orphan charge if DB rolls back. Propose saga: reserve in DB, call PSP, commit ledger, or compensate on failure.

28B. Extended BOE Walkthrough (Interview Script)​

Interviewer: "$50B annual payment volume."

Strong candidate:

"$50B/year ÷ 31536000 sec ≈ $1,580/sec average money velocity—not same as txn count. If AOV $50 → ~32 txns/sec average, peak 10× → 320/sec—modest for ledger. If AOV $5 → 3200/sec peak—still shardable.

Ledger 3 entries per txn → 10K entries/sec peak—PostgreSQL may need sharding by merchant_id or event sourcing to Kafka.

Critical path latency is PSP network 200-400ms—optimize for correctness: idempotency keys, double-entry, reconciliation nightly + real-time anomaly on imbalance.

PCI: tokenization only—I never touch PAN. Webhooks via outbox. Refund saga with compensating entries, never DELETE from ledger."

26. Knowledge Check (extended)​

  1. What is a compensating ledger entry?
  2. Why processing state after PSP timeout?
  3. Name accounts in marketplace split.
  4. SAQ scope reduction technique?

27. Flashcards​

FrontBack
Idempotency-KeyDedup client retries
Double-entryDebits equal credits
CaptureSettle authorized funds
PCI tokenizationNo raw PAN storage
Auth holdLedger account for uncaptured funds
Settlement filePSP daily batch for reconciliation
Dispute workflowChargeback evidence and status
Minor unitsInteger cents—never float money
Marketplace splitMulti-party ledger from one charge
SAQ AReduced PCI scope with tokenization
Ambiguous processingPSP timeout pending state
Compensating entryReversal without deleting history
P0 ledger haltStop captures on imbalance detection

28. Cheat Sheet​

REQUIREMENTS: charge, refund, ledger, webhooks, reconciliation
SCALE: shard ledger; PSP idempotency; 16K+ txns/sec peak
APIs: POST /payments + Idempotency-Key; capture; refund
DATA: payments; append-only ledger_entries; idempotency_records
ARCH: Payment Svc → PSP + Ledger + Outbox
DEEP: saga refund; auth/capture; nightly recon
RELIABILITY: recon repair; stuck processing job
SECURITY: PCI tokenization; webhook HMAC
OPS: ledger imbalance P0; settlement windows
TRADEOFFS: sync capture vs async; multi-PSP

28A. Principal Interview Deep Dive​

Ledger invariants (formal)​

For all transactions t and currencies c:

Σ debit(t,c) = Σ credit(t,c)
Σ all entries in system (per c) = 0 (closed system with external PSP as boundary)

Violations trigger P0 halt on new captures until reconciled.

PSP ambiguity state machine​

processing + PSP unknown → query PSP by idempotency_key
→ succeeded: complete ledger
→ failed: mark failed
→ still unknown: remain processing; alert ops after T

Never create second PSP charge for same idempotency key.

Marketplace ledger accounts (example)​

AccountPurpose
customer_cashFunds from card
merchant_{id}_payableOwed to seller
platform_feeRevenue
psp_settlementClearing with PSP
chargeback_reserveRisk hold

Payout moves merchant_payable → merchant_paid via ACH batch.

PCI scope diagram (conceptual)​

[Browser PCI iframe] → [PSP]
Your API sees token only → in scope: SAQ A or reduced
Never: log raw PAN, never: store CVV

Principal owns data-flow diagram for annual QSA review.

30. References​

  • PCI-DSS v4.0 — compliance requirements (consult QSA).
  • Kleppmann, DDIA — transactions, exactly-once semantics.
  • Stripe API idempotency documentation — industry pattern.

Distinction: Ledger invariants are mathematical; PCI requirements are regulatory; PSP behaviors are vendor-specific.

30A. Further reading paths​

Essential companions: Sagas for refund flows, ACID and Isolation for txn boundaries, Security Architecture Fundamentals for PCI scoping workshops. Contrast money movement with Notification Platform—both need idempotency but payment has zero tolerance for ledger imbalance. Lab: write property test asserting Σ debits = Σ credits after random refund sequence.