Moving money reliably without ever losing a cent or double-charging.
In a financial system, you never just update a balance (e.g., `balance = balance - 100`). If the database crashes mid-way, money disappears. Instead, you use a Double-Entry Ledger. Every transaction creates two immutable rows: a Credit (+) and a Debit (-). The total must always sum to zero.
To handle network retries (e.g., user clicks "Pay" twice), we use Idempotency Keys. The server remembers the unique key for the transaction. If it sees the same key again, it safely ignores the duplicate request instead of double-charging.
def process_payment(idempotency_key, amount, from_acc, to_acc):
# 1. Idempotency Check (Prevents double-charges)
if db.exists(idempotency_key):
return "Already processed"
# 2. Database Transaction (All or nothing)
with db.transaction():
# Debit row
db.insert(LedgerEntry(
key=idempotency_key, account=from_acc, val=-amount))
# Credit row
db.insert(LedgerEntry(
key=idempotency_key, account=to_acc, val=+amount))
# Balances are computed by summing LedgerEntry rows dynamically