StackMonkey
Home / Templates / Payment System

Designing an Idempotent Payment Engine

Financial payment processing tolerates zero data loss and zero double charges. Learn how to design a fault-tolerant payment gateway with distributed idempotency keys, the Saga orchestration pattern, double-entry ledgers, and transactional outbox architectures.

Peak Settlement Rate
10,000 tx/s
Black Friday peak ingress
Financial Loss Tolerance
$0.00 SLA
Double-entry bookkeeping
Payment Execution
Effectively once
At-least-once delivery with idempotency keys
Confirmation SLA
< 500 ms
p99 synchronous capture
Step 1 of 4

Double-Entry Accounting & Integrity Invariants

Floating point numbers are forbidden in financial software due to IEEE-754 precision rounding errors ($0.1 + 0.2 \ne 0.3$). Every monetary quantity is stored as an exact 64-bit integer representing cents or micros.

Double-Entry Bookkeeping Principles

  • 1. Fundamental Equation: $\sum \text{Debits} = \sum \text{Credits}$ across every single transaction. Money is never created or destroyed; it is only transferred between accounts.
  • 2. Transaction Amplification: A single customer checkout of $50 involves 4 ledger entries: Debit Customer Card ($50), Credit Merchant Settlement ($48.50), Credit Platform Fee ($1.50). 10,000 tx/s requires 40,000 ledger balance mutations/sec.
  • 3. Immutable Append-Only Audit: Ledger lines are never `UPDATE`d or `DELETE`d. A refund creates new compensating ledger records, maintaining an unbroken audit trail for regulatory compliance.

Idempotency Key Protocol

  • 1. Client Key Injection: Every charge request carries an `Idempotency-Key: {UUIDv4}` HTTP header.
  • 2. Distributed Mutex Lock: On request arrival, the orchestrator acquires an atomic lease in Redis: SET lock:{idempotency_key} {worker_id} NX EX 60. If lock exists, concurrent duplicate requests wait or receive 409.
  • 3. Cached Response Cache: Once the payment settles, the full response body is cached in PostgreSQL against the unique idempotency key constraint for 24 hours. Retried calls return the identical 200 OK without re-charging the bank.
Step 2 of 4

Distributed 2-Phase Commit (2PC) vs. Orchestrated Saga Pattern

Why modern payment architectures abandon distributed two-phase commit locks across microservices in favor of asynchronous Saga orchestrators with compensating transactions.

Pattern Locking Mechanism Throughput Limit Failure Handling Production Recommendation
2-Phase Commit (2PC) Synchronous distributed DB locks < 500 tx/s (lock contention) Coordinator crash leaves database rows locked indefinitely; cascading thread death. Avoid in distributed architectures
Saga Orchestrator (Recommended) Local ACID DB transactions > 25,000 tx/s (lock-free) Compensating backward transactions (reversal / refund events) restore consistency. Standard for Stripe / Uber / Amazon

The Transactional Outbox Pattern

Writing to a database and publishing an event to Kafka in separate operations risks silent data corruption if the network fails between the two steps. The Transactional Outbox pattern writes both the business entity and the outgoing event into the same SQL database transaction. An asynchronous Change Data Capture (CDC) process (e.g. Debezium) streams outbox records into Apache Kafka with guaranteed at-least-once delivery.

Step 3 of 4

Bank Gateway Timeouts & The Zombie Charge Dilemma

When the upstream card network (Visa / Mastercard) times out, did the transaction succeed or fail? Discover how blind retries cause double billing.

The Network Timeout Paradox

The payment service sends a POST /charges request to the bank acquiring gateway. The bank successfully debits the customer's credit card for $100.

Before the HTTP response reaches our servers, a network route flap occurs. The socket times out after 3,000ms.

Our service marks the transaction as `FAILED_TIMEOUT` and the user taps "Try Again". If a new charge request is dispatched, the customer is billed twice ($200 total), generating immediate chargebacks, fines, and payment network penalties.

Production Resolution Protocol
  • Never Retry Blindly: When a bank gateway times out, transition the payment state to `PENDING_RECONCILIATION`.
  • Active Status Querying: A background worker polls the acquiring bank's `GET /charges?idempotency_key=xxx` API before triggering any reversal or new charge.
  • Nightly Settlement Matching: Parse bank settlement batch files (NACHA / ISO 20022) to reconcile ledger entries against actual bank fund transfers.
Step 4 of 4

Six-Component Payment Architecture Grid

The distributed topology guaranteeing zero loss, zero double-charges, and strict compliance.

01 · Idempotency Edge Filter
Envoy / Kong API Ingress
Validates cryptographic idempotency tokens, verifies payload signatures, and checks distributed locks in Redis before routing to payment services.
02 · Payment Saga Orchestrator
Temporal / Cadence State Engine
Coordinates multi-step payment workflows (Authorize → Capture → Ledger Record → Fulfillment). Automatically triggers compensating refunds if capture fails.
03 · Transactional Outbox + CDC
PostgreSQL + Debezium + Kafka
Atomic database transaction commits payment records and outbox events in a single step. Debezium streams events to Kafka with zero dual-write bugs.
04 · Acquiring Gateway Adapter
Multi-Bank Gateway Client
Connects to Visa, Mastercard, and Stripe APIs with smart retry circuits, mTLS encryption, and automatic failover between secondary bank acquirers.
05 · Double-Entry Ledger Store
CockroachDB / TigerBeetle
Immutable, append-only financial ledger enforcing balance invariants ($\sum \text{debits} = \sum \text{credits}$). Compliant with SOX and PCI-DSS Level 1.
06 · Reconciliation Batch Engine
Apache Spark Batch Workers
Runs automated nightly 3-way reconciliation matching internal ledger transactions against bank clearing files and processor payout statements.
Interactive Discrete Event Simulation

Simulate the Payment Engine Live

Test Saga compensating transactions, simulate bank gateway timeouts, and verify idempotency deduplication under aggressive concurrent retry attacks.