Home / Notes / Idempotency in a ledger

· Python · Django · PostgreSQL

Idempotency keys and row locks in a double-entry ledger

A ledger has one job that cannot bend: money posted twice, or posted half, is a bug that someone eventually has to explain to an auditor. ledger-service is my reference implementation of that job over HTTP. These are the four decisions that carry most of the weight.

1. Every write takes an idempotency key

Networks retry. A client that times out cannot know whether its posting landed, so the only safe contract is one where sending the same request again does nothing new. Every write carries an Idempotency-Key, and the second arrival of a key returns the first result instead of posting again.

2. Concurrent postings serialize on row locks, in a fixed order

Two postings that touch the same accounts must not interleave. The service takes row locks on the accounts involved, always in the same order. A fixed order means two transactions can never each hold what the other wants, so there are no deadlocks and no retry loops to paper over them.

3. The database refuses an unbalanced transaction

Every transaction's entries must sum to zero in every currency. That rule is enforced by the database at commit, not only by application code, so a bug in a handler cannot persist a transaction that does not balance.

4. Events leave through an outbox, and a job checks the books

Downstream systems learn about postings through a transactional outbox: the event is written in the same transaction as the entries, so a crash cannot produce one without the other. Separately, a reconciliation job re-checks every invariant against the raw tables, because a guarantee you never verify is only a hope.

What I would tell my past self

← Back to the portfolio