MODULE 06 · DISTRIBUTED TRANSACTIONS & FINTECH

Payment Ledger & Distributed Transactions

Architect zero-drift financial infrastructure using immutable double-entry accounting, exact-once idempotency keys, transactional outbox with WAL CDC, and Saga compensating rollbacks.

Zero-Sum Double-Entry Idempotency-Key Lock Transactional Outbox + CDC Immutable Saga Rollback
Act I · Scope & Back-of-the-Envelope Scale Math

Financial Invariants & Ledger Capacity Envelope

Step 1 of 5
Functional Guarantees
Accounting Core
  • Immutable Double-Entry Journal: Every money movement writes balanced DEBIT and CREDIT legs where SUM(debits) == SUM(credits)—never UPDATE or DELETE past rows.
  • Exact-Once Transfers via Idempotency-Key: Persist client keys + SHA-256 request hashes inside the same ACID transaction so network retries replay cached responses with 0 duplicate charges.
  • Atomic Ledger + Event Emission (Zero Dual-Write): Commit domain events to outbox_events in the same DB transaction and stream via WAL CDC.
  • Cross-Service Saga Rollbacks & T+0 Reconciliation: Reverse downstream card/fraud failures using compensating journal entries and continuously verify ledger sums.
Non-Functional Invariants
Strict ACID & Audit
  • Strict Serializability / Optimistic Concurrency: Protect balances against race conditions using version CAS checks and deterministic account lock ordering to prevent deadlocks.
  • Integer Minor Units (int64 Cents): Store all amounts as 64-bit integers in minor currency units ($150.00 = 15000)—zero IEEE-754 floating-point rounding drift.
  • At-Least-Once Outbox + Idempotent Consumers: Downstream fulfillment workers deduplicate via a unique processed_events(event_id) table.
  • 7-Year Immutable Audit Trail: Range-partitioned append-only journal tables support regulatory audits and point-in-time balance reconstruction.
Peak Payment TPS
20K TPS

40K+ ledger rows/sec across paired DEBIT + CREDIT entries plus outbox rows.

Zero-Sum Invariant
$0.00 Drift

int64 minor units; continuous assertion Σ Debits + Σ Credits == 0.

P99 ACID Commit
< 35 ms

Single-shard atomic tx: idempotency lock + balance CAS + 2 ledger legs + outbox.

7-Year Audit Log
18 TB / yr

Append-only monthly partitioned journal compressed & tiered to cold object store.

Act II · Wire Protocol & Ledger Storage Contracts

Idempotent Transfer API & Double-Entry SQL Schema

Step 2 of 5
Payment Transfer Wire Contract (POST /v1/payments/transfer)
Double-Entry & Outbox SQL Schema (PostgreSQL / ACID)
Act III · Interactive Payment & Saga Cluster Simulator

Double-Entry Ledger, WAL CDC & Saga Rollback Lab

LEDGER BALANCED
Step 1 / 6
Ledger Invariant
Σ = $0.00
Zero-sum verified
Double-Charges
0
Exact-once guarded
Outbox Lag
12 ms
WAL CDC slot healthy
Saga / Tx State
IN_FLIGHT
idem_9f8a2c
Payment Cluster Topology · Double-Entry & Idempotency
POST /TRANSFER
shopping_cart Client / Checkout Idempotency-Key: idem_9f8a2c POST /transfer ($150) 3x RETRY STORM fingerprint Payment API & Idem SHA-256 Hash · Lock Guard READY · STATELESS account_balance Ledger DB (ACID + Outbox) PostgreSQL · int64 Cents Alice (acct_alice) $500.00 Merchant (merch_01) $100.00 Hold / Pending Pool $0.00 Outbox Queue 0 pending Σ Delta = $0.00 · BALANCED sync_alt WAL CDC Relay Logical Replication Slot TAILING WAL · 12ms Zero Dual-Write Window hub Event Bus / Saga Orchestrator & Workers ONLINE · DEDUP READY processed_events Guard BROKER DOWN credit_card Card Network & Fraud External Issuer & ML Risk STANDBY · 200 OK Fraud Threshold < 0.50 502 DECLINED
POST /TRANSFER

