A ledger that doesn't lose money.
This is a small API I wrote that moves money between accounts. Two things tend to go wrong with that: requests at the same time overwrite each other, and a retried request charges someone twice. I fixed both, and wrote tests that try to break it.
Problems & how they were addressed
Click any row in the table to watch the failure happen step by step, followed immediately by the implemented fix.
| Problem | What goes wrong | How I fixed it | Demo |
|---|---|---|---|
| Lost updates | Two concurrent withdrawals read the same starting balance and overwrite each other. | Row lock via select ... for update so the second transfer waits until the first commits. |
|
| Deadlock cycles | Alice pays Bob while Bob pays Alice; each locks one row and waits on the other forever. | Always lock the lower account id first (Math.min), so every request locks in the same order. |
|
| Duplicate retries | A dropped network reply makes the client retry a transfer that already went through. | Idempotency-Key header checked before running, returning the saved transfer on retry. |
|
| Same-instant duplicates | Two copies of the same request arrive together and both pass the initial lookup check. | Unique constraint on idempotency_key catches the race and returns the winner's row. |
|
| Rounding & balance drift | Decimals lose fractions of a cent, and updating a single column leaves no audit trail. | Store whole cents as Long and write paired -amount and +amount ledger entries. |
How it works
Every transfer goes through one method and runs in one database transaction.
POST /transfers Idempotency-Key: abc-123
│
▼
[ TransferController ] validates body and header
│
▼
[ TransferService ]
1. key already in db? ── yes ──► return the stored transfer
│ no
▼
2. begin transaction
3. lock account min(from, to) select ... for update
4. lock account max(from, to) select ... for update
5. balance >= amount? ── no ──► 400, rollback
6. debit, credit
7. insert transfer (unique idempotency_key)
8. insert ledger entry -amount, +amount
9. commit
│
▼ unique violation at step 7 or 9? read the winner's row
1. Double-entry records
Each transfer saves one row in transfers and two in ledger_entries, one negative and one positive. Amounts are whole cents stored in a Long, so no decimal rounding. If you add up every entry you always get zero.
2. Row locking
Reading a balance, checking it and saving it back is a race. findByIdForUpdate in AccountRepository uses @Lock(PESSIMISTIC_WRITE), which becomes select ... for update in SQL. If another transfer touches the same account, it waits until the first one is done.
@Lock(LockModeType.PESSIMISTIC_WRITE) @Query("select a from Account a where a.id = :id") Optional<Account> findByIdForUpdate(@Param("id") Long id);
3. Lock ordering
Locks can deadlock. If Alice sends to Bob while Bob sends to Alice, each one can grab a lock and wait for the other forever. The fix is simple: always lock the lower account id first. Everyone takes locks in the same order, so nobody ends up waiting in a circle.
Long firstId = Math.min(request.fromAccountId(), request.toAccountId()); Long secondId = Math.max(request.fromAccountId(), request.toAccountId()); Account first = accountRepository.findByIdForUpdate(firstId).orElseThrow(...); Account second = accountRepository.findByIdForUpdate(secondId).orElseThrow(...);
4. Idempotency
The client sends an Idempotency-Key header, and the transfers table has a unique constraint on it. I check for an existing transfer first, but two identical requests can both pass that check at the same time. So the database makes the final call: one insert works, the other throws a DataIntegrityViolationException, and I catch it and return the first transfer.
try { return transactionTemplate.execute(s -> executeTransfer(key, request)); } catch (DataIntegrityViolationException e) { // another thread saved this key first; return its result return transferRepository.findByIdempotencyKey(key) .map(TransferResponse::from) .orElseThrow(() -> e); }
What the tests check
There are 24 tests. The ones about concurrency run against a real PostgreSQL.
| Property | Test |
|---|---|
| No lost updates | ConcurrentTransferIntegrationTest: 50 transfers on a 16-thread pool |
| Total stays the same, no negative balances | Same class: 60 random transfers, 16 threads |
| One transfer per key | IdempotencyIntegrationTest: 10 parallel requests, same key |
| Balances and ledger entries | TransferIntegrationTest, TransferServiceTest |
| Validation and errors | Controller tests |
GitHub Actions runs all of them on every push, with a Postgres container.
API
| Endpoint | Description | Success |
|---|---|---|
POST /accounts | Create an account | 201 + Location |
GET /accounts/{id} | Read an account and its balance | 200 |
POST /transfers | Move money. Requires Idempotency-Key | 201 |
GET /health | Liveness check | 200 ok |
Errors come back as JSON. An unknown account is a 404. Not enough money, a missing header, the same account on both sides, or an amount of zero or less is a 400.
curl -X POST http://localhost:8080/transfers \ -H "Content-Type: application/json" \ -H "Idempotency-Key: 7f3c1e9a-0001" \ -d '{"fromAccountId": 1, "toAccountId": 2, "amountCents": 2500}'
Run it
You need Docker and Java 21. docker compose up -d starts Postgres, then ./mvnw spring-boot:run starts the app. To run the tests use ./mvnw clean test with the database running.