Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 39 ยท Projects and Practice

Project: Money Transfers with Locking and Retries

Build a money-transfer service step by step - invariants, optimistic versions, ordered pessimistic locks, retries and an audit ledger - and test it with concurrent threads.

Bank transfers are the classic concurrency exercise because the rules are strict: money must never be created or destroyed, balances must never go negative, and two transfers touching the same account must not interfere. In this project you design the service three ways (naive, optimistic, pessimistic), watch the naive one fail under load, and finish with a ledger that makes the books auditable.

Hibernate is not available in the browser, so the entity and service code is read-only. The runnable programs implement the same strategies on JDBC and H2 with real threads, so you can see correct and incorrect behaviour.

The domain and the invariants

Java
@Entity
public class Account {
    @Id Long id;
    @Column(nullable = false) long balanceCents;     // money in the smallest unit, never double
    @Version int version;

    void withdraw(long cents) {
        if (balanceCents < cents) throw new InsufficientFundsException(id);
        balanceCents -= cents;
    }
    void deposit(long cents) { balanceCents += cents; }
}

@Entity
public class LedgerEntry {                          // append-only, one row per movement
    @Id @GeneratedValue Long id;
    Long accountId; long deltaCents; Instant at; String transferId;
}

Invariants: the sum of all balances never changes during a transfer, and a balance never goes below zero (also enforced by a database check (balance_cents >= 0) as a second line of defence). Store money as integer cents or BigDecimal, never double.

Version 1: naive read-modify-write

Java
sessionFactory.inTransaction(s -> {
    Account from = s.find(Account.class, fromId);
    Account to = s.find(Account.class, toId);
    from.withdraw(cents);
    to.deposit(cents);
});

With no @Version and no lock, two transfers from the same account both read the same balance and the second overwrites the first (a lost update). The next program shows the effect with the same read-then-write steps.

Java The naive transfer loses money under concurrency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The final balance is almost always below 400, and the exact number changes between runs.

Version 2: optimistic locking with retries

With @Version the lost update becomes an OptimisticLockException; the service retries the whole transaction:

Java
public void transfer(long fromId, long toId, long cents) {
    retry(3, () -> sessionFactory.inTransaction(s -> {
        Account from = s.find(Account.class, fromId);
        Account to = s.find(Account.class, toId);
        from.withdraw(cents);
        to.deposit(cents);
        s.persist(new LedgerEntry(fromId, -cents, Instant.now(), transferId));
        s.persist(new LedgerEntry(toId, cents, Instant.now(), transferId));
    }));
}

This is correct and needs no database locks. For accounts with little contention it is the best choice. For a hot account (a merchant receiving thousands of payments per second) most attempts conflict, and the retries burn CPU.

Version 3: pessimistic locks in a fixed order

Java
public void transfer(long fromId, long toId, long cents) {
    long first = Math.min(fromId, toId), second = Math.max(fromId, toId);
    sessionFactory.inTransaction(s -> {
        Account a = s.find(Account.class, first, LockModeType.PESSIMISTIC_WRITE);
        Account b = s.find(Account.class, second, LockModeType.PESSIMISTIC_WRITE);
        Account from = a.id.equals(fromId) ? a : b;
        Account to = from == a ? b : a;
        from.withdraw(cents);
        to.deposit(cents);
        // ledger entries ...
    });
}

Locking the lower id first prevents the deadlock between "A to B" and "B to A" (see Retries, Deadlocks and Concurrency Patterns). Transactions queue instead of failing, which gives steady throughput for hot rows.

Version 4: atomic statements plus a ledger

The simplest correct code often avoids reading at all:

SQL
update account set balance = balance - :cents where id = :from and balance >= :cents
update account set balance = balance + :cents where id = :to

The first statement returns 0 rows if funds are insufficient; no lock is held longer than the two statements. Pair it with a ledger so every cent has a trail, and add a nightly check that sum(ledger) = sum(balances).

Java Atomic transfers with a ledger keep the books balanced

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Whatever the interleaving, the total stays 1500 and the ledger nets to zero.

Step: test and harden

  1. Write a test (see Testing Hibernate Code) that runs 200 random transfers on 8 threads and asserts that the sum is unchanged and no balance is negative.
  2. Add an idempotency key column transfer_id with a unique index, so a repeated request from a client that timed out returns the first result instead of moving money twice.
  3. Set a lock timeout so a stuck transaction fails fast.
  4. Decide per account type: optimistic for normal customers, pessimistic or atomic SQL for hot accounts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the naive read-modify-write transfer unsafe?

    Without a version or a lock the interleaving of reads and writes loses updates.
  2. 2. What does locking the lower account id first achieve?

    If every transaction takes locks in the same order, no cycle of waiting transactions can form.
  3. 3. Which is the best fit for a very hot account with thousands of concurrent updates?

    Optimistic conflicts would dominate; queuing or a single atomic statement scales better.
  4. 4. Why store money in cents or BigDecimal?

    double rounding errors accumulate; integers and BigDecimal are exact.

Summary

  • Define invariants first (total money constant, no negative balance) and enforce them in the database too.
  • Naive read-modify-write loses updates; @Version plus retries, ordered pessimistic locks, or atomic SQL fix it.
  • Choose per workload: optimistic for low contention, queued locks or atomic statements for hot rows.
  • Keep a ledger and an idempotency key so every movement is traceable and repeatable requests are safe.

Next: Hibernate Practice Questions