Loading payment simulator...

Invariant active
Chaos Switchboard
0 Active
Terminal Event Console
Act IV · Zero-Dependency Go Blueprints

Idiomatic Go Ledger Core & Production Stack Mapping

Auto-Synced to Simulator
Production Stack Mapping Strip 6 Core Primitives
Agnostic Primitive Real-World Backend Systems Operational Role
ACID Double-Entry Ledger PostgreSQL / CockroachDB / TigerBeetle Append-only balanced debit/credit journal with strict serializability
Idempotency Key Store PostgreSQL Unique Index / Redis / DynamoDB Locks in-flight requests and caches committed responses by key + hash
Transactional Outbox CDC Debezium (Postgres WAL) / DynamoDB Streams Streams committed outbox rows asynchronously with zero dual-write gap
Saga Orchestrator Temporal / Cadence / AWS Step Functions Durable multi-step state machine executing reverse compensations
Event Streaming Bus Apache Kafka / Redpanda / Amazon Kinesis Durable partitioned transport delivering settlement & fulfillment events
T+0 Reconciliation Engine Apache Flink / Spark SQL / ClickHouse Continuously verifies ledger zero-sum & external bank settlement files
Act V · Architectural Tradeoffs & Production SLOs

Fintech Design Tradeoffs & Reliability Targets

Step 5 of 5
Tradeoff 01 Exact Math

Integer Minor Units vs. Floating-Point

int64 Minor Units

Stores cents or basis points as exact 64-bit integers ($150.00 = 15000) with deterministic arithmetic and fast CPU ALU ops.

IEEE-754 Float

Binary fractions cannot represent base-10 decimals (0.1 + 0.2 != 0.3), causing silent penny drift across millions of transfers.

Verdict Always store int64 minor units alongside explicit ISO-4217 currency codes; format decimals strictly at the presentation edge.
Tradeoff 02 Hot Accounts

Optimistic Locking vs. Hot-Account Contention

CAS + Sharded Sub-Accounts

Use version CAS for normal users; split mega-merchants into merch_01#0..#15 sub-accounts + async rollup to eliminate row lock bottlenecks.

Single-Row FOR UPDATE

Serializes every checkout on a single merchant row, collapsing throughput to <500 TPS during flash sales due to lock waits.

Verdict Combine ordered row locking / CAS for retail accounts with sharded sub-accounts for high-velocity platform/merchant accounts.
Tradeoff 03 Cross-Service Tx

Distributed 2PC (XA) vs. Saga Pattern

Saga + Compensating Entries

Each service commits local ACID transactions fast; downstream failures execute reverse compensating ledger entries without holding global locks.

Distributed 2PC (XA)

Holds database locks across slow external HTTP/card-network calls, causing cascading lock timeouts and blocking if the coordinator crashes.

Verdict Use Saga Orchestration across microservice/external-network boundaries and model pending holds explicitly in the ledger.
Tradeoff 04 Event Atomicity

App Dual-Write vs. Transactional Outbox + CDC

Outbox + WAL CDC

Ledger entries and outbox_events commit in one atomic DB transaction; WAL CDC relays events reliably even after pod crashes.

App Dual-Write

Writing DB then calling Kafka creates a fatal crash window: if the pod dies between calls, money moved but fulfillment never runs.

Verdict Never dual-write in payment systems—use Transactional Outbox + WAL CDC paired with idempotent consumers.
Production Observability SLOs
Financial Telemetry Targets
Ledger Balance Drift $0.00 Continuous invariant assertion
Duplicate Charge Rate 0.000% Idempotency key enforcement
Ledger Write P99 < 35 ms Single-shard ACID commit
Outbox CDC Lag P99 < 250 ms WAL tail to broker ACK