Demonstration project / Design exercise /
Ledger Lab
A sample transaction ledger built around database constraints and reproducible integration tests.
Overview
Ledger Lab models transfers between fictional accounts. It is an educational case study about transaction boundaries and record invariants.
Problem and objectives
A transfer must either record both sides or record neither. Retrying a request after a lost response must return the previous result without creating a second transfer. Balance checks must hold when two requests arrive at the same time.
Technical approach
Use an immutable transfer record and two signed entries in a single transaction. Validate that amounts use integer minor units for the chosen currency. Lock the two account rows in canonical order to prevent the common deadlock where opposite-direction transfers take locks in reverse order.
SELECT id, balance_minor
FROM account
WHERE id IN ($1, $2)
ORDER BY id
FOR UPDATE;
Engineering challenges
Checking the balance before acquiring locks yields stale decisions. The implementation checks the balance inside the transaction after both locks are acquired. A unique request key resolves concurrent retries, and a stored request fingerprint distinguishes a replay from accidental key reuse.
Outcomes and lessons
The test design runs against PostgreSQL and compares concurrent results with ledger invariants. It checks that duplicate requests share a transfer identifier, concurrent debits respect the allowed balance, and a forced rollback leaves no partial transfer.
Use the storage engine that production depends on when a test needs to verify locking or isolation semantics.