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.
balance
Zero-Sum Double-Entry
fingerprint
Idempotency-Key Lock
outbox
Transactional Outbox + CDC
undo
Immutable Saga Rollback
architecture
Act I · Scope & Back-of-the-Envelope Scale Math
Financial Invariants & Ledger Capacity Envelope
Step 1 of 5
balance
Immutable Double-Entry Journal: Every money movement writes balanced DEBIT and CREDIT legs where SUM(debits) == SUM(credits) —never UPDATE or DELETE past rows.
fingerprint
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.
outbox
Atomic Ledger + Event Emission (Zero Dual-Write): Commit domain events to outbox_events in the same DB transaction and stream via WAL CDC.
undo
Cross-Service Saga Rollbacks & T+0 Reconciliation: Reverse downstream card/fraud failures using compensating journal entries and continuously verify ledger sums.
lock
Strict Serializability / Optimistic Concurrency: Protect balances against race conditions using version CAS checks and deterministic account lock ordering to prevent deadlocks.
pin
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.
sync_alt
At-Least-Once Outbox + Idempotent Consumers: Downstream fulfillment workers deduplicate via a unique processed_events(event_id) table.
history_edu
7-Year Immutable Audit Trail: Range-partitioned append-only journal tables support regulatory audits and point-in-time balance reconstruction.
20K TPS
40K+ ledger rows/sec across paired DEBIT + CREDIT entries plus outbox rows.
Zero-Sum Invariant
balance
$0.00 Drift
int64 minor units; continuous assertion Σ Debits + Σ Credits == 0.
< 35 ms
Single-shard atomic tx: idempotency lock + balance CAS + 2 ledger legs + outbox.
18 TB / yr
Append-only monthly partitioned journal compressed & tiered to cold object store.
data_object
Act II · Wire Protocol & Ledger Storage Contracts
Idempotent Transfer API & Double-Entry SQL Schema
Step 2 of 5
hub
Act III · Interactive Payment & Saga Cluster Simulator
Double-Entry Ledger, WAL CDC & Saga Rollback Lab
LEDGER BALANCED
Ledger Invariant
balance
Σ = $0.00
Zero-sum verified
Double-Charges
fingerprint
0
Exact-once guarded
Outbox Lag
outbox
12 ms
WAL CDC slot healthy
Saga / Tx State
receipt_long
IN_FLIGHT
idem_9f8a2c
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
fingerprint
POST /TRANSFER
Loading payment simulator...
verified
Invariant active
Duplicate Retry Storm (3x Same Key)
OFF
Broker Down (CDC Backpressure)
OFF
Card Issuer 502 / Timeout
OFF
crisis_alert
Simulate Post-Commit Crash & Retry Storm
code
Act IV · Zero-Dependency Go Blueprints
Idiomatic Go Ledger Core & Production Stack Mapping
Auto-Synced to Simulator
layers
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
balance
Act V · Architectural Tradeoffs & Production SLOs
Fintech Design Tradeoffs & Reliability Targets
Step 5 of 5
pin
Tradeoff 01
Exact Math
Integer Minor Units vs. Floating-Point
check_circle int64 Minor Units
Stores cents or basis points as exact 64-bit integers ($150.00 = 15000 ) with deterministic arithmetic and fast CPU ALU ops.
tune 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.
lock
Tradeoff 02
Hot Accounts
Optimistic Locking vs. Hot-Account Contention
check_circle 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.
tune 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.
undo
Tradeoff 03
Cross-Service Tx
Distributed 2PC (XA) vs. Saga Pattern
check_circle Saga + Compensating Entries
Each service commits local ACID transactions fast; downstream failures execute reverse compensating ledger entries without holding global locks.
tune 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.
outbox
Tradeoff 04
Event Atomicity
App Dual-Write vs. Transactional Outbox + CDC
check_circle Outbox + WAL CDC
Ledger entries and outbox_events commit in one atomic DB transaction; WAL CDC relays events reliably even after pod crashes.
tune 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.
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