I come at payments as someone who used to clear trades. My first question is never whether the money moved. It is when the money stops being able to move back.
Authorization is a promise. Settlement is cash. Finality lives at the end of the dispute window, up to 120 days on cards and 60 calendar days for consumer-unauthorized ACH returns. A marketplace that pays sellers on day 3 while holding 120 days of chargeback exposure is writing an uncovered put on the seller's solvency. The take rate is the premium, and the rolling reserve is margin.
Fintech Payment Rails Lab turns those mechanics into a paired vulnerable-and-fixed Python and SQLite benchmark (github.com/ghostintheprompt/fintech_payment_rails_lab) covering concurrency, refund business logic, tail-exposure math, and transaction monitoring.
How retries and refunds drain the ledger
Payment workers often check an in-memory seen_keys set or cache, run a balance check or external call, and record the idempotency key afterward (CWE-362). Two concurrent retries carrying the same idem_key both clear if idem_key in self.seen_keys before either writes back. In vulnerable/ledger.py, firing two threads at a $100.00 payout (10_000 cents) with identical keys posts twice and credits $200.00 to seller_01. Game developers recognize the pattern as an inventory duplication glitch. On a payout rail it drains the float.
Refund paths break for a related reason (CWE-840). When issue_refund accepts a destination instrument without binding to the original tender or tracking cumulative refunded cents, a caller can pay with a disputable card (card_visa_4242), push the refund out over ACH (bank_ach_9999), and submit a second refund past the settled total. Alongside those two ledger bugs, the lab models cash structuring just under the $10,000 Currency Transaction Report (CTR) threshold (31 U.S.C. 5324) and high-decline card-testing bursts.
Putting idempotency and tender checks inside the lock
Deduplicating on (amount, timestamp) fails in production because legitimate repeat orders share amounts and network retries carry fresh timestamps. In fixed/ledger.py, idempotency (idem_key TEXT PRIMARY KEY) lives inside the exact same SQLite BEGIN IMMEDIATE transaction as the integer-cent debit and credit statements. The losing thread hits sqlite3.IntegrityError, rolls back cleanly, and returns "replayed":
self.conn.execute("BEGIN IMMEDIATE")
self.conn.execute("INSERT INTO idempotency (idem_key) VALUES (?)", (idem_key,))
row = self.conn.execute(
"SELECT balance_cents FROM accounts WHERE account = ?", (from_acct,)
).fetchone()
Refunds lock the parent charge in the same transaction and verify both target_instrument == orig_instrument and refunded_cents + amount_cents <= orig_amount before moving a cent.
For reserve sizing, shared/exposure.py models dispute arrival with a truncated exponential cumulative distribution (tau=25.0, window=120). On $200,000/day of card volume at a 0.6% dispute rate paid out at T+3, $25,949.55 of open chargeback exposure sits uncollected in the tail; pushing payout to T+14 cuts that tail directly. On the detection side, detect/rule.py scores emitted JSONL logs with zero false positives across four rules: FIN-001 (duplicate committed idempotency key), FIN-002 (cross-instrument or over-refund), FIN-003 (three or more cash deposits in the $8,500 to $9,999 band within three days), and FIN-004 (card-testing velocity across distinct PANs and decline ratios).
Running the ledger against itself
Running make test executes all five concurrency, refund, tail-exposure, and JSONL detection checks offline against in-memory SQLite:
Scenario | Vulnerable | Fixed
--------------------------------------------------------------------
Concurrent TOCTOU Payout ($100) | $200.00 | $100.00
Cross-Instrument Refund Allowed | True | False
Open Chargeback Tail (T+3, $200k) | $25,949.55
Ran 5 tests in 0.153s (OK)
Everything runs locally on synthetic integer-cent accounts, with no connection to a live card network, Automated Clearing House (ACH) originating institution, or bank core.
GhostInThePrompt.com // Authorization is a promise. Finality is when the money cannot come back.