← All work

idempotent-payments-ledger

A small payments backend built around two guarantees: never charge twice, and never let the books stop balancing, even under concurrency, retries and a live schema migration.

25
threads race one key, one charge
300
Hypothesis ledger cases
17
tests
5
retries, then dead-letter

Exactly-once under real concurrency

A charge does not check whether a key was seen and then decide what to do; that check-then-act shape has a race window. Every attempt tries to insert an idempotency record first, and a UNIQUE constraint makes the database pick exactly one winner. Losers poll the winner's row and return its stored result.

The flagship test fires 25 threads at the same key behind a barrier, and asserts one transaction, one real charge, and 24 replays that return the same transaction id.

The books stay balanced

Hypothesis generates hundreds of random charge sequences and checks after each run that the double-entry ledger sums to exactly zero and no balance goes negative.

Two more things payments systems must get right

Webhook delivery that survives a flaky receiver, with exponential backoff and dead-lettering after 5 attempts. And a zero-downtime column rename using expand, backfill and dual-write, with a resumable backfill proven against a simulated crash.

Stack

Python · SQLAlchemy · SQLite / Postgres · Hypothesis · Pytest

Honest notes

It runs on SQLite with a lock around the connection because the sandbox had no Postgres; the guarantee comes from the UNIQUE constraint, not that lock. Webhook sending is injected rather than real HTTP, and there is no scheduled reconciliation job yet.