← 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
random charge sequences, books balanced
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.

With 25 threads firing the same key behind a barrier, the result is one transaction, one real charge, and 24 replays that return the same transaction id.

The books stay balanced

Across hundreds of random charge sequences, 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

Next

A scheduled reconciliation job and real HTTP webhook delivery. The exactly-once guarantee comes from the database UNIQUE constraint, so it carries over unchanged from SQLite to Postgres.